repo
string | commit
string | message
string | diff
string |
---|---|---|---|
dojo4/ey-cloud-recipes | f27ee3e25aeea55f42dc138ffbe5a442c5acf789 | Fixing cron job for postgresql | diff --git a/cookbooks/postgres/recipes/default.rb b/cookbooks/postgres/recipes/default.rb
index 44bbffc..93dd190 100644
--- a/cookbooks/postgres/recipes/default.rb
+++ b/cookbooks/postgres/recipes/default.rb
@@ -1,142 +1,142 @@
require 'pp'
#
# Cookbook Name:: postgres
# Recipe:: default
#
postgres_root = '/var/lib/postgresql'
postgres_version = '8.3'
directory '/db/postgresql' do
owner 'postgres'
group 'postgres'
mode '0755'
action :create
recursive true
end
link "setup-postgresq-db-my-symlink" do
to '/db/postgresql'
target_file postgres_root
end
execute "setup-postgresql-db-symlink" do
command "rm -rf /var/lib/postgresql; ln -s /data/postgresql /var/lib/postgresql"
action :run
only_if "if [ ! -L #{postgres_root} ]; then exit 0; fi; exit 1;"
end
execute "init-postgres" do
command "initdb -D #{postgres_root}/#{postgres_version}/data"
action :run
user 'postgres'
only_if "if [ ! -d #{postgres_root}/#{postgres_version}/data ]; then exit 0; fi; exit 1;"
end
execute "enable-postgres" do
command "rc-update add postgresql-#{postgres_version} default"
action :run
end
execute "restart-postgres" do
command "/etc/init.d/postgresql-#{postgres_version} restart"
action :run
not_if "/etc/init.d/postgresql-8.3 status | grep -q start"
end
gem_package "pg" do
action :install
end
template "/etc/.postgresql.backups.yml" do
owner 'root'
group 'root'
mode 0600
source "postgresql.backups.yml.erb"
variables({
:dbuser => node[:users].first[:username],
:dbpass => node[:users].first[:password],
:keep => node[:backup_window] || 14,
:id => node[:aws_secret_id],
:key => node[:aws_secret_key],
:env => node[:environment][:name]
})
end
#set backup interval
cron_hour = if node[:backup_interval].to_s == '24'
"1" # 0100 Pacific, per support's request
# NB: Instances run in the Pacific (Los Angeles) timezone
elsif node[:backup_interval]
"*/#{node[:backup_interval]}"
else
"1"
end
cron "eybackup" do
action :delete
end
-cron "eybackup -e postgresql" do
+cron "eybackup postgresql" do
minute '10'
hour cron_hour
day '*'
month '*'
weekday '*'
- command "eybackup"
+ command "eybackup -e postgresql"
not_if { node[:backup_window].to_s == '0' }
end
node[:applications].each do |app_name,data|
user = node[:users].first
db_name = "#{app_name}_#{node[:environment][:framework_env]}"
execute "create-db-user-#{user[:username]}" do
command "`psql -c '\\du' | grep -q '#{user[:username]}'`; if [ $? -eq 1 ]; then\n psql -c \"create user #{user[:username]} with encrypted password \'#{user[:password]}\'\"\nfi"
action :run
user 'postgres'
end
execute "create-db-#{db_name}" do
command "`psql -c '\\l' | grep -q '#{db_name}'`; if [ $? -eq 1 ]; then\n createdb #{db_name}\nfi"
action :run
user 'postgres'
end
execute "grant-perms-on-#{db_name}-to-#{user[:username]}" do
command "/usr/bin/psql -c 'grant all on database #{db_name} to #{user[:username]}'"
action :run
user 'postgres'
end
execute "alter-public-schema-owner-on-#{db_name}-to-#{user[:username]}" do
command "/usr/bin/psql #{db_name} -c 'ALTER SCHEMA public OWNER TO #{user[:username]}'"
action :run
user 'postgres'
end
template "/data/#{app_name}/shared/config/keep.database.yml" do
source "database.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:username => user[:username],
:app_name => app_name,
:db_pass => user[:password]
})
end
template "/data/#{app_name}/shared/config/database.yml" do
source "database.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:username => user[:username],
:app_name => app_name,
:db_pass => user[:password]
})
end
end
|
dojo4/ey-cloud-recipes | 386f9d47a3dc6ab996b903f7db03413fcd450979 | Fixing dbuser/dbpass in postgres recipe | diff --git a/cookbooks/postgres/recipes/default.rb b/cookbooks/postgres/recipes/default.rb
index 0ce3ee9..44bbffc 100644
--- a/cookbooks/postgres/recipes/default.rb
+++ b/cookbooks/postgres/recipes/default.rb
@@ -1,142 +1,142 @@
require 'pp'
#
# Cookbook Name:: postgres
# Recipe:: default
#
postgres_root = '/var/lib/postgresql'
postgres_version = '8.3'
directory '/db/postgresql' do
owner 'postgres'
group 'postgres'
mode '0755'
action :create
recursive true
end
link "setup-postgresq-db-my-symlink" do
to '/db/postgresql'
target_file postgres_root
end
execute "setup-postgresql-db-symlink" do
command "rm -rf /var/lib/postgresql; ln -s /data/postgresql /var/lib/postgresql"
action :run
only_if "if [ ! -L #{postgres_root} ]; then exit 0; fi; exit 1;"
end
execute "init-postgres" do
command "initdb -D #{postgres_root}/#{postgres_version}/data"
action :run
user 'postgres'
only_if "if [ ! -d #{postgres_root}/#{postgres_version}/data ]; then exit 0; fi; exit 1;"
end
execute "enable-postgres" do
command "rc-update add postgresql-#{postgres_version} default"
action :run
end
execute "restart-postgres" do
command "/etc/init.d/postgresql-#{postgres_version} restart"
action :run
not_if "/etc/init.d/postgresql-8.3 status | grep -q start"
end
gem_package "pg" do
action :install
end
template "/etc/.postgresql.backups.yml" do
owner 'root'
group 'root'
mode 0600
source "postgresql.backups.yml.erb"
variables({
- :dbuser => user[:username],
- :dbpass => user[:password],
+ :dbuser => node[:users].first[:username],
+ :dbpass => node[:users].first[:password],
:keep => node[:backup_window] || 14,
:id => node[:aws_secret_id],
:key => node[:aws_secret_key],
:env => node[:environment][:name]
})
end
#set backup interval
cron_hour = if node[:backup_interval].to_s == '24'
"1" # 0100 Pacific, per support's request
# NB: Instances run in the Pacific (Los Angeles) timezone
elsif node[:backup_interval]
"*/#{node[:backup_interval]}"
else
"1"
end
cron "eybackup" do
action :delete
end
cron "eybackup -e postgresql" do
minute '10'
hour cron_hour
day '*'
month '*'
weekday '*'
command "eybackup"
not_if { node[:backup_window].to_s == '0' }
end
node[:applications].each do |app_name,data|
user = node[:users].first
db_name = "#{app_name}_#{node[:environment][:framework_env]}"
execute "create-db-user-#{user[:username]}" do
command "`psql -c '\\du' | grep -q '#{user[:username]}'`; if [ $? -eq 1 ]; then\n psql -c \"create user #{user[:username]} with encrypted password \'#{user[:password]}\'\"\nfi"
action :run
user 'postgres'
end
execute "create-db-#{db_name}" do
command "`psql -c '\\l' | grep -q '#{db_name}'`; if [ $? -eq 1 ]; then\n createdb #{db_name}\nfi"
action :run
user 'postgres'
end
execute "grant-perms-on-#{db_name}-to-#{user[:username]}" do
command "/usr/bin/psql -c 'grant all on database #{db_name} to #{user[:username]}'"
action :run
user 'postgres'
end
execute "alter-public-schema-owner-on-#{db_name}-to-#{user[:username]}" do
command "/usr/bin/psql #{db_name} -c 'ALTER SCHEMA public OWNER TO #{user[:username]}'"
action :run
user 'postgres'
end
template "/data/#{app_name}/shared/config/keep.database.yml" do
source "database.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:username => user[:username],
:app_name => app_name,
:db_pass => user[:password]
})
end
template "/data/#{app_name}/shared/config/database.yml" do
source "database.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:username => user[:username],
:app_name => app_name,
:db_pass => user[:password]
})
end
end
|
dojo4/ey-cloud-recipes | 277ff094a12e97d7d91ba966e9ffa248fffee04f | Improving postgres recipes to handle backups and install necessary gems | diff --git a/cookbooks/postgres/recipes/default.rb b/cookbooks/postgres/recipes/default.rb
index c64bbd2..0ce3ee9 100644
--- a/cookbooks/postgres/recipes/default.rb
+++ b/cookbooks/postgres/recipes/default.rb
@@ -1,97 +1,142 @@
require 'pp'
#
# Cookbook Name:: postgres
# Recipe:: default
#
postgres_root = '/var/lib/postgresql'
postgres_version = '8.3'
directory '/db/postgresql' do
owner 'postgres'
group 'postgres'
mode '0755'
action :create
recursive true
end
link "setup-postgresq-db-my-symlink" do
to '/db/postgresql'
target_file postgres_root
end
execute "setup-postgresql-db-symlink" do
command "rm -rf /var/lib/postgresql; ln -s /data/postgresql /var/lib/postgresql"
action :run
only_if "if [ ! -L #{postgres_root} ]; then exit 0; fi; exit 1;"
end
execute "init-postgres" do
command "initdb -D #{postgres_root}/#{postgres_version}/data"
action :run
user 'postgres'
only_if "if [ ! -d #{postgres_root}/#{postgres_version}/data ]; then exit 0; fi; exit 1;"
end
execute "enable-postgres" do
command "rc-update add postgresql-#{postgres_version} default"
action :run
end
execute "restart-postgres" do
command "/etc/init.d/postgresql-#{postgres_version} restart"
action :run
not_if "/etc/init.d/postgresql-8.3 status | grep -q start"
end
+gem_package "pg" do
+ action :install
+end
+
+template "/etc/.postgresql.backups.yml" do
+ owner 'root'
+ group 'root'
+ mode 0600
+ source "postgresql.backups.yml.erb"
+ variables({
+ :dbuser => user[:username],
+ :dbpass => user[:password],
+ :keep => node[:backup_window] || 14,
+ :id => node[:aws_secret_id],
+ :key => node[:aws_secret_key],
+ :env => node[:environment][:name]
+ })
+end
+
+
+#set backup interval
+cron_hour = if node[:backup_interval].to_s == '24'
+ "1" # 0100 Pacific, per support's request
+ # NB: Instances run in the Pacific (Los Angeles) timezone
+ elsif node[:backup_interval]
+ "*/#{node[:backup_interval]}"
+ else
+ "1"
+ end
+
+cron "eybackup" do
+ action :delete
+end
+
+cron "eybackup -e postgresql" do
+ minute '10'
+ hour cron_hour
+ day '*'
+ month '*'
+ weekday '*'
+ command "eybackup"
+ not_if { node[:backup_window].to_s == '0' }
+end
+
node[:applications].each do |app_name,data|
user = node[:users].first
db_name = "#{app_name}_#{node[:environment][:framework_env]}"
execute "create-db-user-#{user[:username]}" do
command "`psql -c '\\du' | grep -q '#{user[:username]}'`; if [ $? -eq 1 ]; then\n psql -c \"create user #{user[:username]} with encrypted password \'#{user[:password]}\'\"\nfi"
action :run
user 'postgres'
end
execute "create-db-#{db_name}" do
command "`psql -c '\\l' | grep -q '#{db_name}'`; if [ $? -eq 1 ]; then\n createdb #{db_name}\nfi"
action :run
user 'postgres'
end
execute "grant-perms-on-#{db_name}-to-#{user[:username]}" do
command "/usr/bin/psql -c 'grant all on database #{db_name} to #{user[:username]}'"
action :run
user 'postgres'
end
execute "alter-public-schema-owner-on-#{db_name}-to-#{user[:username]}" do
command "/usr/bin/psql #{db_name} -c 'ALTER SCHEMA public OWNER TO #{user[:username]}'"
action :run
user 'postgres'
end
template "/data/#{app_name}/shared/config/keep.database.yml" do
source "database.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:username => user[:username],
:app_name => app_name,
:db_pass => user[:password]
})
end
template "/data/#{app_name}/shared/config/database.yml" do
source "database.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:username => user[:username],
:app_name => app_name,
:db_pass => user[:password]
})
end
+
end
diff --git a/cookbooks/postgres/templates/default/database.yml.erb b/cookbooks/postgres/templates/default/database.yml.erb
index f00f810..45d56e5 100644
--- a/cookbooks/postgres/templates/default/database.yml.erb
+++ b/cookbooks/postgres/templates/default/database.yml.erb
@@ -1,6 +1,6 @@
<%= @node[:environment][:framework_env] %>:
- adapter: postgres
+ adapter: postgresql
database: <%= @app_name %>_<%= @node[:environment][:framework_env] %>
username: <%= @username %>
password: <%= @db_pass %>
host: <%= @node[:db_host] %>
diff --git a/cookbooks/postgres/templates/default/postgresql.backup.yml.erb b/cookbooks/postgres/templates/default/postgresql.backup.yml.erb
new file mode 100644
index 0000000..003152e
--- /dev/null
+++ b/cookbooks/postgres/templates/default/postgresql.backup.yml.erb
@@ -0,0 +1,11 @@
+---
+:keep: <%= @keep %>
+:aws_secret_id: <%= @id %>
+:aws_secret_key: <%= @key %>
+:dbuser: <%= @dbuser %>
+:dbpass: <%= @dbpass %>
+:env: <%= @env %>
+:databases:
+<% @node[:applications].each_key do |app| %>
+<%= "- #{app}_#{@node[:environment][:framework_env]}" %>
+<% end %>
\ No newline at end of file
|
dojo4/ey-cloud-recipes | c95077f95e3273c55f615f37dfc9b84643021fe2 | Updating ssmtp recipe | diff --git a/cookbooks/ssmtp/recipes/default.rb b/cookbooks/ssmtp/recipes/default.rb
index 4959ff9..1cf856e 100644
--- a/cookbooks/ssmtp/recipes/default.rb
+++ b/cookbooks/ssmtp/recipes/default.rb
@@ -1,18 +1,26 @@
require 'pp'
#
# Cookbook Name:: ssmtp
# Recipe:: default
#
if ['solo', 'app', 'app_master'].include?(node[:instance_role])
directory "/etc/ssmtp" do
recursive true
action :delete
end
+ directory "/data/ssmtp" do
+ owner "root"
+ group "root"
+ mode "0755"
+ action :create
+ not_if "test -d /data/ssmtp"
+ end
+
link "/etc/ssmtp" do
to '/data/ssmtp'
end
end
|
dojo4/ey-cloud-recipes | 74dc9f401114988a59401b4f8c6022b064a9d66e | Adding simple ssmtp recipe | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 12fd9b0..bc15188 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,26 +1,29 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
# require_recipe "mbari-ruby"
# uncomment to turn on thinking sphinx
# require_recipe "thinking_sphinx"
# uncomment to turn on ultrasphinx
# require_recipe "ultrasphinx"
#uncomment to turn on memcached
# require_recipe "memcached"
#uncomment to run the authorized_keys recipe
#require_recipe "authorized_keys"
#uncomment to run the eybackup_slave recipe
-#require_recipe "eybackup_slave"
\ No newline at end of file
+#require_recipe "eybackup_slave"
+
+#uncomment to run the ssmtp recipe
+#require_recipe "ssmtp"
diff --git a/cookbooks/ssmtp/recipes/default.rb b/cookbooks/ssmtp/recipes/default.rb
new file mode 100644
index 0000000..4959ff9
--- /dev/null
+++ b/cookbooks/ssmtp/recipes/default.rb
@@ -0,0 +1,18 @@
+require 'pp'
+#
+# Cookbook Name:: ssmtp
+# Recipe:: default
+#
+
+if ['solo', 'app', 'app_master'].include?(node[:instance_role])
+
+ directory "/etc/ssmtp" do
+ recursive true
+ action :delete
+ end
+
+ link "/etc/ssmtp" do
+ to '/data/ssmtp'
+ end
+
+end
|
dojo4/ey-cloud-recipes | 72a59417cdad9225e8632f9247ebb8966a100e08 | Added eybackup_slave to backup the DB slave instead of the master | diff --git a/cookbooks/eybackup_slave/recipes/default.rb b/cookbooks/eybackup_slave/recipes/default.rb
new file mode 100644
index 0000000..05715cc
--- /dev/null
+++ b/cookbooks/eybackup_slave/recipes/default.rb
@@ -0,0 +1,28 @@
+#set backup interval
+cron_hour = if node[:backup_interval].to_s == '24'
+ "1" # 0100 Pacific, per support's request
+ # NB: Instances run in the Pacific (Los Angeles) timezone
+ elsif node[:backup_interval]
+ "*/#{node[:backup_interval]}"
+ else
+ "1"
+ end
+
+
+if ['db_master'].include?(node[:instance_role])
+ cron "eybackup" do
+ action :delete
+ end
+end
+
+if ['db_slave'].include?(node[:instance_role])
+ cron "eybackup" do
+ minute '10'
+ hour cron_hour
+ day '*'
+ month '*'
+ weekday '*'
+ command "eybackup"
+ not_if { node[:backup_window].to_s == '0' }
+ end
+end
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index e3b4964..12fd9b0 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,23 +1,26 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
# require_recipe "mbari-ruby"
# uncomment to turn on thinking sphinx
# require_recipe "thinking_sphinx"
# uncomment to turn on ultrasphinx
# require_recipe "ultrasphinx"
#uncomment to turn on memcached
# require_recipe "memcached"
#uncomment to run the authorized_keys recipe
#require_recipe "authorized_keys"
+
+#uncomment to run the eybackup_slave recipe
+#require_recipe "eybackup_slave"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | c45c2d7cac9b8765e5c662980031b8a4c3e5e71a | make run_for_app helper take multiple apps, add ruby_block helper | diff --git a/cookbooks/main/libraries/ruby_block.rb b/cookbooks/main/libraries/ruby_block.rb
new file mode 100644
index 0000000..aa0129a
--- /dev/null
+++ b/cookbooks/main/libraries/ruby_block.rb
@@ -0,0 +1,40 @@
+
+class Chef
+ class Resource
+ class RubyBlock < Chef::Resource
+ def initialize(name, collection=nil, node=nil)
+ super(name, collection, node)
+ @resource_name = :ruby_block
+ @action = :create
+ @allowed_actions.push(:create)
+ end
+
+ def block(&block)
+ if block
+ @block = block
+ else
+ @block
+ end
+ end
+ end
+ end
+end
+
+
+class Chef
+ class Provider
+ class RubyBlock < Chef::Provider
+ def load_current_resource
+ Chef::Log.debug(@new_resource.inspect)
+ true
+ end
+
+ def action_create
+ @new_resource.block.call
+ end
+ end
+ end
+end
+
+Chef::Platform.platforms[:default].merge! :ruby_block => Chef::Provider::RubyBlock
+
diff --git a/cookbooks/main/libraries/run_for_app.rb b/cookbooks/main/libraries/run_for_app.rb
index bc25eb7..46385fd 100644
--- a/cookbooks/main/libraries/run_for_app.rb
+++ b/cookbooks/main/libraries/run_for_app.rb
@@ -1,11 +1,12 @@
class Chef
class Recipe
- def run_for_app(app, &block)
+ def run_for_app(*apps, &block)
+ apps.map! {|a| a.to_s }
node[:applications].map{|k,v| [k,v] }.sort_by {|a,b| a }.each do |name, app_data|
- if name == app
+ if apps.include?(name)
block.call(name, app_data)
end
end
end
end
end
\ No newline at end of file
|
dojo4/ey-cloud-recipes | ba0dba10336db2cc5590a2205ea46d2978fd6ddb | removing authorized_keys recipe | diff --git a/cookbooks/authorized_keys/files/default/root.authorized_keys b/cookbooks/authorized_keys/files/default/root.authorized_keys
deleted file mode 100644
index a916a1a..0000000
--- a/cookbooks/authorized_keys/files/default/root.authorized_keys
+++ /dev/null
@@ -1 +0,0 @@
-ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAs1YlRb1Q00POkH1r9q9NwC2oph2ppEkhGG8X+c6uFrT3/5ArjJpDS/Px/ygJplwREukpFCc4ki4yXCt5zeQARuuvuw0madFfy6DT/O26CZeK2GotUxcJGgqXrSWSF5H/AC7y5QxTEtilwTw+vwEgvq3We1OvBtdJltxGhKw2a5y1rsxN5V6YA1bqD/wP/WuJ6PA40eAt9DzFAJLToLx9AYMGqu6lyjox30RamgbaHRIGfCppwr8xaRZy1FuzAN/CwvdT+lQlv0B/FRTeQrhzRPzEs3uNG6nq4V7iWKsYU+JkOy9XSgg68R6cU45kEOo7AYU+AVLApAd8FgjtxF/Pvw== [email protected]
diff --git a/cookbooks/authorized_keys/files/default/user.authorized_keys b/cookbooks/authorized_keys/files/default/user.authorized_keys
deleted file mode 100644
index e69de29..0000000
diff --git a/cookbooks/authorized_keys/recipes/default.rb b/cookbooks/authorized_keys/recipes/default.rb
deleted file mode 100644
index 34bbc3a..0000000
--- a/cookbooks/authorized_keys/recipes/default.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-require 'pp'
-#
-# Cookbook Name:: thinking_sphinx
-# Recipe:: default
-#
-
-remote_file "/home/#{node[:owner_name]}/.ssh/authorized_keys" do
- owner "root"
- group "root"
- mode 0600
- source "user.authorized_keys"
- backup false
- action :create
-end
-
-remote_file "/root/.ssh/authorized_keys" do
- owner node[:owner_name]
- group node[:owner_name]
- mode 0600
- source "root.authorized_keys"
- backup false
- action :create
-end
-
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 60978f5..e3b4964 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,23 +1,23 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
# require_recipe "mbari-ruby"
# uncomment to turn on thinking sphinx
# require_recipe "thinking_sphinx"
# uncomment to turn on ultrasphinx
# require_recipe "ultrasphinx"
#uncomment to turn on memcached
# require_recipe "memcached"
#uncomment to run the authorized_keys recipe
-require_recipe "authorized_keys"
+#require_recipe "authorized_keys"
|
dojo4/ey-cloud-recipes | 46b936137c09e365d6aed61ffe1a80c04a4b2a61 | adding authorized_keys recipe | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index ac1acd2..60978f5 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,20 +1,23 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
# require_recipe "mbari-ruby"
# uncomment to turn on thinking sphinx
# require_recipe "thinking_sphinx"
# uncomment to turn on ultrasphinx
# require_recipe "ultrasphinx"
#uncomment to turn on memcached
- require_recipe "authorized_keys"
+# require_recipe "memcached"
+
+#uncomment to run the authorized_keys recipe
+require_recipe "authorized_keys"
|
dojo4/ey-cloud-recipes | 29e45aa83af5e1b8c3a9b272d2c28ab0b35b6def | adding authorized_keys recipe | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index f39290f..ac1acd2 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,20 +1,20 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
# require_recipe "mbari-ruby"
# uncomment to turn on thinking sphinx
# require_recipe "thinking_sphinx"
# uncomment to turn on ultrasphinx
# require_recipe "ultrasphinx"
#uncomment to turn on memcached
-# require_recipe "memcached"
+ require_recipe "authorized_keys"
|
dojo4/ey-cloud-recipes | fc05f9d3e5956a25a8c3574e122415f54a47eb80 | adding authorized_keys recipe | diff --git a/cookbooks/authorized_keys/files/default/root.authorized_keys b/cookbooks/authorized_keys/files/default/root.authorized_keys
new file mode 100644
index 0000000..a916a1a
--- /dev/null
+++ b/cookbooks/authorized_keys/files/default/root.authorized_keys
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAs1YlRb1Q00POkH1r9q9NwC2oph2ppEkhGG8X+c6uFrT3/5ArjJpDS/Px/ygJplwREukpFCc4ki4yXCt5zeQARuuvuw0madFfy6DT/O26CZeK2GotUxcJGgqXrSWSF5H/AC7y5QxTEtilwTw+vwEgvq3We1OvBtdJltxGhKw2a5y1rsxN5V6YA1bqD/wP/WuJ6PA40eAt9DzFAJLToLx9AYMGqu6lyjox30RamgbaHRIGfCppwr8xaRZy1FuzAN/CwvdT+lQlv0B/FRTeQrhzRPzEs3uNG6nq4V7iWKsYU+JkOy9XSgg68R6cU45kEOo7AYU+AVLApAd8FgjtxF/Pvw== [email protected]
diff --git a/cookbooks/authorized_keys/files/default/user.authorized_keys b/cookbooks/authorized_keys/files/default/user.authorized_keys
new file mode 100644
index 0000000..e69de29
diff --git a/cookbooks/authorized_keys/recipes/default.rb b/cookbooks/authorized_keys/recipes/default.rb
new file mode 100644
index 0000000..34bbc3a
--- /dev/null
+++ b/cookbooks/authorized_keys/recipes/default.rb
@@ -0,0 +1,24 @@
+require 'pp'
+#
+# Cookbook Name:: thinking_sphinx
+# Recipe:: default
+#
+
+remote_file "/home/#{node[:owner_name]}/.ssh/authorized_keys" do
+ owner "root"
+ group "root"
+ mode 0600
+ source "user.authorized_keys"
+ backup false
+ action :create
+end
+
+remote_file "/root/.ssh/authorized_keys" do
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0600
+ source "root.authorized_keys"
+ backup false
+ action :create
+end
+
|
dojo4/ey-cloud-recipes | fe8722096bcc00ecc37c0695ce6f91a63944f7f6 | Updating readme for memcached | diff --git a/cookbooks/memcached/README.md b/cookbooks/memcached/README.md
index a7f9b5b..fb3baed 100644
--- a/cookbooks/memcached/README.md
+++ b/cookbooks/memcached/README.md
@@ -1,8 +1,11 @@
Memcached
===============
-A chef recipe for configuring distributed memcached on [EY Cloud]. This recipe is meant to allow memcached to accept remote connections and add all the servers in your EY Cloud cluser to the /data/<app_name>/shared/config/memcached.yml file.
-
+A chef recipe for configuring distributed memcached on [EY Cloud]. This recipe is meant to allow memcached to accept remote connections and add all the servers in your EY Cloud cluser to the `/data/<app_name>/shared/config/memcached.yml` file.
+To make use of this recipe you will also need to add a [deploy hook](https://cloud-support.engineyard.com/faqs/overview/getting-started-with-engine-yard-cloud#using_deploy_hooks) to your application to create a symlink for the memcached configuration. Just add a line like this to your `before_migrate.rb` hook:
+
+ run "ln -nfs #{shared_path}/config/memcached_custom.yml #{release_path}/config/memcached.yml"
+
[EY Cloud]: https://cloud.engineyard.com/extras
|
dojo4/ey-cloud-recipes | b6381c67b689bd35f5ceb55554e67deb929fecc9 | Allow memcached recipe to work with solo instances | diff --git a/cookbooks/memcached/recipes/default.rb b/cookbooks/memcached/recipes/default.rb
index 84da537..ca297d3 100644
--- a/cookbooks/memcached/recipes/default.rb
+++ b/cookbooks/memcached/recipes/default.rb
@@ -1,32 +1,32 @@
require 'pp'
#
# Cookbook Name:: memcached
# Recipe:: default
#
node[:applications].each do |app_name,data|
user = node[:users].first
case node[:instance_role]
- when "app", "app_master"
- template "/data/#{app_name}/shared/config/memcached.yml" do
+ when "solo", "app", "app_master"
+ template "/data/#{app_name}/shared/config/memcached_custom.yml" do
source "memcached.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:app_name => app_name,
:server_names => node[:members]
})
end
template "/etc/conf.d/memcached" do
owner 'root'
group 'root'
mode 0644
source "memcached.erb"
variables :memusage => 64,
:port => 11211
end
end
end
diff --git a/cookbooks/memcached/templates/default/memcached.yml.erb b/cookbooks/memcached/templates/default/memcached.yml.erb
index f8db3b7..18088dd 100644
--- a/cookbooks/memcached/templates/default/memcached.yml.erb
+++ b/cookbooks/memcached/templates/default/memcached.yml.erb
@@ -1,26 +1,27 @@
defaults:
ttl: 1800
readonly: false
urlencode: false
c_threshold: 10000
compression: true
debug: false
namespace: <%= @app_name %>
sessions: false
session_servers: false
fragments: true
memory: 64
servers: localhost:11211
benchmarking: true
raise_errors: true
fast_hash: false
fastest_hash: false
<%= @node[:environment][:framework_env] %>:
memory: 64
benchmarking: false
sessions: false
fragments: true
+ <% unless @server_names.nil? %>
servers:
- - <%= @server_names.join(":11211\n - ") %>:11211
-
+ - <%= @server_names.join(":11211\n - ") %>:11211
+ <% end %>
|
dojo4/ey-cloud-recipes | 96998f811235de9baae0fea04f7dfff0e1d74961 | Do not auto-generate symlink for memcached | diff --git a/cookbooks/memcached/recipes/default.rb b/cookbooks/memcached/recipes/default.rb
index 3b6e829..84da537 100644
--- a/cookbooks/memcached/recipes/default.rb
+++ b/cookbooks/memcached/recipes/default.rb
@@ -1,36 +1,32 @@
require 'pp'
#
# Cookbook Name:: memcached
# Recipe:: default
#
node[:applications].each do |app_name,data|
user = node[:users].first
case node[:instance_role]
when "app", "app_master"
template "/data/#{app_name}/shared/config/memcached.yml" do
source "memcached.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:app_name => app_name,
:server_names => node[:members]
})
end
- link "/data/#{app_name}/current/config/memcached.yml" do
- to "/data/#{app_name}/shared/config/memcached.yml"
- end
-
template "/etc/conf.d/memcached" do
owner 'root'
group 'root'
mode 0644
source "memcached.erb"
variables :memusage => 64,
:port => 11211
end
end
end
|
dojo4/ey-cloud-recipes | e7e42185a7c6ea18950e05f5bf89a46f77fcef0e | Fixing memory setting for memcached | diff --git a/cookbooks/memcached/recipes/default.rb b/cookbooks/memcached/recipes/default.rb
index db3dbad..3b6e829 100644
--- a/cookbooks/memcached/recipes/default.rb
+++ b/cookbooks/memcached/recipes/default.rb
@@ -1,36 +1,36 @@
require 'pp'
#
# Cookbook Name:: memcached
# Recipe:: default
#
node[:applications].each do |app_name,data|
user = node[:users].first
case node[:instance_role]
when "app", "app_master"
template "/data/#{app_name}/shared/config/memcached.yml" do
source "memcached.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:app_name => app_name,
:server_names => node[:members]
})
end
link "/data/#{app_name}/current/config/memcached.yml" do
to "/data/#{app_name}/shared/config/memcached.yml"
end
template "/etc/conf.d/memcached" do
owner 'root'
group 'root'
mode 0644
source "memcached.erb"
- variables :memusage => 512,
+ variables :memusage => 64,
:port => 11211
end
end
end
diff --git a/cookbooks/memcached/templates/default/memcached.erb b/cookbooks/memcached/templates/default/memcached.erb
index 950a6ab..91b9ebb 100644
--- a/cookbooks/memcached/templates/default/memcached.erb
+++ b/cookbooks/memcached/templates/default/memcached.erb
@@ -1,32 +1,32 @@
# Copyright 2003 Gentoo Technologies, Inc
# $Header: /var/cvsroot/gentoo-x86/net-misc/memcached/files/1.2.6/conf,v 1.1 2008/08/01 15:56:55 caleb Exp $
# memcached config file
MEMCACHED_BINARY="/usr/bin/memcached"
#Specify memory usage in megabytes (do not use letters)
#64MB is default
-MEMUSAGE="64"
+MEMUSAGE="<%= @memusage %>"
#User to run as
MEMCACHED_RUNAS="memcached"
#Specify maximum number of concurrent connections
#1024 is default
MAXCONN="1024"
#Listen for connections on what address?
# If this is empty, memcached will listen on 0.0.0.0
# be sure you have a firewall in place!
LISTENON="0.0.0.0"
#Listen for connections on what port?
PORT="<%= @port %>"
#PID file location
# '-${PORT}.${CONF}.pid' will be appended to this!
# You do not normally need to change this.
PIDBASE="/var/run/memcached/memcached"
#Other Options
MISC_OPTS=""
|
dojo4/ey-cloud-recipes | eaae5bb4356a101abb4acb817efc4f36bdb7ab1e | Moving memcached.yml to shared/config | diff --git a/cookbooks/memcached/recipes/default.rb b/cookbooks/memcached/recipes/default.rb
index eea0657..db3dbad 100644
--- a/cookbooks/memcached/recipes/default.rb
+++ b/cookbooks/memcached/recipes/default.rb
@@ -1,32 +1,36 @@
require 'pp'
#
# Cookbook Name:: memcached
# Recipe:: default
#
node[:applications].each do |app_name,data|
user = node[:users].first
case node[:instance_role]
when "app", "app_master"
- template "/data/#{app_name}/current/config/memcached.yml" do
+ template "/data/#{app_name}/shared/config/memcached.yml" do
source "memcached.yml.erb"
owner user[:username]
group user[:username]
mode 0744
variables({
:app_name => app_name,
:server_names => node[:members]
})
end
+
+ link "/data/#{app_name}/current/config/memcached.yml" do
+ to "/data/#{app_name}/shared/config/memcached.yml"
+ end
template "/etc/conf.d/memcached" do
owner 'root'
group 'root'
mode 0644
source "memcached.erb"
variables :memusage => 512,
:port => 11211
end
end
end
|
dojo4/ey-cloud-recipes | 1852dabe885e95205ae85221c5454003127ee643 | setting memeory back down to a default of 64M | diff --git a/cookbooks/memcached/templates/default/memcached.erb b/cookbooks/memcached/templates/default/memcached.erb
index 8f5a1e4..950a6ab 100644
--- a/cookbooks/memcached/templates/default/memcached.erb
+++ b/cookbooks/memcached/templates/default/memcached.erb
@@ -1,32 +1,32 @@
# Copyright 2003 Gentoo Technologies, Inc
# $Header: /var/cvsroot/gentoo-x86/net-misc/memcached/files/1.2.6/conf,v 1.1 2008/08/01 15:56:55 caleb Exp $
# memcached config file
MEMCACHED_BINARY="/usr/bin/memcached"
#Specify memory usage in megabytes (do not use letters)
#64MB is default
-MEMUSAGE="512"
+MEMUSAGE="64"
#User to run as
MEMCACHED_RUNAS="memcached"
#Specify maximum number of concurrent connections
#1024 is default
MAXCONN="1024"
#Listen for connections on what address?
# If this is empty, memcached will listen on 0.0.0.0
# be sure you have a firewall in place!
LISTENON="0.0.0.0"
#Listen for connections on what port?
PORT="<%= @port %>"
#PID file location
# '-${PORT}.${CONF}.pid' will be appended to this!
# You do not normally need to change this.
PIDBASE="/var/run/memcached/memcached"
#Other Options
MISC_OPTS=""
diff --git a/cookbooks/memcached/templates/default/memcached.yml.erb b/cookbooks/memcached/templates/default/memcached.yml.erb
index 391d91a..f8db3b7 100644
--- a/cookbooks/memcached/templates/default/memcached.yml.erb
+++ b/cookbooks/memcached/templates/default/memcached.yml.erb
@@ -1,26 +1,26 @@
defaults:
ttl: 1800
readonly: false
urlencode: false
c_threshold: 10000
compression: true
debug: false
namespace: <%= @app_name %>
sessions: false
session_servers: false
fragments: true
- memory: 512
+ memory: 64
servers: localhost:11211
benchmarking: true
raise_errors: true
fast_hash: false
fastest_hash: false
<%= @node[:environment][:framework_env] %>:
- memory: 512
+ memory: 64
benchmarking: false
sessions: false
fragments: true
servers:
- <%= @server_names.join(":11211\n - ") %>:11211
|
dojo4/ey-cloud-recipes | 7990f9637cccbedfbfc80d221e0a0de8533c08ff | fixing namespace in memcached.yml | diff --git a/cookbooks/memcached/templates/default/memcached.yml.erb b/cookbooks/memcached/templates/default/memcached.yml.erb
index 26325c2..391d91a 100644
--- a/cookbooks/memcached/templates/default/memcached.yml.erb
+++ b/cookbooks/memcached/templates/default/memcached.yml.erb
@@ -1,26 +1,26 @@
defaults:
ttl: 1800
readonly: false
urlencode: false
c_threshold: 10000
compression: true
debug: false
- namespace: playmesh
+ namespace: <%= @app_name %>
sessions: false
session_servers: false
fragments: true
memory: 512
servers: localhost:11211
benchmarking: true
raise_errors: true
fast_hash: false
fastest_hash: false
<%= @node[:environment][:framework_env] %>:
memory: 512
benchmarking: false
sessions: false
fragments: true
servers:
- <%= @server_names.join(":11211\n - ") %>:11211
|
dojo4/ey-cloud-recipes | 188f50ecbc023db7af085c4e01a69bd55adff245 | adding memcached recipe | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 58377d0..f39290f 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,18 +1,20 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
# require_recipe "mbari-ruby"
# uncomment to turn on thinking sphinx
# require_recipe "thinking_sphinx"
# uncomment to turn on ultrasphinx
# require_recipe "ultrasphinx"
+#uncomment to turn on memcached
+# require_recipe "memcached"
diff --git a/cookbooks/memcached/README.md b/cookbooks/memcached/README.md
new file mode 100644
index 0000000..a7f9b5b
--- /dev/null
+++ b/cookbooks/memcached/README.md
@@ -0,0 +1,8 @@
+Memcached
+===============
+
+A chef recipe for configuring distributed memcached on [EY Cloud]. This recipe is meant to allow memcached to accept remote connections and add all the servers in your EY Cloud cluser to the /data/<app_name>/shared/config/memcached.yml file.
+
+
+
+[EY Cloud]: https://cloud.engineyard.com/extras
diff --git a/cookbooks/memcached/recipes/default.rb b/cookbooks/memcached/recipes/default.rb
new file mode 100644
index 0000000..eea0657
--- /dev/null
+++ b/cookbooks/memcached/recipes/default.rb
@@ -0,0 +1,32 @@
+require 'pp'
+#
+# Cookbook Name:: memcached
+# Recipe:: default
+#
+
+node[:applications].each do |app_name,data|
+ user = node[:users].first
+
+case node[:instance_role]
+ when "app", "app_master"
+ template "/data/#{app_name}/current/config/memcached.yml" do
+ source "memcached.yml.erb"
+ owner user[:username]
+ group user[:username]
+ mode 0744
+ variables({
+ :app_name => app_name,
+ :server_names => node[:members]
+ })
+ end
+
+ template "/etc/conf.d/memcached" do
+ owner 'root'
+ group 'root'
+ mode 0644
+ source "memcached.erb"
+ variables :memusage => 512,
+ :port => 11211
+ end
+ end
+end
diff --git a/cookbooks/memcached/templates/default/memcached.erb b/cookbooks/memcached/templates/default/memcached.erb
new file mode 100644
index 0000000..8f5a1e4
--- /dev/null
+++ b/cookbooks/memcached/templates/default/memcached.erb
@@ -0,0 +1,32 @@
+# Copyright 2003 Gentoo Technologies, Inc
+# $Header: /var/cvsroot/gentoo-x86/net-misc/memcached/files/1.2.6/conf,v 1.1 2008/08/01 15:56:55 caleb Exp $
+# memcached config file
+
+MEMCACHED_BINARY="/usr/bin/memcached"
+
+#Specify memory usage in megabytes (do not use letters)
+#64MB is default
+MEMUSAGE="512"
+
+#User to run as
+MEMCACHED_RUNAS="memcached"
+
+#Specify maximum number of concurrent connections
+#1024 is default
+MAXCONN="1024"
+
+#Listen for connections on what address?
+# If this is empty, memcached will listen on 0.0.0.0
+# be sure you have a firewall in place!
+LISTENON="0.0.0.0"
+
+#Listen for connections on what port?
+PORT="<%= @port %>"
+
+#PID file location
+# '-${PORT}.${CONF}.pid' will be appended to this!
+# You do not normally need to change this.
+PIDBASE="/var/run/memcached/memcached"
+
+#Other Options
+MISC_OPTS=""
diff --git a/cookbooks/memcached/templates/default/memcached.yml.erb b/cookbooks/memcached/templates/default/memcached.yml.erb
new file mode 100644
index 0000000..26325c2
--- /dev/null
+++ b/cookbooks/memcached/templates/default/memcached.yml.erb
@@ -0,0 +1,26 @@
+defaults:
+ ttl: 1800
+ readonly: false
+ urlencode: false
+ c_threshold: 10000
+ compression: true
+ debug: false
+ namespace: playmesh
+ sessions: false
+ session_servers: false
+ fragments: true
+ memory: 512
+ servers: localhost:11211
+ benchmarking: true
+ raise_errors: true
+ fast_hash: false
+ fastest_hash: false
+
+<%= @node[:environment][:framework_env] %>:
+ memory: 512
+ benchmarking: false
+ sessions: false
+ fragments: true
+ servers:
+ - <%= @server_names.join(":11211\n - ") %>:11211
+
|
dojo4/ey-cloud-recipes | 417fdd5e8c2dec4324f65097ebd9e3d5861acebf | Added fledgeling jruby recipe. It still needs some love -- to much has to be manually configured right now. | diff --git a/cookbooks/jruby/recipes/default.rb b/cookbooks/jruby/recipes/default.rb
new file mode 100644
index 0000000..24eb2a9
--- /dev/null
+++ b/cookbooks/jruby/recipes/default.rb
@@ -0,0 +1,102 @@
+#
+# Cookbook Name:: jruby
+# Recipe:: default
+#
+
+package "dev-java/sun-jdk" do
+ action :install
+end
+
+package "dev-java/jruby-bin" do
+ action :install
+end
+
+execute "install-glassfish" do
+ command "/usr/bin/jruby -S gem install glassfish"
+end
+
+#####
+#
+# Edit this to point to YOUR app's directory
+#
+#####
+
+APP_DIRECTORY = '/data/hello_world/current'
+
+#####
+#
+# These are generic tuning parameters for each instance size; you may want to further tune them for
+# your application's specific needs if they prove inadequate.
+# In particular, if you have a thread-safe application, you will _definitely_ only want a single
+# runtime.
+#
+#####
+
+size = `curl -s http://instance-data.ec2.internal/latest/meta-data/instance-type`
+case size
+when /m1.small/ # 1.7G RAM, 1 ECU, 32-bit
+ JVM_CONFIG = '-server -Xmx1g -Xms1g -XX:MaxPermSize=256m -XX:PermSize=256m -XX:NewRatio=2 -XX:+DisableExplicitGC'
+ JRUBY_RUNTIME_POOL_INITIAL = 1
+ JRUBY_RUNTIME_POOL_MIN = 1
+ JRUBY_RUNTIME_POOL_MAX = 1
+when /m1.large/ # 1.7G RAM, 5 ECU, 32-bit
+ JVM_CONFIG = '-server -Xmx1g -Xms1g -XX:MaxPermSize=256m -XX:PermSize=256m -XX:NewRatio=2 -XX:+DisableExplicitGC'
+ JRUBY_RUNTIME_POOL_INITIAL = 1
+ JRUBY_RUNTIME_POOL_MIN = 1
+ JRUBY_RUNTIME_POOL_MAX = 5
+when /m1.xlarge/ # 7.5G RAM, 4 ECU, 64-bit
+ JVM_CONFIG = '-server -Xmx2.5g -Xms2.5g -XX:MaxPermSize=378m -XX:PermSize=378m =XX:NewRatio=2'
+ JRUBY_RUNTIME_POOL_INITIAL = 1
+ JRUBY_RUNTIME_POOL_MIN = 1
+ JRUBY_RUNTIME_POOL_MAX = 5
+when /c1.medium/ # 15G RAM, 8 ECU, 64-bit
+ JVM_CONFIG = '-server -Xmx2.5g -Xms2.5g -XX:MaxPermSize=378m -XX:PermSize=378m =XX:NewRatio=2'
+ JRUBY_RUNTIME_POOL_INITIAL = 1
+ JRUBY_RUNTIME_POOL_MIN = 1
+ JRUBY_RUNTIME_POOL_MAX = 8
+when /c1.xlarge/ # 7.5G RAM, 20 ECU, 64-bit
+ JVM_CONFIG = '-server -Xmx2.5g -Xms2.5g -XX:MaxPermSize=378m -XX:PermSize=378m =XX:NewRatio=2'
+ JRUBY_RUNTIME_POOL_INITIAL = 1
+ JRUBY_RUNTIME_POOL_MIN = 1
+ JRUBY_RUNTIME_POOL_MAX = 20
+else # This shouldn't happen, but do something rational if it does.
+ JVM_CONFIG = '-server -Xmx1g -Xms1g -XX:MaxPermSize=256m -XX:PermSize=256m -XX:NewRatio=2 -XX:+DisableExplicitGC'
+ JRUBY_RUNTIME_POOL_INITIAL = 1
+ JRUBY_RUNTIME_POOL_MIN = 1
+ JRUBY_RUNTIME_POOL_MAX = 1
+end
+
+ require 'yaml'
+ File.open('/tmp/node.out','w+') {|fh| fh.puts node.to_yaml }
+
+# Install the glassfish configuration file.
+template File.join([APP_DIRECTORY],'config','glassfish.yml') do
+ owner node[:owner_name]
+ group node[:owner_name]
+ source 'glassfish.yml.erb'
+ variables({
+ :environment => 'development',
+ :port => 3000,
+ :contextroot => '/',
+ :log_level => 3,
+ :jruby_runtime_pool_initial => JRUBY_RUNTIME_POOL_INITIAL,
+ :jruby_runtime_pool_min => JRUBY_RUNTIME_POOL_MIN,
+ :jruby_runtime_pool_max => JRUBY_RUNTIME_POOL_MAX,
+ :daemon_enable => 'false', # It will be daemonized, but leave this as false for now.
+ :jvm_options => JVM_CONFIG
+ })
+end
+
+# Install the glassfish start/stop script.
+template '/etc/init.d/glassfish' do
+ owner 'root'
+ group 'root'
+ mode 0755
+ source 'init.d-glassfish.erb'
+end
+
+execute "ensure-glassfish-is-running" do
+ command %Q{
+ /etc/init.d/glassfish start --config /data/hello_world/current/config/glassfish.yml /data/hello_world/current
+ }
+end
diff --git a/cookbooks/jruby/templates/default/glassfish.monitrc.erb b/cookbooks/jruby/templates/default/glassfish.monitrc.erb
new file mode 100644
index 0000000..cffdc5d
--- /dev/null
+++ b/cookbooks/jruby/templates/default/glassfish.monitrc.erb
@@ -0,0 +1,4 @@
+check process glassfish_5000
+ with pidfile /var/run/glassfish/glassfish.5000.pid
+ start program = /usr/bin/jruby -S glassfish --config /data/hello_world/current/config/glassfish.yml /data/hello_world/current
+ stop program =
diff --git a/cookbooks/jruby/templates/default/glassfish.yml.erb b/cookbooks/jruby/templates/default/glassfish.yml.erb
new file mode 100644
index 0000000..c4f1e5a
--- /dev/null
+++ b/cookbooks/jruby/templates/default/glassfish.yml.erb
@@ -0,0 +1,96 @@
+#
+# GlassFish configuration.
+#
+# Please read the comments for each configuration settings before modifying.
+#
+
+# application environment. Default value development
+environment: <%= @environment %>
+
+
+# HTTP configuration
+http:
+
+ # port
+ port: <%= @port %>
+
+ # context root. The default value is '/'
+ contextroot: <%= @contextroot %>
+
+
+#Logging configuration
+log:
+
+ # Log file location. Default log file is log/<environment>.log. For
+ # example, if you are running in development environment, then the log
+ # file would be log/development.log.
+ #
+ # The log-file value must be either an absolute path or relative to your
+ # application directory.
+
+ #log-file:
+
+ # Logging level. Log level 0 to 7. 0:OFF, 1:SEVERE, 2:WARNING,
+ # 3:INFO (default), 4:FINE, 5:FINER, 6:FINEST, 7:ALL.
+ log-level: <%= @log_level %>
+
+#
+# Runtime configuration
+# If you are using Rails ver < 2.1.x, you should configure the JRuby runtime
+# pool for increased scalability.
+jruby-runtime-pool:
+
+ # Initial number of jruby runtimes that Glassfish starts with. It defaults
+ # to one. It also represents the lowest value that Glassfish will use for
+ # the maximum and the highest value that Glassfish will accept for the
+ # minimum. As of this time, setting this number too high may cause
+ # undesirable behavior. Default value is .
+ initial: <%= @jruby_runtime_pool_initial %>
+
+ # Minimum number of jruby runtimes that will be available in the pool.
+ # It defaults to one. The pool will always be at least this large, but
+ # may well be larger than this. Default value is 1.
+ min: <%= @jruby_runtime_pool_min %>
+
+
+ # Maximum number of jruby runtimes that may be available in the pool.
+ # It defaults to two. The pool will not neccessarily be this large.
+ # Values that are too high may result in OutOfMemory errors, either in
+ # the heap or in the PermGen. Default value is 1.
+ max: <%= @jruby_runtime_pool_max %>
+
+daemon:
+ # Run GlassFish as a daemon. GlassFish may not run as a daemon process
+ # on all platforms. Default value is false.
+ #enable: <%= @daemon_enable %>
+ enable: false
+
+ # File where the process id of GlassFish is saved when run as daemon.
+ # The location must be either an absolute path or relative to your
+ # application directory.
+ # default PID file is tmp/pids/glassfish-<PID>.pid
+
+ #pid:
+
+ # Like JRuby GlassFish gem runs on Java Virtual Machine. You can pass
+ # JVM properties using 'jvm-options' property. The JVM options must be
+ # SPACE seprated.
+ # 'jvm-options. property can ONLY be used only in daemon
+ # mode. The numbers below are to give an ideas. The numbers in your case
+ # would vary based on the hardware capabilities of machine you are
+ # running. See what is a server class machine
+ # http://java.sun.com/javase/6/docs/technotes/guides/vm/server-class.html
+
+ # GlassFish gem runs with these default options
+ #
+ #jvm-options: -server -Xmx512m -XX:MaxPermSize=192m -XX:NewRatio=2 -XX:+DisableExplicitGC -Dhk2.file.directory.changeIntervalTimer=6000
+
+ # Values below are given for a Sun Fire x4100, 4x Dual Core Opteron, 8G
+ # mem machine. You may like to changes these values according to the
+ # hardware you plan to run your application on. For details see
+ # JVM ergonomics document,
+ # http://java.sun.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
+ #
+ #jvm-options: -server -Xmx2500m -Xms64m -XX:PermSize=256m -XX:MaxPermSize=256m -XX:NewRatio=2 -XX:+DisableExplicitGC -Dhk2.file.directory.changeIntervalTimer=6000
+
+ jvm-options: <%= @jvm_options %>
diff --git a/cookbooks/jruby/templates/default/init.d-glassfish.erb b/cookbooks/jruby/templates/default/init.d-glassfish.erb
new file mode 100644
index 0000000..97ebc57
--- /dev/null
+++ b/cookbooks/jruby/templates/default/init.d-glassfish.erb
@@ -0,0 +1,81 @@
+#!/bin/bash
+
+# Start/stop script for glassfish; In general, just pass args through on start/restart. On stop, look in the "standard" location for the pid file or use the pid file given on the command line.
+
+PID=""
+
+function get_pid {
+ PID=`ps ax |grep bin/java | grep jruby | grep glassfish | cut -d " " -f 1`
+}
+
+function stop {
+ get_pid
+ if [ -z $PID ]; then
+ echo "Glassfish is not running."
+ exit 1
+ else
+ echo -n "Stopping Glassfish.."
+ if [ -z $2 ]; then
+ kill $PID
+ else
+ kill `cat $2`
+ fi
+ echo ".. Done."
+ fi
+}
+
+
+function start {
+ get_pid
+ if [ -z $PID ]; then
+ echo "Starting Glassfish..."
+ exec 1>&-
+ exec 2>&-
+ exec 3>&-
+ nohup jruby -S glassfish $@ & <&- 2>&1 > /dev/null
+ sleep 1
+ get_pid
+ echo "Done. PID=$PID"
+ else
+ echo "Glassfish is already running, PID=$PID"
+ fi
+}
+
+function restart {
+ echo "Restarting Glassfish.."
+ get_pid
+ if [ -z $PID ]; then
+ start
+ else
+ stop
+ start
+ fi
+}
+
+
+function status {
+ get_pid
+ if [ -z $PID ]; then
+ echo "Glassfish is not running."
+ exit 1
+ else
+ echo "Glassfish is running, PID=$PID"
+ fi
+}
+
+case "$1" in
+ start)
+ start
+ ;;
+ stop)
+ stop
+ ;;
+ restart)
+ restart
+ ;;
+ status)
+ status
+ ;;
+ *)
+ echo "Usage: $0 {start|stop|restart|status}"
+esac
|
dojo4/ey-cloud-recipes | 77ca633d84fb7697240c77fd8dfee3e8d27a6aef | adding some recpies in, adding in some READMEs | diff --git a/cookbooks/postgres b/cookbooks/postgres
deleted file mode 160000
index d382416..0000000
--- a/cookbooks/postgres
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit d382416339bab12339aed6dd165b8a1816eb2c1b
diff --git a/cookbooks/postgres/README.md b/cookbooks/postgres/README.md
new file mode 100644
index 0000000..295d917
--- /dev/null
+++ b/cookbooks/postgres/README.md
@@ -0,0 +1,39 @@
+ey-postgrecipes
+===============
+
+A chef recipe for enabling postgres on [solo][eysolo]. Data is persisted to
+EBS so your db naturally restores if you grow/shrink your instances. An
+upcoming release of the ey-flex-gem will be delivering support for native
+eybackup features.
+
+It's almost ready for everyone, it's working wonderfully for us right now.
+
+Dependencies
+============
+ % sudo gem install ey-flex
+
+You'll also need your ey-cloud.yml credentials from ey's [cloud][cloud].
+
+
+Using it
+========
+ mbp:: p/ey-postgrecipes » ey-recipes
+ Current Environments:
+ env: compton running instances: 1
+ instance_ids: ["i-5eu8x492"]
+ mbp:: p/ey-postgrecipes » ey-recipes --update compton
+
+Issues
+=======
+Under rails you'll see an error like this.
+
+ Please install the postgres adapter: `gem install
+ activerecord-postgres-adapter` (no such file to load --
+ active_record/connection_adapters/postgres_adapter)
+
+You'll need to modify cookbooks/postgres/templates/default/database.yml.erb and
+set the adapter to 'postgresql' instead of 'postgres'. Just fork the project
+and do yo thang.
+
+[eysolo]: http://www.engineyard.com/solo
+[cloud]: https://cloud.engineyard.com/extras
diff --git a/cookbooks/postgres/Rakefile b/cookbooks/postgres/Rakefile
new file mode 100644
index 0000000..13ec65b
--- /dev/null
+++ b/cookbooks/postgres/Rakefile
@@ -0,0 +1,42 @@
+TOPDIR = File.dirname(__FILE__)
+
+desc "Test your cookbooks for syntax errors"
+task :test do
+ puts "** Testing your cookbooks for syntax errors"
+ Dir[ File.join(TOPDIR, "cookbooks", "**", "*.rb") ].each do |recipe|
+ sh %{ruby -c #{recipe}} do |ok, res|
+ if ! ok
+ raise "Syntax error in #{recipe}"
+ end
+ end
+ end
+end
+
+desc "By default, run rake test"
+task :default => [ :test ]
+
+desc "Create a new cookbook (with COOKBOOK=name)"
+task :new_cookbook do
+ create_cookbook(File.join(TOPDIR, "cookbooks"))
+end
+
+def create_cookbook(dir)
+ raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"]
+ puts "** Creating cookbook #{ENV["COOKBOOK"]}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "attributes")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "recipes")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "definitions")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "libraries")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "files", "default")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "templates", "default")}"
+ unless File.exists?(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"))
+ open(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"), "w") do |file|
+ file.puts <<-EOH
+#
+# Cookbook Name:: #{ENV["COOKBOOK"]}
+# Recipe:: default
+#
+EOH
+ end
+ end
+end
diff --git a/cookbooks/postgres/cookbooks/main/attributes/recipe.rb b/cookbooks/postgres/cookbooks/main/attributes/recipe.rb
new file mode 100644
index 0000000..9d52e2c
--- /dev/null
+++ b/cookbooks/postgres/cookbooks/main/attributes/recipe.rb
@@ -0,0 +1,3 @@
+recipes('main')
+owner_name(@attribute[:users].first[:username])
+owner_pass(@attribute[:users].first[:password])
\ No newline at end of file
diff --git a/cookbooks/postgres/cookbooks/main/recipes/default.rb b/cookbooks/postgres/cookbooks/main/recipes/default.rb
new file mode 100644
index 0000000..d141a8a
--- /dev/null
+++ b/cookbooks/postgres/cookbooks/main/recipes/default.rb
@@ -0,0 +1,12 @@
+execute "testing" do
+ command %Q{
+ echo "i ran at #{Time.now}" >> /root/cheftime
+ }
+end
+
+# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
+# require_recipe "mbari-ruby"
+
+# uncomment to enable the postgres database server
+require_recipe 'rubygems'
+require_recipe 'postgres'
diff --git a/cookbooks/postgres/cookbooks/mbari-ruby/recipes/default.rb b/cookbooks/postgres/cookbooks/mbari-ruby/recipes/default.rb
new file mode 100644
index 0000000..2d01174
--- /dev/null
+++ b/cookbooks/postgres/cookbooks/mbari-ruby/recipes/default.rb
@@ -0,0 +1,38 @@
+#
+# Cookbook Name:: mbari-ruby
+# Recipe:: default
+#
+
+
+directory "/etc/portage/package.keywords" do
+ owner 'root'
+ group 'root'
+ mode 0775
+ recursive true
+end
+
+execute "add mbari keywords" do
+ command %Q{
+ echo "=dev-lang/ruby-1.8.6_p287-r2" >> /etc/portage/package.keywords/local
+ }
+ not_if "cat /etc/portage/package.keywords/local | grep '=dev-lang/ruby-1.8.6_p287-r2'"
+end
+
+directory "/etc/portage/package.use" do
+ owner 'root'
+ group 'root'
+ mode 0775
+ recursive true
+end
+
+execute "add mbari use flags" do
+ command %Q{
+ echo "dev-lang/ruby mbari" >> /etc/portage/package.use/local
+ }
+ not_if "cat /etc/portage/package.use/local | grep 'dev-lang/ruby mbari'"
+end
+
+package "dev-lang/ruby" do
+ version "1.8.6_p287-r2"
+ action :install
+end
\ No newline at end of file
diff --git a/cookbooks/postgres/cookbooks/postgres/recipes/default.rb b/cookbooks/postgres/cookbooks/postgres/recipes/default.rb
new file mode 100644
index 0000000..c64bbd2
--- /dev/null
+++ b/cookbooks/postgres/cookbooks/postgres/recipes/default.rb
@@ -0,0 +1,97 @@
+require 'pp'
+#
+# Cookbook Name:: postgres
+# Recipe:: default
+#
+postgres_root = '/var/lib/postgresql'
+postgres_version = '8.3'
+
+directory '/db/postgresql' do
+ owner 'postgres'
+ group 'postgres'
+ mode '0755'
+ action :create
+ recursive true
+end
+
+link "setup-postgresq-db-my-symlink" do
+ to '/db/postgresql'
+ target_file postgres_root
+end
+
+execute "setup-postgresql-db-symlink" do
+ command "rm -rf /var/lib/postgresql; ln -s /data/postgresql /var/lib/postgresql"
+ action :run
+ only_if "if [ ! -L #{postgres_root} ]; then exit 0; fi; exit 1;"
+end
+
+execute "init-postgres" do
+ command "initdb -D #{postgres_root}/#{postgres_version}/data"
+ action :run
+ user 'postgres'
+ only_if "if [ ! -d #{postgres_root}/#{postgres_version}/data ]; then exit 0; fi; exit 1;"
+end
+
+execute "enable-postgres" do
+ command "rc-update add postgresql-#{postgres_version} default"
+ action :run
+end
+
+execute "restart-postgres" do
+ command "/etc/init.d/postgresql-#{postgres_version} restart"
+ action :run
+ not_if "/etc/init.d/postgresql-8.3 status | grep -q start"
+end
+
+node[:applications].each do |app_name,data|
+ user = node[:users].first
+ db_name = "#{app_name}_#{node[:environment][:framework_env]}"
+
+ execute "create-db-user-#{user[:username]}" do
+ command "`psql -c '\\du' | grep -q '#{user[:username]}'`; if [ $? -eq 1 ]; then\n psql -c \"create user #{user[:username]} with encrypted password \'#{user[:password]}\'\"\nfi"
+ action :run
+ user 'postgres'
+ end
+
+ execute "create-db-#{db_name}" do
+ command "`psql -c '\\l' | grep -q '#{db_name}'`; if [ $? -eq 1 ]; then\n createdb #{db_name}\nfi"
+ action :run
+ user 'postgres'
+ end
+
+ execute "grant-perms-on-#{db_name}-to-#{user[:username]}" do
+ command "/usr/bin/psql -c 'grant all on database #{db_name} to #{user[:username]}'"
+ action :run
+ user 'postgres'
+ end
+
+ execute "alter-public-schema-owner-on-#{db_name}-to-#{user[:username]}" do
+ command "/usr/bin/psql #{db_name} -c 'ALTER SCHEMA public OWNER TO #{user[:username]}'"
+ action :run
+ user 'postgres'
+ end
+
+ template "/data/#{app_name}/shared/config/keep.database.yml" do
+ source "database.yml.erb"
+ owner user[:username]
+ group user[:username]
+ mode 0744
+ variables({
+ :username => user[:username],
+ :app_name => app_name,
+ :db_pass => user[:password]
+ })
+ end
+
+ template "/data/#{app_name}/shared/config/database.yml" do
+ source "database.yml.erb"
+ owner user[:username]
+ group user[:username]
+ mode 0744
+ variables({
+ :username => user[:username],
+ :app_name => app_name,
+ :db_pass => user[:password]
+ })
+ end
+end
diff --git a/cookbooks/postgres/cookbooks/postgres/templates/default/database.yml.erb b/cookbooks/postgres/cookbooks/postgres/templates/default/database.yml.erb
new file mode 100644
index 0000000..f00f810
--- /dev/null
+++ b/cookbooks/postgres/cookbooks/postgres/templates/default/database.yml.erb
@@ -0,0 +1,6 @@
+<%= @node[:environment][:framework_env] %>:
+ adapter: postgres
+ database: <%= @app_name %>_<%= @node[:environment][:framework_env] %>
+ username: <%= @username %>
+ password: <%= @db_pass %>
+ host: <%= @node[:db_host] %>
diff --git a/cookbooks/postgres/cookbooks/rubygems/recipes/default.rb b/cookbooks/postgres/cookbooks/rubygems/recipes/default.rb
new file mode 100644
index 0000000..4d95836
--- /dev/null
+++ b/cookbooks/postgres/cookbooks/rubygems/recipes/default.rb
@@ -0,0 +1,24 @@
+require 'pp'
+#
+# Cookbook Name:: rubygems-1.3.5
+# Recipe:: default
+#
+execute "fetch-rubygems" do
+ command "wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz"
+ action :run
+end
+
+execute "extract-rubygems" do
+ command "tar zxvf rubygems-1.3.5.tgz"
+ action :run
+end
+
+execute "install-rubygems" do
+ command "cd rubygems-1.3.5; ruby setup.rb"
+ action :run
+end
+
+execute "install-bundler" do
+ command "gem install bundler"
+ action :run
+end
|
dojo4/ey-cloud-recipes | 5ec4b06fce145789c52cd7e00482c7cfbcdd4d85 | adding readme | diff --git a/README.md b/README.md
new file mode 100644
index 0000000..86f2f84
--- /dev/null
+++ b/README.md
@@ -0,0 +1,22 @@
+ey-cloud-recipes
+===============
+This is a repository of some basic recipes for EY-Cloud using chef to deploy, setup, and configure common tools for Rails applications.
+
+
+Installation
+============
+
+Follow these steps to use custom deployment recipes with your applications.
+
+* Download your ey-cloud.yml file from your EY Cloud [Extras](http://cloud.engineyard.com/extras) page and put it in your HOME directory ~/.ey-cloud.yml
+* Install the required gems:
+ sudo gem install rest-client aws-s3
+ sudo gem install ey-flex --source http://gems.engineyard.com # make sure you are using the lastest version
+* Add any custom recipes or tweeks to the base recipes of your own and commit them to HEAD.
+* Upload them with: ey-recipes --upload ENV # where ENV is the name of your environment in Engine Yard Cloud. This may be different than your Rails environment name.
+* Once you have completed these steps, each deployment will run the latest version of your recipes after the default Engine Yard recipes have run. When you update your recipes, just re-run the ey-recipes --upload ENV task.
+
+
+
+[eysolo]: http://www.engineyard.com/solo
+[cloud]: https://cloud.engineyard.com/extras
diff --git a/cookbooks/ey-postgres b/cookbooks/postgres
similarity index 100%
rename from cookbooks/ey-postgres
rename to cookbooks/postgres
|
dojo4/ey-cloud-recipes | ae8ff85b32179141749207fe921a3cffeffea6af | adding a few recipes | diff --git a/cookbooks/ey-postgres b/cookbooks/ey-postgres
new file mode 160000
index 0000000..d382416
--- /dev/null
+++ b/cookbooks/ey-postgres
@@ -0,0 +1 @@
+Subproject commit d382416339bab12339aed6dd165b8a1816eb2c1b
diff --git a/cookbooks/thinking_sphinx/recipes/default.rb b/cookbooks/thinking_sphinx/recipes/default.rb
index 79faaff..23baf72 100644
--- a/cookbooks/thinking_sphinx/recipes/default.rb
+++ b/cookbooks/thinking_sphinx/recipes/default.rb
@@ -1,59 +1,57 @@
require 'pp'
#
# Cookbook Name:: thinking_sphinx
# Recipe:: default
#
if ['solo', 'app', 'app_master'].include?(node[:instance_role])
# be sure to replace "app_name" with the name of your application.
run_for_app("app_name") do |app_name, data|
directory "/var/run/sphinx" do
owner node[:owner_name]
group node[:owner_name]
mode 0755
end
directory "/var/log/engineyard/sphinx/#{app_name}" do
recursive true
owner node[:owner_name]
group node[:owner_name]
mode 0755
end
remote_file "/etc/logrotate.d/sphinx" do
owner "root"
group "root"
mode 0755
source "sphinx.logrotate"
backup false
action :create
end
template "/etc/monit.d/sphinx.#{app_name}.monitrc" do
source "sphinx.monitrc.erb"
owner node[:owner_name]
group node[:owner_name]
mode 0644
variables({
:app_name => app_name,
:user => node[:owner_name]
})
end
template "/data/#{app_name}/shared/config/sphinx.yml" do
owner node[:owner_name]
group node[:owner_name]
mode 0644
source "sphinx.yml.erb"
variables({
:app_name => app_name,
:user => node[:owner_name]
})
end
end
-
-
end
diff --git a/cookbooks/ultrasphinx/recipes/default.rb b/cookbooks/ultrasphinx/recipes/default.rb
index 15597ec..ea3405d 100644
--- a/cookbooks/ultrasphinx/recipes/default.rb
+++ b/cookbooks/ultrasphinx/recipes/default.rb
@@ -1 +1,59 @@
-# recipes go here.
\ No newline at end of file
+require 'pp'
+#
+# Cookbook Name:: ultrasphinx
+# Recipe:: default
+#
+#if_app_needs_recipe("ultrasphinx") do |app,data,index|
+
+if ['solo', 'app', 'app_master'].include?(node[:instance_role])
+
+ run_for_app("<appname>") do |app_name, data|
+
+ directory "/var/run/sphinx" do
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0755
+ end
+
+ directory "/var/log/engineyard/sphinx/#{app_name}" do
+ recursive true
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0755
+ end
+
+ remote_file "/etc/logrotate.d/sphinx" do
+ owner "root"
+ group "root"
+ mode 0755
+ source "sphinx.logrotate"
+ action :create
+ end
+
+ template "/etc/monit.d/sphinx.#{app_name}.monitrc" do
+ source "sphinx.monitrc.erb"
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0644
+ variables({
+ :app_name => app_name,
+ :user => node[:owner_name]
+ })
+ end
+
+ template "/data/#{app_name}/shared/config/sphinx.yml" do
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0644
+ source "sphinx.yml.erb"
+ variables({
+ :app_name => app_name,
+ :user => node[:owner_name]
+ })
+ end
+
+ end
+
+
+end
+
diff --git a/cookbooks/ultrasphinx/templates/default/sphinx.monitrc.erb b/cookbooks/ultrasphinx/templates/default/sphinx.monitrc.erb
index e69de29..8c06a1a 100644
--- a/cookbooks/ultrasphinx/templates/default/sphinx.monitrc.erb
+++ b/cookbooks/ultrasphinx/templates/default/sphinx.monitrc.erb
@@ -0,0 +1,6 @@
+check process sphinx_<%= @app_name %>_3312
+ with pidfile /var/run/sphinx/<%= @app_name %>.pid
+ start program = "/engineyard/bin/ultrasphinx_searchd <%= @app_name %> start" as uid <%= @user %> and gid <%= @user %>
+ stop program = "/engineyard/bin/ultrasphinx_searchd <%= @app_name %> stop" as uid <%= @user %> and gid <%= @user %>
+ group sphinx_<%= @app_name %>
+
diff --git a/cookbooks/ultrasphinx/templates/default/sphinx.yml.erb b/cookbooks/ultrasphinx/templates/default/sphinx.yml.erb
index 99b6ad4..4afe170 100644
--- a/cookbooks/ultrasphinx/templates/default/sphinx.yml.erb
+++ b/cookbooks/ultrasphinx/templates/default/sphinx.yml.erb
@@ -1 +1,10 @@
-# stuff goes here.
\ No newline at end of file
+<%= @node[:environment][:framework_env] %>:
+ searchd_log_file: /var/log/engineyard/sphinx/<%= @app_name %>/searchd.log
+ query_log_file: /var/log/engineyard/sphinx/<%= @app_name %>/query.log
+ pid_file: /var/run/sphinx/<%= @app_name %>.pid
+ address: localhost
+ port: 3312
+ mem_limit: 32
+ config_file: /data/<%= @app_name %>/current/config/ultrasphinx/<%= @node[:environment][:framework_env] %>.sphinx.conf
+ searchd_file_path: /var/log/engineyard/sphinx/<%= @app_name %>/indexes
+
|
dojo4/ey-cloud-recipes | a7f14fd622bbec61109a4f2e729e30d040c1acca | abstracted app_name for thinking_sphinx | diff --git a/cookbooks/thinking_sphinx/recipes/default.rb b/cookbooks/thinking_sphinx/recipes/default.rb
index f6897f5..79faaff 100644
--- a/cookbooks/thinking_sphinx/recipes/default.rb
+++ b/cookbooks/thinking_sphinx/recipes/default.rb
@@ -1,58 +1,59 @@
require 'pp'
#
# Cookbook Name:: thinking_sphinx
# Recipe:: default
#
-#if_app_needs_recipe("thinking_sphinx") do |app,data,index|
if ['solo', 'app', 'app_master'].include?(node[:instance_role])
- run_for_app("rede") do |app_name, data|
+ # be sure to replace "app_name" with the name of your application.
+ run_for_app("app_name") do |app_name, data|
directory "/var/run/sphinx" do
owner node[:owner_name]
group node[:owner_name]
mode 0755
end
directory "/var/log/engineyard/sphinx/#{app_name}" do
recursive true
owner node[:owner_name]
group node[:owner_name]
mode 0755
end
remote_file "/etc/logrotate.d/sphinx" do
owner "root"
group "root"
mode 0755
source "sphinx.logrotate"
+ backup false
action :create
end
template "/etc/monit.d/sphinx.#{app_name}.monitrc" do
source "sphinx.monitrc.erb"
owner node[:owner_name]
group node[:owner_name]
mode 0644
variables({
:app_name => app_name,
:user => node[:owner_name]
})
end
template "/data/#{app_name}/shared/config/sphinx.yml" do
owner node[:owner_name]
group node[:owner_name]
mode 0644
source "sphinx.yml.erb"
variables({
:app_name => app_name,
:user => node[:owner_name]
})
end
end
end
|
dojo4/ey-cloud-recipes | cde607d2698be36b1dd3d393469e778ce966c625 | added sphinx recipes, ultrasphinx under construction | diff --git a/cookbooks/main/libraries/run_for_app.rb b/cookbooks/main/libraries/run_for_app.rb
new file mode 100644
index 0000000..bc25eb7
--- /dev/null
+++ b/cookbooks/main/libraries/run_for_app.rb
@@ -0,0 +1,11 @@
+class Chef
+ class Recipe
+ def run_for_app(app, &block)
+ node[:applications].map{|k,v| [k,v] }.sort_by {|a,b| a }.each do |name, app_data|
+ if name == app
+ block.call(name, app_data)
+ end
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 576faec..58377d0 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,11 +1,18 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
-# require_recipe "mbari-ruby"
\ No newline at end of file
+# require_recipe "mbari-ruby"
+
+# uncomment to turn on thinking sphinx
+# require_recipe "thinking_sphinx"
+
+# uncomment to turn on ultrasphinx
+# require_recipe "ultrasphinx"
+
diff --git a/cookbooks/thinking_sphinx/files/default/sphinx.logrotate b/cookbooks/thinking_sphinx/files/default/sphinx.logrotate
new file mode 100644
index 0000000..4976dfa
--- /dev/null
+++ b/cookbooks/thinking_sphinx/files/default/sphinx.logrotate
@@ -0,0 +1,11 @@
+/var/log/engineyard/sphinx/*/*.log {
+ daily
+ missingok
+ dateext
+ rotate 30
+ compress
+ notifempty
+ sharedscripts
+ extension gz
+ copytruncate
+}
\ No newline at end of file
diff --git a/cookbooks/thinking_sphinx/recipes/default.rb b/cookbooks/thinking_sphinx/recipes/default.rb
new file mode 100644
index 0000000..f6897f5
--- /dev/null
+++ b/cookbooks/thinking_sphinx/recipes/default.rb
@@ -0,0 +1,58 @@
+require 'pp'
+#
+# Cookbook Name:: thinking_sphinx
+# Recipe:: default
+#
+#if_app_needs_recipe("thinking_sphinx") do |app,data,index|
+
+if ['solo', 'app', 'app_master'].include?(node[:instance_role])
+
+ run_for_app("rede") do |app_name, data|
+
+ directory "/var/run/sphinx" do
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0755
+ end
+
+ directory "/var/log/engineyard/sphinx/#{app_name}" do
+ recursive true
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0755
+ end
+
+ remote_file "/etc/logrotate.d/sphinx" do
+ owner "root"
+ group "root"
+ mode 0755
+ source "sphinx.logrotate"
+ action :create
+ end
+
+ template "/etc/monit.d/sphinx.#{app_name}.monitrc" do
+ source "sphinx.monitrc.erb"
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0644
+ variables({
+ :app_name => app_name,
+ :user => node[:owner_name]
+ })
+ end
+
+ template "/data/#{app_name}/shared/config/sphinx.yml" do
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0644
+ source "sphinx.yml.erb"
+ variables({
+ :app_name => app_name,
+ :user => node[:owner_name]
+ })
+ end
+
+ end
+
+
+end
diff --git a/cookbooks/thinking_sphinx/templates/default/sphinx.monitrc.erb b/cookbooks/thinking_sphinx/templates/default/sphinx.monitrc.erb
new file mode 100644
index 0000000..80803d8
--- /dev/null
+++ b/cookbooks/thinking_sphinx/templates/default/sphinx.monitrc.erb
@@ -0,0 +1,5 @@
+check process sphinx_<%= @app_name %>_3312
+ with pidfile /var/run/sphinx/<%= @app_name %>.pid
+ start program = "/engineyard/bin/thinking_sphinx_searchd <%= @app_name %> start" as uid <%= @user %> and gid <%= @user %>
+ stop program = "/engineyard/bin/thinking_sphinx_searchd <%= @app_name %> stop" as uid <%= @user %> and gid <%= @user %>
+ group sphinx_<%= @app_name %>
diff --git a/cookbooks/thinking_sphinx/templates/default/sphinx.yml.erb b/cookbooks/thinking_sphinx/templates/default/sphinx.yml.erb
new file mode 100644
index 0000000..dff3f96
--- /dev/null
+++ b/cookbooks/thinking_sphinx/templates/default/sphinx.yml.erb
@@ -0,0 +1,9 @@
+<%= @node[:environment][:framework_env] %>:
+ searchd_log_file: /var/log/engineyard/sphinx/<%= @app_name %>/searchd.log
+ query_log_file: /var/log/engineyard/sphinx/<%= @app_name %>/query.log
+ pid_file: /var/run/sphinx/<%= @app_name %>.pid
+ address: localhost
+ port: 3312
+ mem_limit: 32
+ config_file: /data/<%= @app_name %>/current/config/thinkingsphinx/<%= @node[:environment][:framework_env] %>.sphinx.conf
+ searchd_file_path: /var/log/engineyard/sphinx/<%= @app_name %>/indexes
diff --git a/cookbooks/ultrasphinx/files/default/sphinx.logrotate b/cookbooks/ultrasphinx/files/default/sphinx.logrotate
new file mode 100644
index 0000000..4976dfa
--- /dev/null
+++ b/cookbooks/ultrasphinx/files/default/sphinx.logrotate
@@ -0,0 +1,11 @@
+/var/log/engineyard/sphinx/*/*.log {
+ daily
+ missingok
+ dateext
+ rotate 30
+ compress
+ notifempty
+ sharedscripts
+ extension gz
+ copytruncate
+}
\ No newline at end of file
diff --git a/cookbooks/ultrasphinx/recipes/default.rb b/cookbooks/ultrasphinx/recipes/default.rb
new file mode 100644
index 0000000..15597ec
--- /dev/null
+++ b/cookbooks/ultrasphinx/recipes/default.rb
@@ -0,0 +1 @@
+# recipes go here.
\ No newline at end of file
diff --git a/cookbooks/ultrasphinx/templates/default/sphinx.monitrc.erb b/cookbooks/ultrasphinx/templates/default/sphinx.monitrc.erb
new file mode 100644
index 0000000..e69de29
diff --git a/cookbooks/ultrasphinx/templates/default/sphinx.yml.erb b/cookbooks/ultrasphinx/templates/default/sphinx.yml.erb
new file mode 100644
index 0000000..99b6ad4
--- /dev/null
+++ b/cookbooks/ultrasphinx/templates/default/sphinx.yml.erb
@@ -0,0 +1 @@
+# stuff goes here.
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 8fefe23decb249bda08d2dae151aa33569183ca7 | Remove integrity cookbook | diff --git a/cookbooks/integrity/libraries/if_app_needs_recipe.rb b/cookbooks/integrity/libraries/if_app_needs_recipe.rb
deleted file mode 100644
index a43175f..0000000
--- a/cookbooks/integrity/libraries/if_app_needs_recipe.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-class Chef
- class Recipe
- def if_app_needs_recipe(recipe, &block)
- index = 0
- node[:applications].map{|k,v| [k,v] }.sort_by {|a,b| a }.each do |name, app_data|
- if app_data[:recipes].detect { |r| r == recipe }
- Chef::Log.info("Applying Recipe: #{recipe}")
- block.call(name, app_data, index)
- index += 1
- end
- end
- end
-
- def any_app_needs_recipe?(recipe)
- needs = false
- node[:applications].each do |name, app_data|
- if app_data[:recipes].detect { |r| r == recipe }
- needs = true
- end
- end
- needs
- end
-
- end
-end
\ No newline at end of file
diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb
deleted file mode 100644
index 01a7918..0000000
--- a/cookbooks/integrity/recipes/default.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-#
-# Cookbook Name:: integrity
-# Recipe:: default
-#
-# Copyright 2009, Engine Yard, Inc.
-#
-# All rights reserved - Do Not Redistribute
-#
-
-require 'digest/sha1'
-
-gem_package 'foca-integrity-email' do
- action :install
- source "http://gems.github.com"
-end
-
-gem_package 'foca-sinatra-ditties' do
- action :install
- source "http://gems.github.com"
-end
-
-gem_package 'do_sqlite3' do
- action :install
-end
-
-gem_package 'integrity' do
- action :install
- version '0.1.9.0'
-end
-
-
-node[:applications].each do |app,data|
-
-
-
- execute "install integrity" do
- command "integrity install --passenger /data/#{app}/current"
- end
-
- template "/data/#{app}/current/config.ru" do
- owner node[:owner_name]
- group node[:owner_name]
- mode 0655
- source "config.ru.erb"
- end
-
- template "/data/#{app}/current/config.yml" do
- owner node[:owner_name]
- group node[:owner_name]
- mode 0655
- source "config.yml.erb"
- variables({
- :app => app,
- :domain => data[:vhosts].first[:name],
- })
- end
-
-end
-
-
-execute "restart-apache" do
- command "/etc/init.d/apache2 restart"
- action :run
-end
\ No newline at end of file
diff --git a/cookbooks/integrity/templates/default/config.ru.erb b/cookbooks/integrity/templates/default/config.ru.erb
deleted file mode 100644
index 1d8f085..0000000
--- a/cookbooks/integrity/templates/default/config.ru.erb
+++ /dev/null
@@ -1,19 +0,0 @@
-require "rubygems"
-require "integrity"
-
-# If you want to add any notifiers, install the gems and then require them here
-# For example, to enable the Email notifier: install the gem (from github:
-#
-# sudo gem install -s http://gems.github.com foca-integrity-email
-#
-# And then uncomment the following line:
-#
-# require "notifier/email"
-
-# Load configuration and initialize Integrity
-Integrity.new(File.dirname(__FILE__) + "/config.yml")
-
-# You probably don't want to edit anything below
-Integrity::App.set :environment, ENV["RACK_ENV"] || :production
-
-run Integrity::App
\ No newline at end of file
diff --git a/cookbooks/integrity/templates/default/config.yml.erb b/cookbooks/integrity/templates/default/config.yml.erb
deleted file mode 100644
index cf41c5c..0000000
--- a/cookbooks/integrity/templates/default/config.yml.erb
+++ /dev/null
@@ -1,41 +0,0 @@
-# Domain where integrity will be running from. This is used to have
-# nice URLs in your notifications.
-# For example:
-# http://builder.integrityapp.com
-:base_uri: <%= @domain %>
-
-# This should be a complete connection string to your database.
-#
-# Examples:
-# * `mysql://user:password@localhost/integrity`
-# * `postgres://<:password@localhost/integrity`
-# * `sqlite3:///home/integrity/db/integrity.sqlite`
-#
-# Note:
-# * The appropriate data_objects adapter must be installed (`do_mysql`, etc)
-# * You must create the `integrity` database on localhost, of course.
-:database_uri: sqlite3:///data/<%= @app %>/current/integrity.db
-
-# This is where your project's code will be checked out to. Make sure it's
-# writable by the user that runs Integrity.
-:export_directory: /data/<%= @app %>/current/builds
-
-# Path to the integrity log file
-:log: /data/<%= @app %>/current/log/integrity.log
-
-# Enable or disable HTTP authentication for the app. BE AWARE that if you
-# disable this anyone can delete and alter projects, so do it only if your
-# app is running in a controlled environment (ie, behind your company's
-# firewall.)
-:use_basic_auth: false
-
-# When `use_basic_auth` is true, the admin's username for HTTP authentication.
-:admin_username: <%= @node[:owner_name] %>
-
-# When `use_basic_auth` is true, the admin's password. Usually saved as a
-# SHA1 hash. See the next option.
-:admin_password: <%= Digest::SHA1.hexdigest(@node[:owner_pass]) %>
-
-# If this is true, then whenever we authenticate the admin user, will hash
-# it using SHA1. If not, we'll assume the provided password is in plain text.
-:hash_admin_password: true
\ No newline at end of file
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 040399f..576faec 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,14 +1,11 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
-# uncomment to turn your instance into an integrity CI server
-#require_recipe "integrity"
-
# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
# require_recipe "mbari-ruby"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 2e4ffb51580728f8f56acc784c830af451641430 | mbari ruby ptch recipes jow works fine just uncomment it to run | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index ac25586..040399f 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,14 +1,14 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
# uncomment to turn your instance into an integrity CI server
#require_recipe "integrity"
# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
-require_recipe "mbari-ruby"
\ No newline at end of file
+# require_recipe "mbari-ruby"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | b6282a1642ac7ff41eb615f8bdedb056bd731eec | fix versioning for ruby interp | diff --git a/cookbooks/mbari-ruby/recipes/default.rb b/cookbooks/mbari-ruby/recipes/default.rb
index 56209d3..2d01174 100644
--- a/cookbooks/mbari-ruby/recipes/default.rb
+++ b/cookbooks/mbari-ruby/recipes/default.rb
@@ -1,37 +1,38 @@
#
# Cookbook Name:: mbari-ruby
# Recipe:: default
#
directory "/etc/portage/package.keywords" do
owner 'root'
group 'root'
mode 0775
recursive true
end
execute "add mbari keywords" do
command %Q{
echo "=dev-lang/ruby-1.8.6_p287-r2" >> /etc/portage/package.keywords/local
}
not_if "cat /etc/portage/package.keywords/local | grep '=dev-lang/ruby-1.8.6_p287-r2'"
end
directory "/etc/portage/package.use" do
owner 'root'
group 'root'
mode 0775
recursive true
end
execute "add mbari use flags" do
command %Q{
echo "dev-lang/ruby mbari" >> /etc/portage/package.use/local
}
not_if "cat /etc/portage/package.use/local | grep 'dev-lang/ruby mbari'"
end
-package "dev-lang/ruby-1.8.6_p287-r2" do
+package "dev-lang/ruby" do
+ version "1.8.6_p287-r2"
action :install
end
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 02dbdff117f96c7a2da0b325dd7a4f597b52a0d7 | e mbari-ruby | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 1cb97d8..ac25586 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,11 +1,14 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
# uncomment to turn your instance into an integrity CI server
-#require_recipe "integrity"
\ No newline at end of file
+#require_recipe "integrity"
+
+# uncomment to turn use the MBARI ruby patches for decreased memory usage and better thread/continuationi performance
+require_recipe "mbari-ruby"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 13bbf36c3fd6d0b03ef256fa34aadfc5360f198e | adding mbari ruby patch build recipes | diff --git a/cookbooks/mbari-ruby/recipes/default.rb b/cookbooks/mbari-ruby/recipes/default.rb
new file mode 100644
index 0000000..56209d3
--- /dev/null
+++ b/cookbooks/mbari-ruby/recipes/default.rb
@@ -0,0 +1,37 @@
+#
+# Cookbook Name:: mbari-ruby
+# Recipe:: default
+#
+
+
+directory "/etc/portage/package.keywords" do
+ owner 'root'
+ group 'root'
+ mode 0775
+ recursive true
+end
+
+execute "add mbari keywords" do
+ command %Q{
+ echo "=dev-lang/ruby-1.8.6_p287-r2" >> /etc/portage/package.keywords/local
+ }
+ not_if "cat /etc/portage/package.keywords/local | grep '=dev-lang/ruby-1.8.6_p287-r2'"
+end
+
+directory "/etc/portage/package.use" do
+ owner 'root'
+ group 'root'
+ mode 0775
+ recursive true
+end
+
+execute "add mbari use flags" do
+ command %Q{
+ echo "dev-lang/ruby mbari" >> /etc/portage/package.use/local
+ }
+ not_if "cat /etc/portage/package.use/local | grep 'dev-lang/ruby mbari'"
+end
+
+package "dev-lang/ruby-1.8.6_p287-r2" do
+ action :install
+end
\ No newline at end of file
|
dojo4/ey-cloud-recipes | bf7dd83164ccae2e963e4707bab50aedc964b500 | integrity works | diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb
index d9f1219..01a7918 100644
--- a/cookbooks/integrity/recipes/default.rb
+++ b/cookbooks/integrity/recipes/default.rb
@@ -1,64 +1,64 @@
#
# Cookbook Name:: integrity
# Recipe:: default
#
# Copyright 2009, Engine Yard, Inc.
#
# All rights reserved - Do Not Redistribute
#
- require 'digest/sha1'
-
- gem_package 'foca-integrity-email' do
- action :install
- source "http://gems.github.com"
- end
-
- gem_package 'foca-sinatra-ditties' do
- action :install
- source "http://gems.github.com"
- end
-
- gem_package 'do_sqlite3' do
- action :install
- end
-
- gem_package 'integrity' do
- action :install
- version '0.1.9.0'
- end
-
-
-Chef::Log.info('apps: ' + node[:applications].inspect)
+require 'digest/sha1'
+gem_package 'foca-integrity-email' do
+ action :install
+ source "http://gems.github.com"
+end
- Chef::Log.info("owner: #{node[:owner_name]} pass: #{node[:owner_pass]}")
+gem_package 'foca-sinatra-ditties' do
+ action :install
+ source "http://gems.github.com"
+end
+
+gem_package 'do_sqlite3' do
+ action :install
+end
+
+gem_package 'integrity' do
+ action :install
+ version '0.1.9.0'
+end
+
node[:applications].each do |app,data|
execute "install integrity" do
command "integrity install --passenger /data/#{app}/current"
end
template "/data/#{app}/current/config.ru" do
owner node[:owner_name]
group node[:owner_name]
mode 0655
source "config.ru.erb"
end
template "/data/#{app}/current/config.yml" do
owner node[:owner_name]
group node[:owner_name]
mode 0655
source "config.yml.erb"
variables({
:app => app,
:domain => data[:vhosts].first[:name],
})
end
end
+
+execute "restart-apache" do
+ command "/etc/init.d/apache2 restart"
+ action :run
+end
\ No newline at end of file
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 15a6a2a..1cb97d8 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,9 +1,11 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
# require_recipe "couchdb"
-require_recipe "integrity"
\ No newline at end of file
+
+# uncomment to turn your instance into an integrity CI server
+#require_recipe "integrity"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 62de9093c0cf4614af94e9c61356bb3d68a366bb | another fix | diff --git a/cookbooks/main/attributes/recipe.rb b/cookbooks/main/attributes/recipe.rb
index 11e0a50..9d52e2c 100644
--- a/cookbooks/main/attributes/recipe.rb
+++ b/cookbooks/main/attributes/recipe.rb
@@ -1 +1,3 @@
-recipes('main')
\ No newline at end of file
+recipes('main')
+owner_name(@attribute[:users].first[:username])
+owner_pass(@attribute[:users].first[:password])
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 26ce729ccd6d2543ed9c425961ca662e40b41e34 | another fix | diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb
index a8a3acf..d9f1219 100644
--- a/cookbooks/integrity/recipes/default.rb
+++ b/cookbooks/integrity/recipes/default.rb
@@ -1,56 +1,64 @@
#
# Cookbook Name:: integrity
# Recipe:: default
#
# Copyright 2009, Engine Yard, Inc.
#
# All rights reserved - Do Not Redistribute
#
require 'digest/sha1'
gem_package 'foca-integrity-email' do
action :install
source "http://gems.github.com"
end
gem_package 'foca-sinatra-ditties' do
action :install
source "http://gems.github.com"
end
gem_package 'do_sqlite3' do
action :install
end
gem_package 'integrity' do
action :install
version '0.1.9.0'
end
+
+Chef::Log.info('apps: ' + node[:applications].inspect)
+
+
+ Chef::Log.info("owner: #{node[:owner_name]} pass: #{node[:owner_pass]}")
+
node[:applications].each do |app,data|
+
+
execute "install integrity" do
command "integrity install --passenger /data/#{app}/current"
end
template "/data/#{app}/current/config.ru" do
owner node[:owner_name]
group node[:owner_name]
mode 0655
source "config.ru.erb"
end
template "/data/#{app}/current/config.yml" do
owner node[:owner_name]
group node[:owner_name]
mode 0655
source "config.yml.erb"
variables({
:app => app,
:domain => data[:vhosts].first[:name],
})
end
end
|
dojo4/ey-cloud-recipes | d9e5de7f88c7e528ce05f2b5540e787f1ee757e2 | integrity | diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb
index 703380d..a8a3acf 100644
--- a/cookbooks/integrity/recipes/default.rb
+++ b/cookbooks/integrity/recipes/default.rb
@@ -1,60 +1,56 @@
#
# Cookbook Name:: integrity
# Recipe:: default
#
# Copyright 2009, Engine Yard, Inc.
#
# All rights reserved - Do Not Redistribute
#
-if any_app_needs_recipe?('integrity')
-
require 'digest/sha1'
gem_package 'foca-integrity-email' do
action :install
source "http://gems.github.com"
end
gem_package 'foca-sinatra-ditties' do
action :install
source "http://gems.github.com"
end
gem_package 'do_sqlite3' do
action :install
end
gem_package 'integrity' do
action :install
version '0.1.9.0'
end
-end
-
-if_app_needs_recipe("integrity") do |app,data,index|
+node[:applications].each do |app,data|
execute "install integrity" do
command "integrity install --passenger /data/#{app}/current"
end
template "/data/#{app}/current/config.ru" do
owner node[:owner_name]
group node[:owner_name]
mode 0655
source "config.ru.erb"
end
template "/data/#{app}/current/config.yml" do
owner node[:owner_name]
group node[:owner_name]
mode 0655
source "config.yml.erb"
variables({
:app => app,
:domain => data[:vhosts].first[:name],
})
end
end
|
dojo4/ey-cloud-recipes | 890c6f64a51da12d441f36f389bba5647762c3a2 | integrity | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 9350d61..15a6a2a 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,8 +1,9 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
-# require_recipe "couchdb"
\ No newline at end of file
+# require_recipe "couchdb"
+require_recipe "integrity"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 9bb3e2e1d21defefff9d276f525e9b63f4e98b82 | adding intergrity recipe | diff --git a/cookbooks/integrity/libraries/if_app_needs_recipe.rb b/cookbooks/integrity/libraries/if_app_needs_recipe.rb
new file mode 100644
index 0000000..a43175f
--- /dev/null
+++ b/cookbooks/integrity/libraries/if_app_needs_recipe.rb
@@ -0,0 +1,25 @@
+class Chef
+ class Recipe
+ def if_app_needs_recipe(recipe, &block)
+ index = 0
+ node[:applications].map{|k,v| [k,v] }.sort_by {|a,b| a }.each do |name, app_data|
+ if app_data[:recipes].detect { |r| r == recipe }
+ Chef::Log.info("Applying Recipe: #{recipe}")
+ block.call(name, app_data, index)
+ index += 1
+ end
+ end
+ end
+
+ def any_app_needs_recipe?(recipe)
+ needs = false
+ node[:applications].each do |name, app_data|
+ if app_data[:recipes].detect { |r| r == recipe }
+ needs = true
+ end
+ end
+ needs
+ end
+
+ end
+end
\ No newline at end of file
diff --git a/cookbooks/integrity/recipes/default.rb b/cookbooks/integrity/recipes/default.rb
new file mode 100644
index 0000000..703380d
--- /dev/null
+++ b/cookbooks/integrity/recipes/default.rb
@@ -0,0 +1,60 @@
+#
+# Cookbook Name:: integrity
+# Recipe:: default
+#
+# Copyright 2009, Engine Yard, Inc.
+#
+# All rights reserved - Do Not Redistribute
+#
+
+if any_app_needs_recipe?('integrity')
+
+ require 'digest/sha1'
+
+ gem_package 'foca-integrity-email' do
+ action :install
+ source "http://gems.github.com"
+ end
+
+ gem_package 'foca-sinatra-ditties' do
+ action :install
+ source "http://gems.github.com"
+ end
+
+ gem_package 'do_sqlite3' do
+ action :install
+ end
+
+ gem_package 'integrity' do
+ action :install
+ version '0.1.9.0'
+ end
+
+end
+
+if_app_needs_recipe("integrity") do |app,data,index|
+
+ execute "install integrity" do
+ command "integrity install --passenger /data/#{app}/current"
+ end
+
+ template "/data/#{app}/current/config.ru" do
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0655
+ source "config.ru.erb"
+ end
+
+ template "/data/#{app}/current/config.yml" do
+ owner node[:owner_name]
+ group node[:owner_name]
+ mode 0655
+ source "config.yml.erb"
+ variables({
+ :app => app,
+ :domain => data[:vhosts].first[:name],
+ })
+ end
+
+end
+
diff --git a/cookbooks/integrity/templates/default/config.ru.erb b/cookbooks/integrity/templates/default/config.ru.erb
new file mode 100644
index 0000000..1d8f085
--- /dev/null
+++ b/cookbooks/integrity/templates/default/config.ru.erb
@@ -0,0 +1,19 @@
+require "rubygems"
+require "integrity"
+
+# If you want to add any notifiers, install the gems and then require them here
+# For example, to enable the Email notifier: install the gem (from github:
+#
+# sudo gem install -s http://gems.github.com foca-integrity-email
+#
+# And then uncomment the following line:
+#
+# require "notifier/email"
+
+# Load configuration and initialize Integrity
+Integrity.new(File.dirname(__FILE__) + "/config.yml")
+
+# You probably don't want to edit anything below
+Integrity::App.set :environment, ENV["RACK_ENV"] || :production
+
+run Integrity::App
\ No newline at end of file
diff --git a/cookbooks/integrity/templates/default/config.yml.erb b/cookbooks/integrity/templates/default/config.yml.erb
new file mode 100644
index 0000000..cf41c5c
--- /dev/null
+++ b/cookbooks/integrity/templates/default/config.yml.erb
@@ -0,0 +1,41 @@
+# Domain where integrity will be running from. This is used to have
+# nice URLs in your notifications.
+# For example:
+# http://builder.integrityapp.com
+:base_uri: <%= @domain %>
+
+# This should be a complete connection string to your database.
+#
+# Examples:
+# * `mysql://user:password@localhost/integrity`
+# * `postgres://<:password@localhost/integrity`
+# * `sqlite3:///home/integrity/db/integrity.sqlite`
+#
+# Note:
+# * The appropriate data_objects adapter must be installed (`do_mysql`, etc)
+# * You must create the `integrity` database on localhost, of course.
+:database_uri: sqlite3:///data/<%= @app %>/current/integrity.db
+
+# This is where your project's code will be checked out to. Make sure it's
+# writable by the user that runs Integrity.
+:export_directory: /data/<%= @app %>/current/builds
+
+# Path to the integrity log file
+:log: /data/<%= @app %>/current/log/integrity.log
+
+# Enable or disable HTTP authentication for the app. BE AWARE that if you
+# disable this anyone can delete and alter projects, so do it only if your
+# app is running in a controlled environment (ie, behind your company's
+# firewall.)
+:use_basic_auth: false
+
+# When `use_basic_auth` is true, the admin's username for HTTP authentication.
+:admin_username: <%= @node[:owner_name] %>
+
+# When `use_basic_auth` is true, the admin's password. Usually saved as a
+# SHA1 hash. See the next option.
+:admin_password: <%= Digest::SHA1.hexdigest(@node[:owner_pass]) %>
+
+# If this is true, then whenever we authenticate the admin user, will hash
+# it using SHA1. If not, we'll assume the provided password is in plain text.
+:hash_admin_password: true
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 017258faf8e5bca61e48aca2ee44114fe49d049d | commenc out couchdb recipe as an example | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 6f8c557..9350d61 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,8 +1,8 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
-require_recipe "couchdb"
\ No newline at end of file
+# require_recipe "couchdb"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 0248e8cf23abe9a0af99779237fd548ff78793c1 | use not_if's | diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb
index dc5a928..7883610 100644
--- a/cookbooks/couchdb/recipes/default.rb
+++ b/cookbooks/couchdb/recipes/default.rb
@@ -1,50 +1,52 @@
#
# Cookbook Name:: couchdb
# Recipe:: default
#
package "couchdb" do
version "0.8.1"
end
directory "/db/couchdb/log" do
owner "couchdb"
group "couchdb"
mode 0755
recursive true
end
template "/etc/couchdb/couch.ini" do
owner 'root'
group 'root'
mode 0644
source "couch.ini.erb"
variables({
:basedir => '/db/couchdb',
:logfile => '/db/couchdb/log/couch.log',
:bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world
:port => '5984',# change if you want to listen on another port
:doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root
:driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo
:loglevel => 'info'
})
end
remote_file "/etc/init.d/couchdb" do
source "couchdb"
owner "root"
group "root"
mode 0755
end
execute "add-couchdb-to-default-run-level" do
command %Q{
rc-update add couchdb default
}
+ not_if "rc-status | grep couchdb"
end
execute "ensure-couchdb-is-running" do
command %Q{
/etc/init.d/couchdb restart
}
+ not_if "/etc/init.d/couchdb status | grep 'status: started'"
end
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 7d2109cc2ac40afd42de2911c7cce75c5a6b4fd5 | reenable couch | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 12f1acc..6f8c557 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,8 +1,8 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
-#require_recipe "couchdb"
\ No newline at end of file
+require_recipe "couchdb"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 37c1387b9034e4851463bde1b344f3b77a8c7964 | dont run couchdb by default | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 6f8c557..12f1acc 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,8 +1,8 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
-require_recipe "couchdb"
\ No newline at end of file
+#require_recipe "couchdb"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 581433f502eb5999a6bdb7ca9609a02b2932e1c5 | couchdb touchpus | diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb
index 6da1407..dc5a928 100644
--- a/cookbooks/couchdb/recipes/default.rb
+++ b/cookbooks/couchdb/recipes/default.rb
@@ -1,51 +1,50 @@
#
# Cookbook Name:: couchdb
# Recipe:: default
#
package "couchdb" do
version "0.8.1"
end
directory "/db/couchdb/log" do
owner "couchdb"
group "couchdb"
mode 0755
recursive true
end
template "/etc/couchdb/couch.ini" do
owner 'root'
group 'root'
mode 0644
source "couch.ini.erb"
variables({
:basedir => '/db/couchdb',
:logfile => '/db/couchdb/log/couch.log',
:bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world
:port => '5984',# change if you want to listen on another port
:doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root
:driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo
:loglevel => 'info'
})
end
remote_file "/etc/init.d/couchdb" do
source "couchdb"
owner "root"
group "root"
mode 0755
end
execute "add-couchdb-to-default-run-level" do
command %Q{
rc-update add couchdb default
}
- not_if "rc-status | grep couchdb"
end
execute "ensure-couchdb-is-running" do
command %Q{
/etc/init.d/couchdb restart
}
end
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 730ea0e1d42d90e5ca53662d021f78fe0a965a1e | just restart couchdb on successful run | diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb
index 5c75fab..6da1407 100644
--- a/cookbooks/couchdb/recipes/default.rb
+++ b/cookbooks/couchdb/recipes/default.rb
@@ -1,52 +1,51 @@
#
# Cookbook Name:: couchdb
# Recipe:: default
#
package "couchdb" do
version "0.8.1"
end
directory "/db/couchdb/log" do
owner "couchdb"
group "couchdb"
mode 0755
recursive true
end
template "/etc/couchdb/couch.ini" do
owner 'root'
group 'root'
mode 0644
source "couch.ini.erb"
variables({
:basedir => '/db/couchdb',
:logfile => '/db/couchdb/log/couch.log',
:bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world
:port => '5984',# change if you want to listen on another port
:doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root
:driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo
:loglevel => 'info'
})
end
remote_file "/etc/init.d/couchdb" do
source "couchdb"
owner "root"
group "root"
mode 0755
end
execute "add-couchdb-to-default-run-level" do
command %Q{
rc-update add couchdb default
}
not_if "rc-status | grep couchdb"
end
execute "ensure-couchdb-is-running" do
command %Q{
/etc/init.d/couchdb restart
}
- not_if "/etc/init.d/couchdb status | grep 'Apache CouchDB has started. Time to relax.'"
end
\ No newline at end of file
|
dojo4/ey-cloud-recipes | 8572b9768c36a1949096558e79f6443e2c79f784 | make sure couchdb is run | diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
index 9350d61..6f8c557 100644
--- a/cookbooks/main/recipes/default.rb
+++ b/cookbooks/main/recipes/default.rb
@@ -1,8 +1,8 @@
execute "testing" do
command %Q{
echo "i ran at #{Time.now}" >> /root/cheftime
}
end
# uncomment if you want to run couchdb recipe
-# require_recipe "couchdb"
\ No newline at end of file
+require_recipe "couchdb"
\ No newline at end of file
|
dojo4/ey-cloud-recipes | f02c31ab128f535992c5bf765b08974ef66f13a0 | comment out the couchdb recipe | diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..13ec65b
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,42 @@
+TOPDIR = File.dirname(__FILE__)
+
+desc "Test your cookbooks for syntax errors"
+task :test do
+ puts "** Testing your cookbooks for syntax errors"
+ Dir[ File.join(TOPDIR, "cookbooks", "**", "*.rb") ].each do |recipe|
+ sh %{ruby -c #{recipe}} do |ok, res|
+ if ! ok
+ raise "Syntax error in #{recipe}"
+ end
+ end
+ end
+end
+
+desc "By default, run rake test"
+task :default => [ :test ]
+
+desc "Create a new cookbook (with COOKBOOK=name)"
+task :new_cookbook do
+ create_cookbook(File.join(TOPDIR, "cookbooks"))
+end
+
+def create_cookbook(dir)
+ raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"]
+ puts "** Creating cookbook #{ENV["COOKBOOK"]}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "attributes")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "recipes")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "definitions")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "libraries")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "files", "default")}"
+ sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "templates", "default")}"
+ unless File.exists?(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"))
+ open(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"), "w") do |file|
+ file.puts <<-EOH
+#
+# Cookbook Name:: #{ENV["COOKBOOK"]}
+# Recipe:: default
+#
+EOH
+ end
+ end
+end
diff --git a/cookbooks/couchdb/files/default/couchdb b/cookbooks/couchdb/files/default/couchdb
new file mode 100644
index 0000000..0e54bae
--- /dev/null
+++ b/cookbooks/couchdb/files/default/couchdb
@@ -0,0 +1,122 @@
+#!/sbin/runscript
+# Copyright 1999-2008 Gentoo Foundation
+# by Gerardo Puerta Cardelles / Vicente Jimenez Aguilar
+# Distributed under the terms of the GNU General Public License v2
+# $Header: $
+
+
+# TODO:
+# * Try to use start-stop-daemon to stop the CouchDB server.
+# * Change init configuration file from /etc/default/couchdb to /etc/conf.d/couchdb
+
+depend() {
+ need net
+ # or just use?
+ need localmount
+ after bootmisc
+}
+
+COUCHDB=/usr/bin/couchdb
+
+# Gentoo doesn't have /lib/lsb
+# LSB_LIBRARY=/lib/lsb/init-functions
+
+# Better put this file into /etc/conf.d
+#
+# for a second version?
+CONFIGURATION_FILE=/etc/default/couchdb
+
+
+sourceconfig() {
+ if test -r $CONFIGURATION_FILE
+ then
+ . $CONFIGURATION_FILE
+ fi
+}
+
+checkpidfileoption() {
+ if test -n "$COUCHDB_PID_FILE"; then
+ pidfile_option="-p $COUCHDB_PID_FILE"
+ # Option for the start-stop-daemon (needed?)
+ couchdb_pidfile="--pidfile $COUCHDB_PID_FILE"
+ # Could be the same variable as both understand -p
+ # but prefered to keep then separated
+ fi
+
+}
+
+checkmoreoptions(){
+ if test -n "$COUCHDB_USER"
+ then
+ # Option for the start-stop-daemon
+ couchdb_user="--chuid $COUCHDB_USER"
+ fi
+
+ # Options for the $COUCHDB command
+ command_options=""
+ if test -n "$COUCHDB_INI_FILE"; then
+ command_options="$command_options -c $COUCHDB_INI_FILE"
+ fi
+ if test -n "$COUCHDB_STDOUT_FILE"; then
+ command_options="$command_options -o $COUCHDB_STDOUT_FILE"
+ fi
+ if test -n "$COUCHDB_STDERR_FILE"; then
+ command_options="$command_options -e $COUCHDB_STDERR_FILE"
+ fi
+ if test -n "$COUCHDB_RESPAWN_TIMEOUT"; then
+ command_options="$command_options -r $COUCHDB_RESPAWN_TIMEOUT"
+ fi
+}
+
+
+start() {
+ ebegin "Starting Apache CouchDB"
+ if test ! -x $COUCHDB
+ then
+ eend $?
+ fi
+# Gentoo doesn't have /lib/lsb
+# if test -r $LSB_LIBRARY
+# then
+# . $LSB_LIBRARY
+# fi
+
+ sourceconfig
+ checkpidfileoption
+ checkmoreoptions
+ # All options are used plus -b for the background (needed -b option?)
+ start-stop-daemon --start $couchdb_user $couchdb_pidfile --oknodo --exec $COUCHDB -- $pidfile_option $command_options -b
+ eend $?
+}
+
+stop() {
+# Imposible to use start-stop-daemon because of respawn.
+# Help needed! Tried everything.
+# Event sending just a -1 signal but the script respawn another instance.
+# Examples of commands tried:
+# start-stop-daemon --stop $couchdb_pidfile --signal 1
+# start-stop-daemon --stop --exec $COUCHDB
+
+ ebegin "Stopping Apache CouchDB"
+ sourceconfig
+ checkpidfileoption
+ # Only -p option is useful when is different from default /var/run/couchdb.pid
+ # Added -d option for the shutdown
+ $COUCHDB $pidfile_option -d
+ eend $?
+}
+
+status() {
+ sourceconfig
+ checkpidfileoption
+ # Only -p option is useful when is different from default /var/run/couchdb.pid
+ # added -s option for status display
+ $COUCHDB $pidfile_option -s
+ # WARNING: due to how $COUCHDB reads arguments,
+ # option -p needs to be put BEFORE -s because when the -s option is read,
+ # the script check status and exit without reading more options.
+ # So if we use a PID file other than the default /var/run/couchdb.pid
+ # and we put no -p option BEFORE the -s option
+ # the script always displays "Apache CouchDB is not running." as the status.
+}
+
diff --git a/cookbooks/couchdb/recipes/default.rb b/cookbooks/couchdb/recipes/default.rb
new file mode 100644
index 0000000..5c75fab
--- /dev/null
+++ b/cookbooks/couchdb/recipes/default.rb
@@ -0,0 +1,52 @@
+#
+# Cookbook Name:: couchdb
+# Recipe:: default
+#
+
+package "couchdb" do
+ version "0.8.1"
+end
+
+directory "/db/couchdb/log" do
+ owner "couchdb"
+ group "couchdb"
+ mode 0755
+ recursive true
+end
+
+template "/etc/couchdb/couch.ini" do
+ owner 'root'
+ group 'root'
+ mode 0644
+ source "couch.ini.erb"
+ variables({
+ :basedir => '/db/couchdb',
+ :logfile => '/db/couchdb/log/couch.log',
+ :bind_address => '127.0.0.1', # '0.0.0.0' if you want couch available to the outside world
+ :port => '5984',# change if you want to listen on another port
+ :doc_root => '/usr/share/couchdb/www', # change if you have a cutom couch www root
+ :driver_dir => '/usr/lib/couchdb/erlang/lib/couch-0.8.1-incubating/priv/lib', # this is good for the 0.8.1 build on our gentoo
+ :loglevel => 'info'
+ })
+end
+
+remote_file "/etc/init.d/couchdb" do
+ source "couchdb"
+ owner "root"
+ group "root"
+ mode 0755
+end
+
+execute "add-couchdb-to-default-run-level" do
+ command %Q{
+ rc-update add couchdb default
+ }
+ not_if "rc-status | grep couchdb"
+end
+
+execute "ensure-couchdb-is-running" do
+ command %Q{
+ /etc/init.d/couchdb restart
+ }
+ not_if "/etc/init.d/couchdb status | grep 'Apache CouchDB has started. Time to relax.'"
+end
\ No newline at end of file
diff --git a/cookbooks/couchdb/templates/default/couch.ini.erb b/cookbooks/couchdb/templates/default/couch.ini.erb
new file mode 100644
index 0000000..f27745a
--- /dev/null
+++ b/cookbooks/couchdb/templates/default/couch.ini.erb
@@ -0,0 +1,21 @@
+[Couch]
+
+ConsoleStartupMsg=Apache CouchDB is starting.
+
+DbRootDir=<%= @basedir %>
+
+Port=<%= @port %>
+
+BindAddress=<%= @bind_address %>
+
+DocumentRoot=<%= @doc_root %>
+
+LogFile=<%= @logfile %>
+
+UtilDriverDir=<%= @driver_dir %>
+
+LogLevel=<%= @loglevel %>
+
+[Couch Query Servers]
+
+javascript=/usr/bin/couchjs /usr/share/couchdb/server/main.js
diff --git a/cookbooks/main/attributes/recipe.rb b/cookbooks/main/attributes/recipe.rb
new file mode 100644
index 0000000..11e0a50
--- /dev/null
+++ b/cookbooks/main/attributes/recipe.rb
@@ -0,0 +1 @@
+recipes('main')
\ No newline at end of file
diff --git a/cookbooks/main/recipes/default.rb b/cookbooks/main/recipes/default.rb
new file mode 100644
index 0000000..9350d61
--- /dev/null
+++ b/cookbooks/main/recipes/default.rb
@@ -0,0 +1,8 @@
+execute "testing" do
+ command %Q{
+ echo "i ran at #{Time.now}" >> /root/cheftime
+ }
+end
+
+# uncomment if you want to run couchdb recipe
+# require_recipe "couchdb"
\ No newline at end of file
|
ngmaloney/gmaplist | 62360766cc8fc3db82e52294142f852547a018cb | Added documentation pages and examples | diff --git a/example1.html b/example1.html
index 463bffa..adcc742 100644
--- a/example1.html
+++ b/example1.html
@@ -1,34 +1,44 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
-<head>
-<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAKYaO3iHtIJp7vbWR-lwa_hTb-vLQlFZmc2N8bgWI8YDPp5FEVBQSnZeAcu9H26_1vNdOb0GvTDmVJA"></script>
-<script>
- google.load("maps", "2.x");
- google.load("jquery", "1.3.1");
- google.setOnLoadCallback(function() {
- gmap = new GMap2(document.getElementById('map'));
- gmap.setCenter(new GLatLng(0, 0), 13);
- $('#newEngland').gmaplist(gmap);
- });
-</script>
-<script src="jquery.gmaplist.js"></script>
-<style media="screen" type="text/css">
- #map, #country_map {
- width:500px;
- height:300px;
- }
-</style>
-</head>
-<body>
-
-<div id="map" style="display:none"></div>
-<ul id="newEngland">
- <li>Connecticut</li>
- <li>Maine</li>
- <li>Massachusetts</li>
- <li>New Hampshire</li>
- <li>Rhode Island</li>
- <li>Vermont</li>
-</ul>
-
-</body>
-</html>
\ No newline at end of file
+ <head>
+ <title>GMAP List - Simple Example</title>
+ <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.8.0r4/build/reset-fonts-grids/reset-fonts-grids.css&2.8.0r4/build/base/base-min.css">
+ <link rel="stylesheet" href="style.css" type="text/css" media="screen" title="no title" charset="utf-8">
+
+ <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAKYaO3iHtIJp7vbWR-lwa_hQ3TGjyPcge1uoyLYv8dGArsmOsbhQ1ptv-4Y7zdT-QIosD_Z9AjYyzSw"></script>
+ <script>
+ google.load("maps", "2.x");
+ google.load("jquery", "1.3.1");
+ google.setOnLoadCallback(function() {
+ gmap = new GMap2(document.getElementById('map'));
+ gmap.setCenter(new GLatLng(0, 0), 13);
+ $('#newEngland').gmaplist(gmap);
+ });
+ </script>
+ <script src="jquery.gmaplist.js"></script>
+
+ </head>
+ <body>
+ <div id="doc">
+ <div id="hd"><!-- header -->
+ <h1>GMAP LIST</h1>
+ <h2>A jquery plugin for creating maps from an HTML list</h2>
+ </div>
+ <div id="bd"><!-- body -->
+ <div id="map" style="display:none"></div>
+ <ul id="newEngland">
+ <li>Connecticut</li>
+ <li>Maine</li>
+ <li>Massachusetts</li>
+ <li>New Hampshire</li>
+ <li>Rhode Island</li>
+ <li>Vermont</li>
+ </ul>
+ </div>
+ <div id="ft"><!-- footer -->
+ © 2010 Nicholas G. Maloney
+ </div>
+ </div>
+
+ </body>
+</html>
diff --git a/example2.html b/example2.html
index 0a91429..99ca7b4 100644
--- a/example2.html
+++ b/example2.html
@@ -1,151 +1,142 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
+ <title>GMAP List - Advanced Example</title>
+ <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.8.0r4/build/reset-fonts-grids/reset-fonts-grids.css&2.8.0r4/build/base/base-min.css">
+ <link rel="stylesheet" href="style.css" type="text/css" media="screen" title="no title" charset="utf-8">
- <!--
- This is a more advanced example of using Jquery Map List. It contains 2 map instances that are displayed after clicking on an anchor link.
- -->
-
- <title>jQuery Mapper Prototype</title>
- <!-- Include JQuery -->
- <!--
- localhost key: ABQIAAAAKYaO3iHtIJp7vbWR-lwa_hTb-vLQlFZmc2N8bgWI8YDPp5FEVBQSnZeAcu9H26_1vNdOb0GvTDmVJA
- binarytransport key: ABQIAAAAKYaO3iHtIJp7vbWR-lwa_hQ3TGjyPcge1uoyLYv8dGArsmOsbhQ1ptv-4Y7zdT-QIosD_Z9AjYyzSw
- -->
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAKYaO3iHtIJp7vbWR-lwa_hQ3TGjyPcge1uoyLYv8dGArsmOsbhQ1ptv-4Y7zdT-QIosD_Z9AjYyzSw"></script>
+ <script>
+ google.load("maps", "2.x");
+ google.load("jquery", "1.3.1");
+ google.setOnLoadCallback(function() {
+ //Function for viewing State Map
+ var view_state_map = function() {
+ var map = new GMap2(document.getElementById('map'));
+ map.setCenter(new GLatLng(0, 0), 13);
+ map.addControl(new GSmallMapControl());
+ map.addControl(new GMapTypeControl());
+ $('#markers').gmaplist(map,{delay:100});
+ return false;
+ }
-<script>
- google.load("maps", "2.x");
- google.load("jquery", "1.3.1");
- google.setOnLoadCallback(function() {
- //Function for viewing State Map
- var view_state_map = function() {
- var map = new GMap2(document.getElementById('map'));
- map.setCenter(new GLatLng(0, 0), 13);
- map.addControl(new GSmallMapControl());
- map.addControl(new GMapTypeControl());
- $('#markers').gmaplist(map,{delay:100,debug:true});
- return false;
- }
-
- //Function for viewing Country Map
- var view_country_map = function() {
- cmap = new GMap2(document.getElementById('country_map'));
- cmap.setCenter(new GLatLng(0, 0), 13);
- $('#countries').gmaplist(cmap, {delay:100,debug:true});
- return false;
- }
-
- var tester = function() {
- alert('clicked');
- }
-
- //Add Click Events
- $('#view_state_map').click(view_state_map);
- $('#view_country_map').click(view_country_map);
- });
-
+ //Function for viewing Country Map
+ var view_country_map = function() {
+ cmap = new GMap2(document.getElementById('country_map'));
+ cmap.setCenter(new GLatLng(0, 0), 13);
+ $('#countries').gmaplist(cmap, {delay:100});
+ return false;
+ }
-</script>
+ var tester = function() {
+ alert('clicked');
+ }
-<script src="jquery.gmaplist.js"></script>
+ //Add Click Events
+ $('#view_state_map').click(view_state_map);
+ $('#view_country_map').click(view_country_map);
+ });
+
+ </script>
+ <script src="jquery.gmaplist.js"></script>
- <!-- CSS -->
- <style media="screen" type="text/css">
- #map, #country_map {
- width:500px;
- height:300px;
- }
- </style>
</head>
<body>
+ <div id="doc">
+ <div id="hd"><!-- header -->
+ <h1>GMAP LIST</h1>
+ <h2>A jquery plugin for creating maps from an HTML list</h2>
+ </div>
+ <div id="bd"><!-- body -->
+ <div class="button_link"><a href="#" id="view_state_map">View Map</a></div>
+ <div id="map" style="display:none"></div>
+ <!-- Add Map Markers -->
+ <ul id="markers">
+ <li>California</li>
+ <li>Colorado</li>
+ <li>Connecticut</li>
+ <li>Florida</li>
+ <li>Hawaii</li>
+ <li>Idaho</li>
+ <li>Illinois</li>
+ <li>Indiana</li>
+ <li>Massachusetts</li>
+ <li>Maine</li>
+ <li>Maryland</li>
+ <li>New Hampshire</li>
+ <li>New Jersey</li>
+ <li>New Mexico</li>
+ <li>Nevada</li>
+ <li>New York</li>
+ <li>North Carolina</li>
+ <li>Ohio</li>
+ <li>Oregon</li>
+ <li>Pennsylvania</li>
+ <li>Puerto Rico</li>
+ <li>Rhode Island</li>
+ <li>Tennessee</li>
+ <li>Texas</li>
+ <li>Utah</li>
+ <li>Virginia</li>
+ <li>Virgin Islands</li>
+ <li>Vermont</li>
+ <li>Wisconsin</li>
+ </ul>
+
+ <div class="button_link"><a href="#" id="view_country_map">View Map</a></div>
+ <div id="country_map" style="display:none"></div>
+ <ul id="countries">
+ <li>Armenia</li>
+ <li>Bahrain</li>
+ <li>Bolivia</li>
+ <li>Brazil</li>
+ <li>Bulgaria</li>
+ <li>Canada</li>
+ <li>Chile</li>
+ <li>Cypress</li>
+ <li>Dominican Republic</li>
+ <li>Ecuador</li>
+ <li>France</li>
+ <li>Germany</li>
+ <li>Greece</li>
+ <li>Guatemala</li>
+ <li>Haiti</li>
+ <li>Honduras</li>
+ <li>Hong Kong</li>
+ <li>India</li>
+ <li>Indonesia</li>
+ <li>Japan</li>
+ <li>Jordan</li>
+ <li>Korea</li>
+ <li>Kuwait</li>
+ <li>Lebanon</li>
+ <li>Mexico</li>
+ <li>Morocco</li>
+ <li>Netherlands Antilles</li>
+ <li>Pakistan</li>
+ <li>Panama</li>
+ <li>Peru</li>
+ <li>Philippines</li>
+ <li>People's Republic of China</li>
+ <li>Saudi Arabia</li>
+ <li>Singapore</li>
+ <li>South Korea</li>
+ <li>Spain</li>
+ <li>Tanzania</li>
+ <li>United Arab Emirates</li>
+ <li>Thailand</li>
+ <li>Turkey</li>
+ <li>Ukraine</li>
+ <li>United Arab Emirates</li>
+ <li>Venezuela</li>
+ <li>Vietnam</li>
+ <li>West Indies</li>
+ </ul>
+ </div>
+ <div id="ft"><!-- footer -->
+ © 2010 Nicholas G. Maloney
+ </div>
+ </div>
- <a href="#" id="view_state_map">View Map</a>
- <div id="map" style="display:none"></div>
- <!-- Add Map Markers -->
- <ul id="markers">
- <li>California</li>
- <li>Colorado</li>
- <li>Connecticut</li>
- <li>Florida</li>
- <li>Hawaii</li>
- <li>Idaho</li>
- <li>Illinois</li>
- <li>Indiana</li>
- <li>Massachusetts</li>
- <li>Maine</li>
- <li>Maryland</li>
- <li>New Hampshire</li>
- <li>New Jersey</li>
- <li>New Mexico</li>
- <li>Nevada</li>
- <li>New York</li>
- <li>North Carolina</li>
- <li>Ohio</li>
- <li>Oregon</li>
- <li>Pennsylvania</li>
- <li>Puerto Rico</li>
- <li>Rhode Island</li>
- <li>Tennessee</li>
- <li>Texas</li>
- <li>Utah</li>
- <li>Virginia</li>
- <li>Virgin Islands</li>
- <li>Vermont</li>
- <li>Wisconsin</li>
- </ul>
-
- <a href="#" id="view_country_map">View Map</a>
- <div id="country_map" style="display:none"></div>
- <ul id="countries">
- <li>Armenia</li>
- <li>Bahrain</li>
- <li>Bolivia</li>
- <li>Brazil</li>
- </ul>
- <!-- Commented out for testing
- <li>Bulgaria</li>
- <li>Canada</li>
- <li>Chile</li>
- <li>Cypress</li>
- <li>Dominican Republic</li>
- <li>Ecuador</li>
- <li>France</li>
- <li>Germany</li>
- <li>Greece</li>
- <li>Guatemala</li>
- <li>Haiti</li>
- <li>Honduras</li>
- <li>Hong Kong</li>
- <li>India</li>
- <li>Indonesia</li>
- <li>Japan</li>
- <li>Jordan</li>
- <li>Korea</li>
- <li>Kuwait</li>
- <li>Lebanon</li>
- <li>Mexico</li>
- <li>Morocco</li>
- <li>Netherlands Antilles</li>
- <li>Pakistan</li>
- <li>Panama</li>
- <li>Peru</li>
- <li>Philippines</li>
- <li>People's Republic of China</li>
- <li>Saudi Arabia</li>
- <li>Singapore</li>
- <li>South Korea</li>
- <li>Spain</li>
- <li>Tanzania</li>
- <li>United Arab Emirates</li>
- <li>Thailand</li>
- <li>Turkey</li>
- <li>Ukraine</li>
- <li>United Arab Emirates</li>
- <li>Venezuela</li>
- <li>Vietnam</li>
- <li>West Indies</li>
- -->
</body>
</html>
-
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..8737c28
--- /dev/null
+++ b/index.html
@@ -0,0 +1,95 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html>
+ <head>
+ <title>GMAP List - Jquery Plugin</title>
+ <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.8.0r4/build/reset-fonts-grids/reset-fonts-grids.css&2.8.0r4/build/base/base-min.css">
+ <link rel="stylesheet" href="style.css" type="text/css" media="screen" title="no title" charset="utf-8">
+ </head>
+ <body>
+ <div id="doc">
+ <div id="hd"><!-- header -->
+ <h1>GMAP LIST</h1>
+ <h2>A jquery plugin for creating maps from an HTML list</h2>
+ </div>
+ <div id="bd"><!-- body -->
+ <h3> Overview </h3>
+ <p>This plugin generates a Google Map from an HTML list. It performs a geocoding lookup on each of the <li>'s and adds the
+ resulting point to the map. Because each element requires a geocode lookup, lists with many elements may take a while to
+ render. A loading animation is displayed while the points are being looked up.</p>
+
+ <p>It was developed to be simple and require no dependencies, aside from Google Maps. Because of the overhead required for
+ looking up each address this plugin is not suitable for large data sets. The optimal size seems to be about ~10.</p>
+
+ <p>The Script takes a GMap2 instance as an argument. I chose not to have the plugin generate the GMap2 object to allow
+ for more flexibility in customizing the map. </p>
+
+ <h3>Download</h3>
+
+ <p><a href="http://github.com/ngmaloney/gmaplist/archives/master">GMap List</a></p>
+
+ <p>The project is hosted on <a href="http://github.com/ngmaloney/gmaplist">github</a>.</p>
+
+ <h3>Basic Usage</h3>
+
+ <pre>
+ <code class="html">
+ <div id="map" style="display:none"></div>
+ <ul id="newEngland">
+ <li>Connecticut</li>
+ <li>Maine</li>
+ <li>Massachusetts></li>
+ <li>New Hampshire</li>
+ <li>Rhode Island</li>
+ <li>Vermont</li>
+ </ul>
+ </code>
+
+ <code class="javascript">
+ <script>
+ gmap = new GMap2(document.getElementById('map'));
+ gmap.setCenter(new GLatLng(0, 0), 13);
+ $('#newEngland').gmaplist(gmap);
+ </script>
+ </code>
+ </pre>
+
+ <h3>Options</h3>
+
+ <p>The plugin accepts an options object. The following variables are accepted:</p>
+
+ <ul>
+ <li><strong>delay:</strong> The lookup delay in milliseconds.<br/>
+ Geocoding lookups need to be throttled to prevent 602 errors. The default value of 100ms is typically good enough.
+ </li>
+
+ <li><strong>loadingGraphic:</strong> Path to a loading graphic<br/>
+ The map is not displayed until all geocoding has been performed. This option is the path to a loading graphic
+ </li>
+
+ <li><strong>debug:</strong> Logs some debugging info to the console<br/>
+ Currently logs each point result from the Google gatLatLng() hook.
+ </li>
+ </ul>
+
+ <h3>More Examples</h3>
+
+ <p><a href="example1.html">Example 1</a> Displays 1 map containing a list of the New England states.</p>
+
+ <p><a href="example2.html">Example 2</a> Is a more advanced example that contains 2 maps, both of which are fired off as a click event. This is useful for larger maps as they have a longer loading time due to Geocoding.</p>
+ </div>
+
+ <h3>Assistance/Feedback</h3>
+
+ <p>If you have any feedback, questions, or need help my twitter account is <a href="http://twitter.com/ngmaloney">@ngmaloney</a>.</p>
+
+ <h3>Sponsor</h3>
+
+ <p>This plugin is sponsored by <a href="http://www.bentley.edu">Bentley Univeristy</a></p>
+
+ <div id="ft"><!-- footer -->
+ © 2010 Nicholas G. Maloney
+ </div>
+ </div>
+
+ </body>
+</html>
diff --git a/style.css b/style.css
new file mode 100644
index 0000000..26c0896
--- /dev/null
+++ b/style.css
@@ -0,0 +1,19 @@
+pre {
+ font: 100% courier,monospace;
+ border: 1px solid #ccc;
+ overflow: auto;
+ overflow-x: scroll;
+ width: 90%;
+ padding: 0 1em 1em 1em;
+ margin: 1em auto 2em auto;
+ background: #fff7f0;
+ color: #000
+}
+code {
+ font-size: 120%
+}
+
+#map, #country_map {
+ width:500px;
+ height:300px;
+}
\ No newline at end of file
|
ngmaloney/gmaplist | fd622d19584940683d953fbe881e98de7ab33ad2 | Found ANOTHER bug in example code | diff --git a/example1.html b/example1.html
index 2f2dafd..463bffa 100644
--- a/example1.html
+++ b/example1.html
@@ -1,34 +1,34 @@
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAKYaO3iHtIJp7vbWR-lwa_hTb-vLQlFZmc2N8bgWI8YDPp5FEVBQSnZeAcu9H26_1vNdOb0GvTDmVJA"></script>
<script>
google.load("maps", "2.x");
google.load("jquery", "1.3.1");
google.setOnLoadCallback(function() {
gmap = new GMap2(document.getElementById('map'));
gmap.setCenter(new GLatLng(0, 0), 13);
$('#newEngland').gmaplist(gmap);
});
</script>
<script src="jquery.gmaplist.js"></script>
<style media="screen" type="text/css">
#map, #country_map {
width:500px;
height:300px;
}
</style>
</head>
<body>
<div id="map" style="display:none"></div>
<ul id="newEngland">
<li>Connecticut</li>
<li>Maine</li>
- <li>Massachusetts></li>
+ <li>Massachusetts</li>
<li>New Hampshire</li>
<li>Rhode Island</li>
<li>Vermont</li>
</ul>
</body>
</html>
\ No newline at end of file
|
ngmaloney/gmaplist | a8e7b4233b0f9411626d0a515b804e8e38c6d89e | Fixed bug in README example code | diff --git a/README.txt b/README.txt
index 70617df..404a6be 100644
--- a/README.txt
+++ b/README.txt
@@ -1,40 +1,40 @@
# JQuery Google Maps List
** Overview **
This plugin generates a Google Map from an HTML list. It performs a geocoding lookup on each of the <li>'s and adds the resulting point to the map. Because each element requires a geocode lookup, lists with many elements may take a while to render. A loading animation is displayed while the points are being looked up.
It was developed to be simple and require no dependencies, aside from Google Maps. Because of the overhead required for looking up each address this plugin is not suitable for large data sets. The optimal size seems to be about ~10.
** Basic Usage **
(as reference only. See example1.html for functional code)
//The Script takes a GMap2 instance as an argument. I chose not to have the plugin generate the GMap2 object to allow for more flexibility in customizing the map.
<script>
- gmap = new GMap2(document.getElementById('country_map'));
+ gmap = new GMap2(document.getElementById('map'));
gmap.setCenter(new GLatLng(0, 0), 13);
$('#newEngland').gmaplist(gmap);
</script>
<div id="map" style="display:none"></div>
<ul id="newEngland">
<li>Connecticut</li>
<li>Maine</li>
<li>Massachusetts></li>
<li>New Hampshire</li>
<li>Rhode Island</li>
<li>Vermont</li>
</ul>
** Options **
The plugin accepts an options object. The following variables are accepted:
- delay: The lookup delay in milliseconds.
Geocoding lookups need to be throttled to prevent 602 errors. The default value of 100ms is typically good enough.
- loadingGraphic: Path to a loading graphic
The map is not displayed until all geocoding has been performed. This option is the path to a loading graphic
- debug: Logs some debugging info to the console
Currently logs each point result from the Google gatLatLng() hook.
|
jaxl/JAXL | 03a885320b97cce64ff84b52399c922f89ef4e0f | Removed instance variables that hold total bytes sent/received. | diff --git a/src/JAXL/core/jaxl_socket_client.php b/src/JAXL/core/jaxl_socket_client.php
index f399f17..d4bf834 100644
--- a/src/JAXL/core/jaxl_socket_client.php
+++ b/src/JAXL/core/jaxl_socket_client.php
@@ -1,263 +1,256 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLSocketClient implements JAXLClientBase
{
private $host = null;
private $port = null;
private $transport = null;
/** @var resource */
private $stream_context = null;
private $blocking = false;
public $fd = null;
public $errno = null;
public $errstr = null;
private $timeout = 10;
private $ibuffer = "";
private $obuffer = "";
private $compressed = false;
- private $recv_bytes = 0;
- private $send_bytes = 0;
-
/** @var callable */
private $recv_cb = null;
private $recv_chunk_size = 1024;
private $writing = false;
/**
* @param resource $stream_context Resource created with stream_context_create().
*/
public function __construct($stream_context = null)
{
$this->stream_context = $stream_context;
}
public function __destruct()
{
//JAXLLogger::debug("cleaning up xmpp socket...");
$this->disconnect();
}
/**
* Emits on on_read_ready.
*
* @param callable $recv_cb
*/
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
/**
* @param string | resource $socket_path
*/
public function connect($socket_path)
{
if (gettype($socket_path) == "string") {
$path_parts = explode(":", $socket_path);
$this->transport = $path_parts[0];
$this->host = substr($path_parts[1], 2, strlen($path_parts[1]));
if (count($path_parts) == 3) {
$this->port = $path_parts[2];
}
JAXLLogger::info("trying ".$socket_path);
if ($this->stream_context) {
$this->fd = @stream_socket_client(
$socket_path,
$this->errno,
$this->errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
$this->stream_context
);
} else {
$this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout);
}
} elseif (is_resource($socket_path)) {
$this->fd = &$socket_path;
} else {
// Some error occurred.
}
if ($this->fd) {
JAXLLogger::debug("connected to ".$socket_path."");
stream_set_blocking($this->fd, $this->blocking);
// watch descriptor for read/write events
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_read_ready')
));
return true;
} else {
JAXLLogger::error(sprintf(
"unable to connect %s with error no: %s, error str: %s",
is_null($socket_path) ? 'NULL' : $socket_path,
is_null($this->errno) ? 'NULL' : $this->errno,
is_null($this->errstr) ? 'NULL' : $this->errstr
));
$this->disconnect();
return false;
}
}
public function disconnect()
{
JAXLLoop::unwatch($this->fd, array(
'read' => true,
'write' => true
));
if (is_resource($this->fd)) {
fclose($this->fd);
}
$this->fd = null;
}
public function compress()
{
$this->compressed = true;
//stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ);
//stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE);
}
public function crypt()
{
// set blocking (since tls negotiation fails if stream is non-blocking)
stream_set_blocking($this->fd, true);
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
}
}
}
// switch back to non-blocking
stream_set_blocking($this->fd, false);
return $ret;
}
/**
* @param string $data
*/
public function send($data)
{
$this->obuffer .= $data;
// add watch for write events
if ($this->writing) {
return;
}
JAXLLoop::watch($this->fd, array(
'write' => array(&$this, 'on_write_ready')
));
$this->writing = true;
}
public function on_read_ready($fd)
{
//JAXLLogger::debug("on read ready called");
$raw = @fread($fd, $this->recv_chunk_size);
$bytes = strlen($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($fd);
if ($meta['eof'] === true) {
JAXLLogger::warning("socket eof, disconnecting");
JAXLLoop::unwatch($fd, array(
'read' => true
));
$this->disconnect();
return;
}
}
- $this->recv_bytes += $bytes;
- $total = $this->ibuffer.$raw;
-
$this->ibuffer = "";
- JAXLLogger::debug("read ".$bytes."/".$this->recv_bytes." of data");
+ JAXLLogger::debug("read $bytes bytes of data");
if ($bytes > 0) {
JAXLLogger::debug($raw);
}
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $raw);
}
}
public function on_write_ready($fd)
{
//JAXLLogger::debug("on write ready called");
$total = strlen($this->obuffer);
$bytes = @fwrite($fd, $this->obuffer);
- $this->send_bytes += $bytes;
- JAXLLogger::debug("sent ".$bytes."/".$this->send_bytes." of data");
+ JAXLLogger::debug("sent $bytes bytes of data");
JAXLLogger::debug(substr($this->obuffer, 0, $bytes));
$this->obuffer = substr($this->obuffer, $bytes, $total-$bytes);
// unwatch for write if obuffer is empty
if (strlen($this->obuffer) === 0) {
JAXLLoop::unwatch($fd, array(
'write' => true
));
$this->writing = false;
}
//JAXLLogger::debug("current obuffer size: ".strlen($this->obuffer)."");
}
}
|
jaxl/JAXL | e0fd8312dc3396607e05ed700edfb1575be41569 | Added write callback in order to listen for write requests. | diff --git a/src/JAXL/core/jaxl_loop.php b/src/JAXL/core/jaxl_loop.php
index 560abcb..8591456 100644
--- a/src/JAXL/core/jaxl_loop.php
+++ b/src/JAXL/core/jaxl_loop.php
@@ -1,168 +1,179 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLLoop
{
/**
* @var JAXLClock
*/
public static $clock = null;
private static $is_running = false;
private static $active_read_fds = 0;
private static $active_write_fds = 0;
private static $read_fds = array();
private static $read_cbs = array();
private static $write_fds = array();
private static $write_cbs = array();
private static $secs = 0;
private static $usecs = 30000;
+ private static $write_callback;
+
private function __construct()
{
}
private function __clone()
{
}
+ public static function set_write_callback($write_callback)
+ {
+ self::$write_callback = $write_callback;
+ }
+
public static function watch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
self::$read_fds[$fdid] = $fd;
self::$read_cbs[$fdid] = $opts['read'];
++self::$active_read_fds;
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
self::$write_fds[$fdid] = $fd;
self::$write_cbs[$fdid] = $opts['write'];
++self::$active_write_fds;
}
JAXLLogger::debug("Watch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function unwatch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
if (isset(self::$read_fds[$fdid])) {
unset(self::$read_fds[$fdid]);
unset(self::$read_cbs[$fdid]);
--self::$active_read_fds;
}
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
if (isset(self::$write_fds[$fdid])) {
unset(self::$write_fds[$fdid]);
unset(self::$write_cbs[$fdid]);
--self::$active_write_fds;
}
}
JAXLLogger::debug("Unwatch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function run()
{
if (!self::$is_running) {
self::$is_running = true;
self::$clock = new JAXLClock();
while ((self::$active_read_fds + self::$active_write_fds) > 0) {
+ if (is_callable(self::$write_callback)) {
+ call_user_func(self::$write_callback);
+ }
+
self::select();
}
JAXLLogger::debug("no more active fd's to select");
self::$is_running = false;
}
}
public static function select()
{
$read = self::$read_fds;
$write = self::$write_fds;
$except = null;
$changed = @stream_select($read, $write, $except, self::$secs, self::$usecs);
if ($changed === false) {
JAXLLogger::error("error in the event loop, shutting down...");
/*foreach (self::$read_fds as $fd) {
if (is_resource($fd)) {
print_r(stream_get_meta_data($fd));
}
}*/
exit;
} elseif ($changed > 0) {
// read callback
foreach ($read as $r) {
$fdid = array_search($r, self::$read_fds);
if (isset(self::$read_fds[$fdid])) {
call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]);
}
}
// write callback
foreach ($write as $w) {
$fdid = array_search($w, self::$write_fds);
if (isset(self::$write_fds[$fdid])) {
call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]);
}
}
self::$clock->tick();
} elseif ($changed === 0) {
//JAXLLogger::debug("nothing changed while selecting for read");
self::$clock->tick((self::$secs * pow(10, 6)) + self::$usecs);
}
}
}
diff --git a/src/JAXL/jaxl.php b/src/JAXL/jaxl.php
index 30a27bf..c633ca6 100644
--- a/src/JAXL/jaxl.php
+++ b/src/JAXL/jaxl.php
@@ -1,857 +1,864 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.1.0';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$cfg_defaults = array(
'auth_type' => 'PLAIN',
'bosh_hold' => null,
'bosh_rid' => null,
'bosh_url' => null,
'bosh_wait' => null,
'domain' => null,
'force_tls' => false,
'host' => null,
'jid' => null,
'log_colorize' => $this->log_colorize,
'log_level' => $this->log_level,
'log_path' => JAXLLogger::$path,
'multi_client' => false,
'pass' => false,
'port' => null,
'priv_dir' => getcwd().'/.jaxl',
'protocol' => null,
'resource' => null,
'stream_context' => null,
'strict' => true
);
$this->cfg = array_merge($cfg_defaults, $config);
// setup logger
JAXLLogger::$path = $this->cfg['log_path'];
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
// env
if ($this->cfg['strict']) {
JAXLLogger::info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => false inside JAXL config to disable this");
JAXLException::addHandlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = ($this->cfg['jid'] !== null) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = $this->cfg['priv_dir'];
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
JAXLLogger::info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
if (($this->cfg['host'] === null || $this->cfg['port'] === null) && $jid) {
// this dns lookup is blocking
JAXLLogger::info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
if ($this->cfg['host'] === null) {
$this->cfg['host'] = $host;
}
if ($this->cfg['port'] === null) {
$this->cfg['port'] = $port;
}
}
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
JAXLLogger::debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
$transport = new JAXLSocketClient($this->cfg['stream_context']);
}
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
+ JAXLLoop::set_write_callback(array($this, 'write'));
+
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
$this->cfg['pass'],
$this->cfg['resource'] !== null ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
$this->cfg['force_tls']
);
}
public function __destruct()
{
// delete pid file
JAXLLogger::info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLClientBase
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$classname = 'XEP'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if ($this->cfg['protocol'] !== null) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
JAXLLogger::info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// If connection to the destination fails.
if ($this->trans->errno == 61 ||
$this->trans->errno == 110 ||
$this->trans->errno == 111
) {
JAXLLogger::debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
JAXLLogger::debug("got sighup");
break;
// interrupt program
case SIGINT:
JAXLLogger::debug("got sigint");
break;
// software termination signal
case SIGTERM:
JAXLLogger::debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
JAXLLogger::debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
JAXLLogger::debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
JAXLLogger::debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
JAXLLogger::debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
JAXLLogger::debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->children as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
$pref_auth = $this->cfg['auth_type'];
// check if preferred auth type exists in available mechanisms
if (isset($mechs[$pref_auth]) && $mechs[$pref_auth]) {
JAXLLogger::debug("pref_auth ".$pref_auth." exists");
} else {
JAXLLogger::debug("pref_auth ".$pref_auth." doesn't exists");
JAXLLogger::error("preferred auth type not supported, trying $pref_auth");
}
$this->send_auth_pkt(
$pref_auth,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//JAXLLogger::debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->children as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->children as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
JAXLLogger::warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_INFO);
foreach ($query->children as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_ITEMS);
foreach ($query->children as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
+
+ public function write()
+ {
+ $this->ev->emit('on_write');
+ }
}
|
jaxl/JAXL | a636179d1c397ef5c3656f716e5a5c4593b9ba38 | Bump version to v3.1.0 | diff --git a/CHANGES.md b/CHANGES.md
index 1fbf40d..cb408ff 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,20 +1,35 @@
Changes
=======
-JAXL introduces changes that affect compatibility:
+JAXL introduces changes that affects on backward compatibility:
v3.1.0
-* PHP version >= 5.3: namespaces and anonymous functions.
-* All methods now in camel case format (i.e. JAXL->require_xep => JAXL->requireXep).
+* JAXL now use autoloader from Composer, so no more `require_once 'jaxl.php'`.
+* Sources moves to subfolder `src/JAXL`, class JAXLCtl goes from `jaxlctl`
+ to `src/JAXL/jaxlctl.php`, class HTTPDispathRule goes from `http_dispatcher.php`
+ to `src/JAXL/http_dispatch_rule.php`.
+* Class names XEP_* drops underscores and changed to XEP* to conform PSR-2.
+* All config parameters of JAXL sets on instantiation to their default values,
+ previously used code like `isset(JAXL->cfg['some-parameter'])` not need
+ `isset` anymore.
+* Globally defined log functions drops their underscores and moves
+ to JAXLLogger, _colorize renamed to JAXLLogger::cliLog.
+* JAXLXml->childrens fixed to children.
+* Some methods now in camel case format (i.e. JAXL->require_xep => JAXL->requireXep).
* All constants now in upper case format (i.e. JAXL::version => JAXL::VERSION).
* Renaming of methods that starts with _ prefix, they only used in private API
and shouldn't affect you.
+* JAXL_CWD not used anymore and changed to getcwd().
+* Move JAXL_MULTI_CLIENT to "multi_client" config parameter.
+* Globally defined NS_* now moves to XEPs constants. File xmpp_nss.php was
+ renamed to xmpp.php, so use XMPP::NS_*.
* JAXL_ERROR and other log levels goes to JAXLLogger::ERROR constant and so on.
* HTTP_CRLF and other HTTP_* codes goes to HTTPServer::HTTP_* constants.
* JAXLEvent->reg is not public property anymore, but you can get
it with JAXLEvent->getRegistry()
* In JAXLXml::construct first argument $name is required.
+* JAXL->add_exception_handlers moves to JAXLException::addHandlers.
* If some of your applications watch for debug message that starts with
"active read fds: " then you've warned about new message format
"Watch: active read fds: " and "Unwatch: active read fds: ".
diff --git a/README.md b/README.md
index 2f812e5..ee41733 100644
--- a/README.md
+++ b/README.md
@@ -1,51 +1,57 @@
-Jaxl v3.0.3
+Jaxl v3.1.0
-----------
Jaxl v3.x is a successor of v2.x (and is NOT backward compatible),
carrying a lot of code from v2.x while throwing away the ugly parts.
A lot of components have been re-written keeping in mind the feedback from
the developer community over the last 4 years. Also Jaxl shares a few
philosophies from my experience with erlang and python languages.
Jaxl is an asynchronous, non-blocking I/O, event based PHP library
for writing custom TCP/IP client and server implementations.
From it's previous versions, library inherits a full blown stable support
-for [XMPP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.3/xmpp).
-In v3.0, support for [HTTP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.3/http)
+for [XMPP protocol stack](https://github.com/jaxl/JAXL/tree/v3.1.0/xmpp).
+In v3.0, support for [HTTP protocol stack](https://github.com/jaxl/JAXL/tree/v3.1.0/http)
has also been added.
-At the heart of every protocol stack sits the [Core stack](https://github.com/jaxl/JAXL/tree/v3.0.3/core).
+At the heart of every protocol stack sits the [Core stack](https://github.com/jaxl/JAXL/tree/v3.1.0/core).
It contains all the building blocks for everything that we aim to do with Jaxl library.
Both XMPP and HTTP protocol stacks are written on top of the Core stack.
Infact the source code of protocol implementations knows nothing
about the standard (inbuilt) PHP socket and stream methods.
-[Examples](https://github.com/jaxl/JAXL/tree/v3.0.3/examples/)
+[Examples](https://github.com/jaxl/JAXL/tree/v3.1.0/examples/)
[Documentation](http://jaxl.readthedocs.org/)
[Group and Mailing List](https://groups.google.com/forum/#!forum/jaxl)
[Create a bug/issue](https://github.com/jaxl/JAXL/issues/new)
[Author](http://abhinavsingh.com/)
+## Installation
+
+```ShellSession
+php composer.phar require "jaxl/jaxl=^3.1.0"
+```
+
## Contributing
JAXL since v3.0.1 adopt [PSR-2](http://www.php-fig.org/psr/psr-2/).
To make it easier to maintain the code contribute your changes after they have
passed [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer)
and [PHPUnit](https://github.com/sebastianbergmann/phpunit). If possible, add
a unit tests for your changes into the *tests* folder.
To know current errors and failed tests, run:
```ShellSession
./vendor/bin/phpcs
./vendor/bin/phpunit
```
## License
The product licensed under the BSD 3-Clause license.
See [LICENSE](https://github.com/jaxl/JAXL/blob/master/LICENSE).
diff --git a/composer.json b/composer.json
index b705253..3549ba5 100644
--- a/composer.json
+++ b/composer.json
@@ -1,45 +1,50 @@
{
"name": "jaxl/jaxl",
"type": "library",
"description": "Jaxl - Async, Non-Blocking, Event based Networking Library in PHP.",
"keywords": ["xmpp", "jabber", "http", "asynchronous", "non blocking", "event loop", "php", "jaxl", "abhinavsingh"],
"homepage": "http://jaxl.readthedocs.org/en/latest/index.html",
"license": "BSD-3-Clause",
"support": {
"forum": "https://groups.google.com/forum/#!forum/jaxl",
"issues": "https://github.com/jaxl/JAXL/issues",
"source": "https://github.com/jaxl/JAXL"
},
"authors": [
{
"name": "Abhinavsingh",
"homepage": "https://abhinavsingh.com/"
}
],
"require": {
- "php": ">=5.3",
+ "php": ">=5.2.4",
"ext-curl": "*",
"ext-hash": "*",
"ext-json": "*",
"ext-libxml": "*",
"ext-openssl": "*",
"ext-pcre": "*",
"ext-sockets": "*"
},
"require-dev": {
"phpunit/phpunit": "^3.7.0",
"squizlabs/php_codesniffer": "*"
},
"suggest": {
"ext-pcntl": "Interrupt JAXL with signals"
},
"autoload": {
"classmap": [
"src/JAXL"
],
"exclude-from-classmap": [
"/tests/"
]
},
- "bin": ["jaxlctl"]
+ "bin": ["jaxlctl"],
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.1.x-dev"
+ }
+ }
}
diff --git a/docs/conf.py b/docs/conf.py
index 101da34..d2c835a 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,242 +1,242 @@
# -*- coding: utf-8 -*-
#
# Jaxl documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 15 03:08:42 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode']
# , 'sphinxcontrib.phpdomain'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Jaxl'
copyright = u'2012, Abhinav Singh'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '3.0'
# The full version, including alpha/beta/rc tags.
-release = '3.0.3'
+release = '3.1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'pastie'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Jaxldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Jaxl.tex', u'Jaxl Documentation',
u'Abhinav Singh', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'jaxl', u'Jaxl Documentation',
[u'Abhinav Singh'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Jaxl', u'Jaxl Documentation',
u'Abhinav Singh', 'Jaxl', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
diff --git a/docs/users/getting_started.rst b/docs/users/getting_started.rst
index 6f57e96..8b02e91 100644
--- a/docs/users/getting_started.rst
+++ b/docs/users/getting_started.rst
@@ -1,149 +1,148 @@
Getting Started
===============
Requirements
------------
No external component or library is required.
You simply need a standard PHP installation to work with Jaxl.
Library has been developed and tested extensively on
linux operating systems. But there is no reason why it should
not work on other OS. File an `issue <https://github.com/jaxl/JAXL/issues/new>`_ if you face any glitches.
Install
-------
Use `Composer <https://getcomposer.org>`_ to install:
-php composer.phar require "jaxl/jaxl=^3.0.3"
-php composer.phar update
+php composer.phar require "jaxl/jaxl=^3.1.0"
Then use autoloader in your application:
require dirname(__FILE__) . '/vendor/autoload.php';
Library Structure
-----------------
Jaxl library comprises of following packages:
* ``jaxl-core``
contains generic networking and eventing components
* ``jaxl-xmpp``
contains xmpp rfc implementation
* ``jaxl-xmpp-xep``
contains various xmpp xep implementation
* ``jaxl-http``
contains http rfc implementation
* ``jaxl-docs``
this documentation comes from this package
* ``jaxl-tests``
test suites for all the above packages
Inside Jaxl everything that you will interact with will be an object which
will emit events and callbacks which we will be able to catch in our applications
for custom processing and routing. Listed below are a few main objects:
#. Core Stack
* ``JAXLLoop``
main select loop
* ``JAXLClock``
timed job/callback dispatcher
* ``JAXLEvent``
event registry and emitter
* ``JAXLFsm``
generic finite state machine
* ``JAXLSocketClient``
generic tcp/udp client
* ``JAXLSocketServer``
generic tcp/udp server
* ``JAXLXmlStream``
streaming XML parser
* ``JAXLXml``
custom XML object implementation
* ``JAXLLogger``
logging facility
#. XMPP Stack
* ``XMPPStream``
base xmpp rfc implementation
* ``XMPPStanza``
provides easy access patterns over xmpp stanza (wraps ``JAXLXml``)
* ``XMPPIq``
xmpp iq stanza object (extends ``XMPPStanza``)
* ``XMPPMsg``
xmpp msg stanza object (extends ``XMPPStanza``)
* ``XMPPPres``
xmpp pres stanza object (extends ``XMPPStanza``)
* ``XMPPXep``
abstract xmpp extension (extended by XEP implementations)
* ``XMPPJid``
xmpp jid object
#. HTTP Stack
* ``HTTPServer``
http server implementation
* ``HTTPClient``
http client implementation
* ``HTTPRequest``
http request object
* ``HTTPResponse``
http response object
Questions, Bugs and Issues
--------------------------
If you have any questions kindly post them on `google groups <https://groups.google.com/forum/#!forum/jaxl>`_. Groups are the quickest
way to get an answer to your questions which is actively monitored by core developers.
If you are facing a bug or issue, please report that it on `github issue tracker <https://github.com/abhinavsingh/JAXL/issues/new>`_.
You can even :ref:`contribute to the library <developer-introduction>` if you already have fixed the bug.
diff --git a/src/JAXL/jaxl.php b/src/JAXL/jaxl.php
index 80900fe..30a27bf 100644
--- a/src/JAXL/jaxl.php
+++ b/src/JAXL/jaxl.php
@@ -1,569 +1,569 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
- const VERSION = '3.0.3';
+ const VERSION = '3.1.0';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$cfg_defaults = array(
'auth_type' => 'PLAIN',
'bosh_hold' => null,
'bosh_rid' => null,
'bosh_url' => null,
'bosh_wait' => null,
'domain' => null,
'force_tls' => false,
'host' => null,
'jid' => null,
'log_colorize' => $this->log_colorize,
'log_level' => $this->log_level,
'log_path' => JAXLLogger::$path,
'multi_client' => false,
'pass' => false,
'port' => null,
'priv_dir' => getcwd().'/.jaxl',
'protocol' => null,
'resource' => null,
'stream_context' => null,
'strict' => true
);
$this->cfg = array_merge($cfg_defaults, $config);
// setup logger
JAXLLogger::$path = $this->cfg['log_path'];
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
// env
if ($this->cfg['strict']) {
JAXLLogger::info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => false inside JAXL config to disable this");
JAXLException::addHandlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = ($this->cfg['jid'] !== null) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = $this->cfg['priv_dir'];
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
JAXLLogger::info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
if (($this->cfg['host'] === null || $this->cfg['port'] === null) && $jid) {
// this dns lookup is blocking
JAXLLogger::info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
if ($this->cfg['host'] === null) {
$this->cfg['host'] = $host;
}
if ($this->cfg['port'] === null) {
$this->cfg['port'] = $port;
}
}
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
JAXLLogger::debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
$transport = new JAXLSocketClient($this->cfg['stream_context']);
}
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
$this->cfg['pass'],
$this->cfg['resource'] !== null ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
$this->cfg['force_tls']
);
}
public function __destruct()
{
// delete pid file
JAXLLogger::info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLClientBase
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$classname = 'XEP'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if ($this->cfg['protocol'] !== null) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
JAXLLogger::info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// If connection to the destination fails.
if ($this->trans->errno == 61 ||
$this->trans->errno == 110 ||
$this->trans->errno == 111
) {
JAXLLogger::debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
JAXLLogger::debug("got sighup");
break;
// interrupt program
case SIGINT:
JAXLLogger::debug("got sigint");
break;
// software termination signal
case SIGTERM:
JAXLLogger::debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
JAXLLogger::debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
|
jaxl/JAXL | 13abcc9cb6e66004f214ff871b7c2893545a554b | Revert "Revert "Fix examples to conform to requirements for PHP 5.2.4"" | diff --git a/docs/users/xmpp_examples.rst b/docs/users/xmpp_examples.rst
index 0f11fdc..30bf4b8 100644
--- a/docs/users/xmpp_examples.rst
+++ b/docs/users/xmpp_examples.rst
@@ -1,117 +1,123 @@
XMPP Examples
=============
Echo Bot Client
---------------
include ``jaxl.php`` and initialize a new ``JAXL`` instance:
.. code-block:: ruby
$client = new JAXL(array(
'jid' => '[email protected]',
'pass' => 'password'
));
We just initialized a new ``JAXL`` instance by passing our jabber client ``jid`` and ``pass``.
View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor.
Next we need to register callbacks on events of interest using ``JAXL::add_cb/2`` method as shown below:
.. code-block:: ruby
- $client->add_cb('on_auth_success', function () {
+ function on_auth_success_callback()
+ {
global $client;
$client->set_status("available!"); // set your status
$client->get_vcard(); // fetch your vcard
$client->get_roster(); // fetch your roster list
- });
+ }
+ $client->add_cb('on_auth_success', 'on_auth_success_callback');
- $client->add_cb('on_chat_message', function ($stanza) {
+ function on_chat_message_callback($stanza)
+ {
global $client;
// echo back
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
- });
+ }
+ $client->add_cb('on_chat_message', 'on_chat_message_callback');
- $client->add_cb('on_disconnect', function () {
+ function on_disconnect_callback()
+ {
JAXLLogger::debug("got on_disconnect cb");
- });
+ }
+ $client->add_cb('on_disconnect', 'on_disconnect_callback');
We just registered callbacks on ``on_auth_success``, ``on_chat_message`` and ``on_disconnect`` events
that will occur inside our configured ``JAXL`` instance lifecycle.
We also passed a method that will be called (with parameters if any) when the event has been detected.
See list of :ref:`available event callbacks <jaxl-instance>` that we can hook to inside ``JAXL`` instance lifecycle.
Received ``$msg`` parameter with ``on_chat_message`` event callback above, will be an instance of ``XMPPMsg`` which
extends ``XMPPStanza`` class, that allows us easy to use access patterns to common XMPP stanza attributes like
``to``, ``from``, ``type``, ``id`` to name a few.
We were also able to access our xmpp client full jabber id by calling ``$client->full_jid``. This attribute of
``JAXL`` instance is available from ``on_auth_success`` event. ``full_jid`` attribute is an instance of ``XMPPJid``.
To send our echo back ``$msg`` packet we called ``JAXL::send/1`` which accepts a single parameter which MUST be
an instance of ``JAXLXml``. Since ``XMPPStanza`` is a wrapper upon ``JAXLXml`` we can very well pass our modified
``$msg`` object to the send method.
Read more about various :ref:`XML Objects <xml-objects>` and how they make writing XMPP applications fun and easy.
You can also :ref:`add custom access patterns <xml-objects>` upon received ``XMPPStanza`` objects. Since all access
patterns are evaluated upon first access and cached for later usage, adding hundreds of custom access patterns that
retrieves information from 100th child of received XML packet will not be an issue.
We will finally start our xmpp client by calling:
.. code-block:: ruby
$client->start();
See list of :ref:`available options <jaxl-instance>` that can be passed to the ``JAXL::start/2`` method.
These options are particularly useful for debugging and monitoring.
Echo Bot BOSH Client
--------------------
Everything goes same for a cli BOSH client. To run above echo bot client example as a bosh client simply
pass additional parameters to ``JAXL`` constructor:
.. code-block:: ruby
$client = new JAXL(array(
'jid' => '[email protected]',
'pass' => 'password',
'bosh_url' => 'http://localhost:5280/http-bind'
));
You can even pass custom values for ``hold``, ``wait`` and other attributes.
View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor.
Echo Bot External Component
---------------------------
Again almost everything goes same for an external component except a few custom ``JAXL`` constructor
parameter as shown below:
.. code-block:: ruby
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required) destination socket
'host' => $argv[3],
'port' => $argv[4]
));
We will also need to include ``XEP0114`` which implements Jabber Component XMPP Extension.
.. code-block:: ruby
// (required)
$comp->require_xep(array(
'0114' // jabber component protocol
));
``JAXL::require_xep/1`` accepts an array of XEP numbers passed as strings.
diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php
index 13d8ca9..9d6e535 100644
--- a/examples/echo_bosh_bot.php
+++ b/examples/echo_bosh_bot.php
@@ -1,107 +1,115 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 3) {
echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'bosh_url' => 'http://localhost:5280/http-bind',
// (optional) srv lookup is done if not provided
// for bosh client 'host' value is used for 'route' attribute
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
// for bosh client 'port' value is used for 'route' attribute
//'port' => 5222,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXLLogger::INFO
));
//
// add necessary event callbacks here
//
-$client->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
global $client;
JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
-});
+}
+$client->add_cb('on_auth_success', 'on_auth_success_callback');
-$client->add_cb('on_auth_failure', function ($reason) {
+function on_auth_failure_callback($reason)
+{
global $client;
$client->send_end_stream();
JAXLLogger::info("got on_auth_failure cb with reason $reason");
-});
+}
+$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
-$client->add_cb('on_chat_message', function ($stanza) {
+function on_chat_message_callback($stanza)
+{
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
-});
+}
+$client->add_cb('on_chat_message', 'on_chat_message_callback');
-$client->add_cb('on_disconnect', function () {
+function on_disconnect_callback()
+{
JAXLLogger::info("got on_disconnect cb");
-});
+}
+$client->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/echo_bot.php b/examples/echo_bot.php
index ec667d9..221e073 100644
--- a/examples/echo_bot.php
+++ b/examples/echo_bot.php
@@ -1,148 +1,161 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// Run as:
// php examples/echo_bot.php root@localhost password
// php examples/echo_bot.php root@localhost password DIGEST-MD5
// php examples/echo_bot.php localhost "" ANONYMOUS
if ($argc < 3) {
echo "Usage: $argv[0] jid pass auth_type".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (optional) srv lookup is done if not provided
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
//'port' => 5222,
// (optional) defaults to false
//'force_tls' => true,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXLLogger::INFO
));
//
// required XEP's
//
$client->require_xep(array(
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
-$client->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
global $client;
JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
-});
+}
+$client->add_cb('on_auth_success', 'on_auth_success_callback');
// by default JAXL instance catches incoming roster list results and updates
// roster list is parsed/cached and an event 'on_roster_update' is emitted
-$client->add_cb('on_roster_update', function () {
+function on_roster_update_callback()
+{
//global $client;
//print_r($client->roster);
-});
+}
+$client->add_cb('on_roster_update', 'on_roster_update_callback');
-$client->add_cb('on_auth_failure', function ($reason) {
+function on_auth_failure_callback($reason)
+{
global $client;
- JAXLLogger::info("got on_auth_failure cb with reason $reason");
+
$client->send_end_stream();
-});
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
+}
+$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
-$client->add_cb('on_chat_message', function ($stanza) {
+function on_chat_message_callback($stanza)
+{
global $client;
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
-});
+}
+$client->add_cb('on_chat_message', 'on_chat_message_callback');
-$client->add_cb('on_presence_stanza', function ($stanza) {
+function on_presence_stanza_callback($stanza)
+{
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
JAXLLogger::info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
-});
+}
+$client->add_cb('on_presence_stanza', 'on_presence_stanza_callback');
-$client->add_cb('on_disconnect', function () {
+function on_disconnect_callback()
+{
JAXLLogger::info("got on_disconnect cb");
-});
+}
+$client->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$client->start(array(
'--with-debug-shell' => true,
'--with-unix-sock' => true
));
echo "done".PHP_EOL;
diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php
index 4ca3646..e205de5 100644
--- a/examples/echo_component_bot.php
+++ b/examples/echo_component_bot.php
@@ -1,99 +1,107 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc != 5) {
echo "Usage: $argv[0] jid pass host port".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'host' => $argv[3],
'port' => $argv[4],
'log_level' => JAXLLogger::INFO
));
//
// XEP's required (required)
//
$comp->require_xep(array(
'0114' // jabber component protocol
));
//
// add necessary event callbacks here
//
-$comp->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
JAXLLogger::info("got on_auth_success cb");
-});
+}
+$comp->add_cb('on_auth_success', 'on_auth_success_callback');
-$comp->add_cb('on_auth_failure', function ($reason) {
+function on_auth_failure_callback($reason)
+{
global $comp;
$comp->send_end_stream();
JAXLLogger::info("got on_auth_failure cb with reason $reason");
-});
+}
+$comp->add_cb('on_auth_failure', 'on_auth_failure_callback');
-$comp->add_cb('on_chat_message', function ($stanza) {
+function on_chat_message_callback($stanza)
+{
global $comp;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $comp->jid->to_string();
$comp->send($stanza);
-});
+}
+$comp->add_cb('on_chat_message', 'on_chat_message_callback');
-$comp->add_cb('on_disconnect', function () {
+function on_disconnect_callback()
+{
JAXLLogger::info("got on_disconnect cb");
-});
+}
+$comp->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$comp->start();
echo "done".PHP_EOL;
diff --git a/examples/http_bind.php b/examples/http_bind.php
index 35f032e..e9ef42a 100644
--- a/examples/http_bind.php
+++ b/examples/http_bind.php
@@ -1,65 +1,67 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if (!isset($_GET['jid']) || !isset($_GET['pass'])) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $_GET['jid'],
'pass' => $_GET['pass'],
'bosh_url' => 'http://localhost:5280/http-bind',
'log_level' => JAXLLogger::DEBUG
));
-$client->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
global $client;
JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
-});
+}
+$client->add_cb('on_auth_success', 'on_auth_success_callback');
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php
index d7f9cbc..de65904 100644
--- a/examples/http_pre_bind.php
+++ b/examples/http_pre_bind.php
@@ -1,99 +1,104 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// http pre bind php script
$body = file_get_contents("php://input");
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (!isset($attrs['to']) &&
!isset($attrs['rid']) &&
!isset($attrs['wait']) &&
!isset($attrs['hold'])
) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
$to = (string)$attrs['to'];
$rid = (int)$attrs['rid'];
$wait = (int)$attrs['wait'];
$hold = (int)$attrs['hold'];
list($host, $port) = JAXLUtil::get_dns_srv($to);
$client = new JAXL(array(
'domain' => $to,
'host' => $host,
'port' => $port,
'bosh_url' => 'http://localhost:5280/http-bind',
'bosh_rid' => $rid,
'bosh_wait' => $wait,
'bosh_hold' => $hold,
'auth_type' => 'ANONYMOUS',
'log_level' => JAXLLogger::INFO
));
-$client->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
global $client;
JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
echo sprintf(
'<body xmlns="%s" sid="%s" rid="%s" jid="%s"/>',
XEP0206::NS_HTTP_BIND,
$client->xeps['0206']->sid,
$client->xeps['0206']->rid,
$client->full_jid->to_string()
);
exit;
-});
+}
+$client->add_cb('on_auth_success', 'on_auth_success_callback');
-$client->add_cb('on_auth_failure', function ($reason) {
+function on_auth_failure_callback($reason)
+{
global $client;
- JAXLLogger::info("got on_auth_failure cb with reason $reason");
+
$client->send_end_stream();
-});
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
+}
+$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php
index 3a0d3e8..be537c3 100644
--- a/examples/muc_log_bot.php
+++ b/examples/muc_log_bot.php
@@ -1,147 +1,157 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 5) {
echo "Usage: $argv[0] host jid pass [email protected] nickname".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[2],
'pass' => $argv[3],
'host' => $argv[1],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0045', // MUC
'0203', // Delayed Delivery
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$_room_full_jid = $argv[4]."/".$argv[5];
$room_full_jid = new XMPPJid($_room_full_jid);
-$client->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
global $client, $room_full_jid;
JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// join muc room
$client->xeps['0045']->join_room($room_full_jid);
-});
+}
+$client->add_cb('on_auth_success', 'on_auth_success_callback');
-$client->add_cb('on_auth_failure', function ($reason) {
+function on_auth_failure_callback($reason)
+{
global $client;
$client->send_end_stream();
JAXLLogger::info("got on_auth_failure cb with reason $reason");
-});
+}
+$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
-$client->add_cb('on_groupchat_message', function ($stanza) {
+function on_groupchat_message_callback($stanza)
+{
global $client;
$from = new XMPPJid($stanza->from);
$delay = $stanza->exists('delay', XEP0203::NS_DELAYED_DELIVERY);
if ($from->resource) {
echo sprintf(
"message stanza rcvd from %s saying... %s, %s".PHP_EOL,
$from->resource,
$stanza->body,
$delay ? "delay timestamp ".$delay->attrs['stamp'] : "timestamp ".gmdate("Y-m-dTH:i:sZ")
);
} else {
$subject = $stanza->exists('subject');
if ($subject) {
echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".
$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL;
}
}
-});
+}
+$client->add_cb('on_groupchat_message', 'on_chat_message_callback');
-$client->add_cb('on_presence_stanza', function ($stanza) {
+function on_presence_stanza_callback($stanza)
+{
global $client, $room_full_jid;
$from = new XMPPJid($stanza->from);
// self-stanza received, we now have complete room roster
if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) {
if (($x = $stanza->exists('x', XEP0045::NS_MUC.'#user')) !== false) {
if (($status = $x->exists('status', null, array('code' => '110'))) !== false) {
$item = $x->exists('item');
JAXLLogger::info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].
", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']);
} else {
JAXLLogger::info("xmlns #user have no x child element");
}
} else {
JAXLLogger::warning("=======> odd case 1");
}
} elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) {
// stanza from other users received
if (($x = $stanza->exists('x', XEP0045::NS_MUC.'#user')) !== false) {
$item = $x->exists('item');
echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".
$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL;
} else {
JAXLLogger::warning("=======> odd case 2");
}
} else {
JAXLLogger::warning("=======> odd case 3");
}
-});
+}
+$client->add_cb('on_presence_stanza', 'on_presence_stanza_callback');
-$client->add_cb('on_disconnect', function () {
+function on_disconnect_callback()
+{
JAXLLogger::info("got on_disconnect cb");
-});
+}
+$client->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/pipes.php b/examples/pipes.php
index a1ba30c..b426bab 100644
--- a/examples/pipes.php
+++ b/examples/pipes.php
@@ -1,55 +1,57 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// configure logger
JAXLLogger::$level = JAXLLogger::INFO;
// initialize
$pipe_name = getmypid();
$pipe = new JAXLPipe($pipe_name);
// add read event callback
-$pipe->set_callback(function ($data) {
+function read_event_callback($data)
+{
global $pipe;
JAXLLogger::info("read ".trim($data)." from pipe");
-});
+}
+$pipe->set_callback('read_event_callback');
JAXLLoop::run();
echo "done".PHP_EOL;
diff --git a/examples/publisher.php b/examples/publisher.php
index 4014245..d37171b 100644
--- a/examples/publisher.php
+++ b/examples/publisher.php
@@ -1,102 +1,108 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 3) {
echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
-$client->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
global $client;
JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// publish
$item = new JAXLXml('item', null, array('id' => time()));
$item->c('entry', 'http://www.w3.org/2005/Atom');
$item->c('title')->t('Soliloquy')->up();
$item->c('summary')->t('To be, or not to be: that is the question')->up();
$item->c(
'link',
null,
array('rel' => 'alternate', 'type' => 'text/html', 'href' => 'http://denmark.lit/2003/12/13/atom03')
)->up();
$item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up();
$item->c('published')->t('2003-12-13T18:30:02Z')->up();
$item->c('updated')->t('2003-12-13T18:30:02Z')->up();
$client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item);
-});
+}
+$client->add_cb('on_auth_success', 'on_auth_success_callback');
-$client->add_cb('on_auth_failure', function ($reason) {
+function on_auth_failure_callback($reason)
+{
global $client;
$client->send_end_stream();
JAXLLogger::info("got on_auth_failure cb with reason $reason");
-});
+}
+$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
-$client->add_cb('on_disconnect', function () {
+function on_disconnect_callback()
+{
JAXLLogger::info("got on_disconnect cb");
-});
+}
+$client->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/register_user.php b/examples/register_user.php
index 62cb463..a9437d9 100644
--- a/examples/register_user.php
+++ b/examples/register_user.php
@@ -1,164 +1,170 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 2) {
echo "Usage: $argv[0] domain".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'log_level' => JAXLLogger::DEBUG
));
$client->require_xep(array(
'0077' // InBand Registration
));
//
// Below are two states which become part of our client's xmpp_stream lifecycle
// consider as if these methods are directly inside xmpp_stream state machine.
//
// Note: $stanza = $args[0] is an instance of JAXLXml in xmpp_stream state methods,
// it is yet not ready for easy access patterns available on XMPPStanza instances.
//
$form = array();
function wait_for_register_response($event, $args)
{
global $client, $form;
if ($event == 'stanza_cb') {
$stanza = $args[0];
if ($stanza->name == 'iq') {
$form['type'] = $stanza->attrs['type'];
if ($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
} elseif ($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo sprintf(
"registration failed with error code: %s and type: %s".PHP_EOL,
$error->attrs['code'],
$error->attrs['type']
);
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
}
}
} else {
JAXLLogger::notice("unhandled event $event rcvd");
}
}
function wait_for_register_form($event, $args)
{
global $client, $form;
$stanza = $args[0];
$query = $stanza->exists('query', XEP0077::NS_INBAND_REGISTER);
if ($query) {
$instructions = $query->exists('instructions');
if ($instructions) {
echo $instructions->text.PHP_EOL;
}
foreach ($query->children as $k => $child) {
if ($child->name != 'instructions') {
$form[$child->name] = readline($child->name.":");
}
}
$client->xeps['0077']->set_form($stanza->attrs['from'], $form);
return "wait_for_register_response";
} else {
$client->end_stream();
return "logged_out";
}
}
//
// add necessary event callbacks here
//
-$client->add_cb('on_stream_features', function ($stanza) {
+function on_stream_features_callback($stanza)
+{
global $client, $argv;
$client->xeps['0077']->get_form($argv[1]);
return "wait_for_register_form";
-});
+}
+$client->add_cb('on_stream_features', 'on_stream_features_callback');
-$client->add_cb('on_disconnect', function () {
+function on_disconnect_callback()
+{
global $form;
JAXLLogger::info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
-});
+}
+$client->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$client->start();
//
// if registration was successful
// try to connect with newly registered account
//
if ($form['type'] == 'result') {
JAXLLogger::info("connecting newly registered user account");
$client = new JAXL(array(
'jid' => $form['username'].'@'.$argv[1],
'pass' => $form['password'],
'log_level' => JAXLLogger::DEBUG
));
- $client->add_cb('on_auth_success', function () {
+ function on_auth_success_callback()
+ {
global $client;
$client->set_status('Available');
- });
+ }
+ $client->add_cb('on_auth_success', 'on_auth_success_callback');
$client->start();
}
echo "done".PHP_EOL;
diff --git a/examples/subscriber.php b/examples/subscriber.php
index b3b0b18..d7a4b30 100644
--- a/examples/subscriber.php
+++ b/examples/subscriber.php
@@ -1,97 +1,105 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 3) {
echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
-$client->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
global $client;
JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// subscribe
$client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node');
-});
+}
+$client->add_cb('on_auth_success', 'on_auth_success_callback');
-$client->add_cb('on_auth_failure', function ($reason) {
+function on_auth_failure_callback($reason)
+{
global $client;
$client->send_end_stream();
JAXLLogger::info("got on_auth_failure cb with reason $reason");
-});
+}
+$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
-$client->add_cb('on_headline_message', function ($stanza) {
+function on_headline_message_callback($stanza)
+{
global $client;
if (($event = $stanza->exists('event', XEP0060::NS_PUBSUB.'#event'))) {
JAXLLogger::info("got pubsub event");
} else {
JAXLLogger::warning("unknown headline message rcvd");
}
-});
+}
+$client->add_cb('on_headline_message', 'on_headline_message_callback');
-$client->add_cb('on_disconnect', function () {
+function on_disconnect_callback()
+{
JAXLLogger::info("got on_disconnect cb");
-});
+}
+$client->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php
index 029e8c9..6ca3288 100644
--- a/examples/xmpp_rest.php
+++ b/examples/xmpp_rest.php
@@ -1,75 +1,79 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// View explanation for this example here:
// https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ
if ($argc < 3) {
echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
// initialize xmpp client
$xmpp = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
// register callbacks on required xmpp events
-$xmpp->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
global $xmpp;
JAXLLogger::info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string());
-});
+}
+$xmpp->add_cb('on_auth_success', 'on_auth_success_callback');
// initialize http server
$http = new HTTPServer();
// add generic callback
// you can also dispatch REST style callback
// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules
-$http->cb = function ($request) {
+function generic_callback($request)
+{
// For demo purposes we simply return xmpp client full jid
global $xmpp;
$request->ok($xmpp->full_jid->to_string());
-};
+}
+$http->cb = 'generic_callback';
// This will start main JAXLLoop,
// hence we don't need to call $http->start() explicitly
$xmpp->start();
diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php
index 734e5ed..284d234 100644
--- a/examples/xoauth2_gtalk_client.php
+++ b/examples/xoauth2_gtalk_client.php
@@ -1,98 +1,106 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc != 3) {
echo "Usage: $argv[0] jid access_token".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// force tls
'force_tls' => true,
// (required) perform X-OAUTH2
'auth_type' => 'X-OAUTH2',
// (optional)
//'resource' => 'resource',
'log_level' => JAXLLogger::DEBUG
));
//
// add necessary event callbacks here
//
-$client->add_cb('on_auth_success', function () {
+function on_auth_success_callback()
+{
global $client;
JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
-});
+}
+$client->add_cb('on_auth_success', 'on_auth_success_callback');
-$client->add_cb('on_auth_failure', function ($reason) {
+function on_auth_failure_callback($reason)
+{
global $client;
$client->send_end_stream();
JAXLLogger::info("got on_auth_failure cb with reason $reason");
-});
+}
+$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
-$client->add_cb('on_chat_message', function ($stanza) {
+function on_chat_message_callback($stanza)
+{
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
-});
+}
+$client->add_cb('on_chat_message', 'on_chat_message_callback');
-$client->add_cb('on_disconnect', function () {
+function on_disconnect_callback()
+{
JAXLLogger::info("got on_disconnect cb");
-});
+}
+$client->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
|
jaxl/JAXL | 70e41c62caf8aae4975da51af3879d9fc32b0c68 | Fix children typo | diff --git a/docs/users/xml_objects.rst b/docs/users/xml_objects.rst
index a92c58b..3afbfc8 100644
--- a/docs/users/xml_objects.rst
+++ b/docs/users/xml_objects.rst
@@ -1,122 +1,122 @@
.. _xml-objects:
Xml Objects
===========
Jaxl library works with custom XML implementation which is similar to
inbuild PHP XML functions but is lightweight and easy to work with.
JAXLXml
-------
``JAXLXml`` is the base XML object. Open up :ref:`Jaxl interactive shell <jaxl-instance>` and try some xml object creation/manipulation:
>>> ./jaxlctl shell
jaxl 1>
jaxl 1> $xml = new JAXLXml(
....... 'dummy',
....... 'dummy:packet',
....... array('attr1' => '[email protected]', 'attr2' => ''),
....... 'Hello World!'
....... );
jaxl 2> echo $xml->to_string();
<dummy xmlns="dummy:packet" attr1="[email protected]" attr2="">Hello World!</dummy>
jaxl 3>
``JAXLXml`` constructor instance accepts following parameters:
* ``JAXLXml($name, $ns, $attrs, $text)``
* ``JAXLXml($name, $ns, $attrs)``
* ``JAXLXml($name, $ns, $text)``
* ``JAXLXml($name, $attrs, $text)``
* ``JAXLXml($name, $attrs)``
* ``JAXLXml($name, $ns)``
* ``JAXLXml($name)``
``JAXLXml`` draws inspiration from StropheJS XML Builder class. Below are available methods
for modifying and manipulating an ``JAXLXml`` object:
* ``t($text, $append = false)``
update text of current rover
* ``c($name, $ns = null, $attrs = array(), $text = null)``
append a child node at current rover
* ``cnode($node)``
append a JAXLXml child node at current rover
* ``up()``
move rover to one step up the xml tree
* ``top()``
move rover back to top element in the xml tree
* ``exists($name, $ns = null, $attrs = array())``
checks if a child with $name exists, return child ``JAXLXml`` if found otherwise false. This function returns at first matching child.
* ``update($name, $ns = null, $attrs = array(), $text = null)``
update specified child element
* ``attrs($attrs)``
merge new attrs with attributes of current rover
* ``match_attrs($attrs)``
pass a kv pair of ``$attrs``, return bool if all passed keys matches their respective values in the xml packet
* ``to_string()``
get string representation of the object
``JAXLXml`` maintains a rover which points to the current level down the XML tree where
manipulation is performed.
XMPPStanza
----------
In the world of XMPP where everything incoming and outgoing payload is an ``JAXLXml`` instance code can become nasty,
developers can get lost in dirty XML manipulations spreaded all over the application code base and what not.
XML structures are not only unreadable for humans but even for machine.
While an instance of ``JAXLXml`` provide direct access to XML ``name``, ``ns`` and ``text``, it can become painful and
-time consuming when trying to retrieve or modify a particular ``attrs`` or ``childrens``. I was fed up of doing
+time consuming when trying to retrieve or modify a particular ``attrs`` or ``children``. I was fed up of doing
``getAttributeByName``, ``setAttributeByName``, ``getChild`` etc everytime i had to access common XMPP Stanza attributes.
``XMPPStanza`` is a wrapper on top of ``JAXLXml`` objects. Preserving all the functionalities of base ``JAXLXml``
instance it also provide direct access to most common XMPP Stanza attributes like ``to``, ``from``, ``id``, ``type`` etc.
It also provides a framework for adding custom access patterns.
``XMPPMsg``, ``XMPPPres`` and ``XMPPIq`` extends ``XMPPStanza`` and also add a few custom access patterns like
``body``, ``thread``, ``subject``, ``status``, ``show`` etc.
Here is a list of default access patterns:
#. ``name``
#. ``ns``
#. ``text``
#. ``attrs``
- #. ``childrens``
+ #. ``children``
#. ``to``
#. ``from``
#. ``id``
#. ``type``
#. ``to_node``
#. ``to_domain``
#. ``to_resource``
#. ``from_node``
#. ``from_domain``
#. ``from_resource``
#. ``status``
#. ``show``
#. ``priority``
#. ``body``
#. ``thread``
#. ``subject``
diff --git a/examples/register_user.php b/examples/register_user.php
index fee6de1..62cb463 100644
--- a/examples/register_user.php
+++ b/examples/register_user.php
@@ -1,164 +1,164 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 2) {
echo "Usage: $argv[0] domain".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'log_level' => JAXLLogger::DEBUG
));
$client->require_xep(array(
'0077' // InBand Registration
));
//
// Below are two states which become part of our client's xmpp_stream lifecycle
// consider as if these methods are directly inside xmpp_stream state machine.
//
// Note: $stanza = $args[0] is an instance of JAXLXml in xmpp_stream state methods,
// it is yet not ready for easy access patterns available on XMPPStanza instances.
//
$form = array();
function wait_for_register_response($event, $args)
{
global $client, $form;
if ($event == 'stanza_cb') {
$stanza = $args[0];
if ($stanza->name == 'iq') {
$form['type'] = $stanza->attrs['type'];
if ($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
} elseif ($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo sprintf(
"registration failed with error code: %s and type: %s".PHP_EOL,
$error->attrs['code'],
$error->attrs['type']
);
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
}
}
} else {
JAXLLogger::notice("unhandled event $event rcvd");
}
}
function wait_for_register_form($event, $args)
{
global $client, $form;
$stanza = $args[0];
$query = $stanza->exists('query', XEP0077::NS_INBAND_REGISTER);
if ($query) {
$instructions = $query->exists('instructions');
if ($instructions) {
echo $instructions->text.PHP_EOL;
}
- foreach ($query->childrens as $k => $child) {
+ foreach ($query->children as $k => $child) {
if ($child->name != 'instructions') {
$form[$child->name] = readline($child->name.":");
}
}
$client->xeps['0077']->set_form($stanza->attrs['from'], $form);
return "wait_for_register_response";
} else {
$client->end_stream();
return "logged_out";
}
}
//
// add necessary event callbacks here
//
$client->add_cb('on_stream_features', function ($stanza) {
global $client, $argv;
$client->xeps['0077']->get_form($argv[1]);
return "wait_for_register_form";
});
$client->add_cb('on_disconnect', function () {
global $form;
JAXLLogger::info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
});
//
// finally start configured xmpp stream
//
$client->start();
//
// if registration was successful
// try to connect with newly registered account
//
if ($form['type'] == 'result') {
JAXLLogger::info("connecting newly registered user account");
$client = new JAXL(array(
'jid' => $form['username'].'@'.$argv[1],
'pass' => $form['password'],
'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
$client->set_status('Available');
});
$client->start();
}
echo "done".PHP_EOL;
diff --git a/src/JAXL/core/jaxl_xml.php b/src/JAXL/core/jaxl_xml.php
index 9b6940c..faba3da 100644
--- a/src/JAXL/core/jaxl_xml.php
+++ b/src/JAXL/core/jaxl_xml.php
@@ -1,310 +1,310 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/
* Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml
*
* @author abhinavsingh
*
*/
class JAXLXml extends JAXLXmlAccess
{
public $parent = null;
public $rover = null;
public $xml = null;
/**
* Accepts any of the following constructors:
*
* * JAXLXml($name, $ns, $attrs, $text)
* * JAXLXml($name, $ns, $attrs)
* * JAXLXml($name, $ns, $text)
* * JAXLXml($name, $attrs, $text)
* * JAXLXml($name, $attrs)
* * JAXLXml($name, $ns)
* * JAXLXml($name)
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
public function __construct($name)
{
$argv = func_get_args();
$argc = count($argv);
$this->name = $name;
switch ($argc) {
case 4:
$this->ns = $argv[1];
$this->attrs = $argv[2];
$this->text = $argv[3];
break;
case 3:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
$this->text = $argv[2];
} else {
$this->ns = $argv[1];
if (is_array($argv[2])) {
$this->attrs = $argv[2];
} else {
$this->text = $argv[2];
}
}
break;
case 2:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
} else {
$this->ns = $argv[1];
}
break;
default:
break;
}
$this->rover = &$this;
}
public function __destruct()
{
}
/**
* Set or update attrs of element.
*
* @param array $attrs
* @return JAXLXml
*/
public function attrs(array $attrs)
{
$this->rover->attrs = array_merge($this->rover->attrs, $attrs);
return $this;
}
/**
* Check that element matches by attrs.
*
* @param array $attrs
* @return bool
*/
public function match_attrs(array $attrs)
{
$matches = true;
foreach ($attrs as $k => $v) {
if ($this->attrs[$k] !== $v) {
$matches = false;
break;
}
}
return $matches;
}
/**
* Set or append XML.
*
* @param JAXLXmlAccess $xml
* @param bool $append
* @return JAXLXml
*/
public function x(JAXLXmlAccess $xml, $append = false)
{
if (!$append) {
$this->rover->xml = $xml;
} else {
if ($this->rover->xml === null) {
$this->rover->xml = '';
}
$this->rover->xml .= $xml;
}
return $this;
}
/**
* Set or append text.
*
* @param string $text
* @param bool $append
* @return JAXLXml
*/
public function t($text, $append = false)
{
if (!$append) {
$this->rover->text = $text;
} else {
if ($this->rover->text === null) {
$this->rover->text = '';
}
$this->rover->text .= $text;
}
return $this;
}
/**
* Create child.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
* @return JAXLXml
*/
public function c($name, $ns = null, array $attrs = array(), $text = null)
{
$node = new JAXLXml($name, $ns, $attrs, $text);
$node->parent = &$this->rover;
- $this->rover->childrens[] = &$node;
+ $this->rover->children[] = &$node;
$this->rover = &$node;
return $this;
}
/**
* Append child node.
*
* @param JAXLXml $node
* @return JAXLXml
*/
public function cnode($node)
{
$node->parent = &$this->rover;
- $this->rover->childrens[] = &$node;
+ $this->rover->children[] = &$node;
$this->rover = &$node;
return $this;
}
/**
* @return JAXLXml
*/
public function up()
{
if ($this->rover->parent) {
$this->rover = &$this->rover->parent;
}
return $this;
}
/**
* @return JAXLXml
*/
public function top()
{
$this->rover = &$this;
return $this;
}
/**
* @param string $name
* @param string $ns
* @param array $attrs
* @return JAXLXml|bool
*/
public function exists($name, $ns = null, array $attrs = array())
{
- foreach ($this->childrens as $child) {
+ foreach ($this->children as $child) {
if ($ns) {
if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) {
return $child;
}
} elseif ($child->name == $name && $child->match_attrs($attrs)) {
return $child;
}
}
return false;
}
/**
* Update child with name ``$name``.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
public function update($name, $ns = null, array $attrs = array(), $text = null)
{
- foreach ($this->childrens as $k => $child) {
+ foreach ($this->children as $k => $child) {
if ($child->name == $name) {
$child->ns = $ns;
$child->attrs($attrs);
$child->text = $text;
- $this->childrens[$k] = $child;
+ $this->children[$k] = $child;
break;
}
}
}
/**
* @param string $parent_ns
* @return string
*/
public function to_string($parent_ns = null)
{
$xml = '';
$xml .= '<'.$this->name;
if ($this->ns && $this->ns != $parent_ns) {
$xml .= ' xmlns="'.$this->ns.'"';
}
foreach ($this->attrs as $k => $v) {
if (!is_null($v) && $v !== false) {
$xml .= ' '.$k.'="'.htmlspecialchars($v).'"';
}
}
$xml .= '>';
- foreach ($this->childrens as $child) {
+ foreach ($this->children as $child) {
$xml .= $child->to_string($this->ns);
}
if ($this->xml !== null) {
$xml .= $this->xml;
}
if ($this->text !== null) {
$xml .= htmlspecialchars($this->text);
}
$xml .= '</'.$this->name.'>';
return $xml;
}
}
diff --git a/src/JAXL/core/jaxl_xml_access.php b/src/JAXL/core/jaxl_xml_access.php
index 2172211..5843de6 100644
--- a/src/JAXL/core/jaxl_xml_access.php
+++ b/src/JAXL/core/jaxl_xml_access.php
@@ -1,33 +1,33 @@
<?php
/**
* @method JAXLXml attrs(array $attrs) Set or update attrs of element.
* @method bool match_attrs(array $attrs) Check that element matches by attrs.
* @method JAXLXml x(JAXLXmlAccess $xml, $append = false) Set or append XML.
* @method JAXLXml t($text, $append = false) Set or append text.
* @method JAXLXml c($name, $ns = null, array $attrs = array(), $text = null) Create child.
* @method JAXLXml cnode($node) Append child node.
* @method JAXLXml up()
* @method JAXLXml top()
* @method JAXLXml|bool exists($name, $ns = null, array $attrs = array())
* @method void update($name, $ns = null, array $attrs = array(), $text = null) Update child with name ``$name``.
* @method string to_string($parent_ns = null)
*/
abstract class JAXLXmlAccess
{
/** @var string */
public $name = null;
/** @var string */
public $ns = null;
/** @var array */
public $attrs = array();
/** @var string */
public $text = null;
/** @var JAXLXml[] */
- public $childrens = array();
+ public $children = array();
}
diff --git a/src/JAXL/jaxl.php b/src/JAXL/jaxl.php
index 9173250..80900fe 100644
--- a/src/JAXL/jaxl.php
+++ b/src/JAXL/jaxl.php
@@ -156,702 +156,702 @@ class JAXL extends XMPPStream
// env
if ($this->cfg['strict']) {
JAXLLogger::info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => false inside JAXL config to disable this");
JAXLException::addHandlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = ($this->cfg['jid'] !== null) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = $this->cfg['priv_dir'];
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
JAXLLogger::info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
if (($this->cfg['host'] === null || $this->cfg['port'] === null) && $jid) {
// this dns lookup is blocking
JAXLLogger::info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
if ($this->cfg['host'] === null) {
$this->cfg['host'] = $host;
}
if ($this->cfg['port'] === null) {
$this->cfg['port'] = $port;
}
}
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
JAXLLogger::debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
$transport = new JAXLSocketClient($this->cfg['stream_context']);
}
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
$this->cfg['pass'],
$this->cfg['resource'] !== null ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
$this->cfg['force_tls']
);
}
public function __destruct()
{
// delete pid file
JAXLLogger::info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLClientBase
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$classname = 'XEP'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if ($this->cfg['protocol'] !== null) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
JAXLLogger::info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// If connection to the destination fails.
if ($this->trans->errno == 61 ||
$this->trans->errno == 110 ||
$this->trans->errno == 111
) {
JAXLLogger::debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
JAXLLogger::debug("got sighup");
break;
// interrupt program
case SIGINT:
JAXLLogger::debug("got sigint");
break;
// software termination signal
case SIGTERM:
JAXLLogger::debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
JAXLLogger::debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
JAXLLogger::debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
JAXLLogger::debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
JAXLLogger::debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
JAXLLogger::debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
- foreach ($mechanisms->childrens as $mechanism) {
+ foreach ($mechanisms->children as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
$pref_auth = $this->cfg['auth_type'];
// check if preferred auth type exists in available mechanisms
if (isset($mechs[$pref_auth]) && $mechs[$pref_auth]) {
JAXLLogger::debug("pref_auth ".$pref_auth." exists");
} else {
JAXLLogger::debug("pref_auth ".$pref_auth." doesn't exists");
JAXLLogger::error("preferred auth type not supported, trying $pref_auth");
}
$this->send_auth_pkt(
$pref_auth,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//JAXLLogger::debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
- foreach ($query->childrens as $child) {
+ foreach ($query->children as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
- foreach ($child->childrens as $group) {
+ foreach ($child->children as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
JAXLLogger::warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_INFO);
- foreach ($query->childrens as $k => $child) {
+ foreach ($query->children as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_ITEMS);
- foreach ($query->childrens as $k => $child) {
+ foreach ($query->children as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
}
diff --git a/src/JAXL/xep/xep_0114.php b/src/JAXL/xep/xep_0114.php
index 219dc06..69cfbe6 100644
--- a/src/JAXL/xep/xep_0114.php
+++ b/src/JAXL/xep/xep_0114.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class XEP0114 extends XMPPXep
{
const NS_JABBER_COMPONENT_ACCEPT = 'jabber:component:accept';
//
// abstract method
//
public function init()
{
return array(
'on_connect' => 'start_stream',
'on_stream_start' => 'start_handshake',
'on_handshake_stanza' => 'logged_in',
'on_error_stanza' => 'logged_out'
);
}
//
// event callbacks
//
public function start_stream()
{
$xml = sprintf(
'<stream:stream xmlns:stream="%s" to="%s" xmlns="%s">',
XMPP::NS_XMPP,
$this->jaxl->jid->to_string(),
self::NS_JABBER_COMPONENT_ACCEPT
);
$this->jaxl->send_raw($xml);
}
public function start_handshake($stanza)
{
JAXLLogger::debug("starting component handshake");
$id = $stanza->id;
$hash = strtolower(sha1($id.$this->jaxl->pass));
$stanza = new JAXLXml('handshake', null, $hash);
$this->jaxl->send($stanza);
}
public function logged_in($stanza)
{
JAXLLogger::debug("component handshake complete");
$this->jaxl->handle_auth_success();
return array("logged_in", 1);
}
public function logged_out($stanza)
{
if ($stanza->name == "error" && $stanza->ns == XMPP::NS_XMPP) {
- $reason = $stanza->childrens[0]->name;
+ $reason = $stanza->children[0]->name;
$this->jaxl->handle_auth_failure($reason);
$this->jaxl->send_end_stream();
return array("logged_out", 0);
} else {
JAXLLogger::debug("uncatched stanza received in logged_out");
}
}
}
diff --git a/src/JAXL/xmpp/xmpp_stanza.php b/src/JAXL/xmpp/xmpp_stanza.php
index 103398c..bede159 100644
--- a/src/JAXL/xmpp/xmpp_stanza.php
+++ b/src/JAXL/xmpp/xmpp_stanza.php
@@ -1,231 +1,231 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Generic xmpp stanza object which provide convinient access pattern over xml objects
* Also to be able to convert an existing xml object into stanza object (to get access patterns going)
* this class doesn't extend xml, but infact works on a reference of xml object
* If not provided during constructor, new xml object is created and saved as reference
*
* @author abhinavsingh
*
* Access to common xml attributes:
*
* @property string $to
* @property string $from
* @property string $id
* @property string $type
*
* Access to parts of common xml attributes:
*
* @property string $to_node
* @property string $to_domain
* @property string $to_resource
* @property string $from_node
* @property string $from_domain
* @property string $from_resource
*
* Access to first child element text:
*
* @property string $status
* @property string $show
* @property string $priority
* @property string $body
* @property string $thread
* @property string $subject
*/
class XMPPStanza extends JAXLXmlAccess
{
/**
* @var JAXLXml
*/
private $xml;
/**
* @param JAXLXml|string $name
* @param array $attrs
* @param string $ns
*/
public function __construct($name, array $attrs = array(), $ns = XMPP::NS_JABBER_CLIENT)
{
// TRICKY: Remove JAXLXmlAccess properties, so magic method __get will
// be called for them. This needed to use JAXLXmlAccess as a type hint.
$this->name = null;
unset($this->name);
$this->ns = null;
unset($this->ns);
$this->attrs = null;
unset($this->attrs);
$this->text = null;
unset($this->text);
- $this->childrens = null;
- unset($this->childrens);
+ $this->children = null;
+ unset($this->children);
if ($name instanceof JAXLXml) {
$this->xml = $name;
} else {
$this->xml = new JAXLXml($name, $ns, $attrs);
}
}
public function __call($method, $args)
{
return call_user_func_array(array($this->xml, $method), $args);
}
public function __get($prop)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
- case 'childrens':
+ case 'children':
return $this->xml->$prop;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
return isset($this->xml->attrs[$prop]) ? $this->xml->attrs[$prop] : null;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val) {
return null;
}
$val = new XMPPJid($val);
return $val->$key;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val = $this->xml->exists($prop);
if (!$val) {
return null;
}
return $val->text;
break;
default:
return null;
break;
}
}
public function __set($prop, $val)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
- case 'childrens':
+ case 'children':
return $this->xml->$prop = $val;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
$this->xml->attrs[$prop] = $val;
return true;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val1 = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val1) {
$val1 = '';
}
$val1 = new XMPPJid($val1);
$val1->$key = $val;
$this->xml->attrs[$attr] = $val1->to_string();
return true;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val1 = $this->xml->exists($prop);
if (!$val1) {
$this->xml->c($prop)->t($val)->up();
} else {
$this->xml->update($prop, $val1->ns, $val1->attrs, $val);
}
return true;
break;
default:
return null;
break;
}
}
}
diff --git a/src/JAXL/xmpp/xmpp_stream.php b/src/JAXL/xmpp/xmpp_stream.php
index 8c873ef..5d32289 100644
--- a/src/JAXL/xmpp/xmpp_stream.php
+++ b/src/JAXL/xmpp/xmpp_stream.php
@@ -123,642 +123,642 @@ abstract class XMPPStream extends JAXLFsm
}
public function handle_invalid_state($r)
{
JAXLLogger::error(sprintf(
"got invalid return value from state handler '%s', sending end stream...",
$this->state
));
$this->send_end_stream();
$this->state = "logged_out";
JAXLLogger::notice(sprintf(
"state handler '%s' returned %s, kindly report this to developers",
$this->state,
serialize($r)
));
}
/**
* @param JAXLXmlAccess $stanza
*/
public function send(JAXLXmlAccess $stanza)
{
$this->trans->send($stanza->to_string());
}
/**
* @param string $data
*/
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.XMPP::NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.XMPP::NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.XMPP::NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', XMPP::NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', XMPP::NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', XMPP::NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', XMPP::NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
JAXLLogger::debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', XMPP::NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', XMPP::NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
JAXLLogger::debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//JAXLLogger::debug("stream started");
return "wait_for_stream_features";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', XMPP::NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', XMPP::NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', XMPP::NS_BIND) ? true : false;
$sess = $stanza->exists('session', XMPP::NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', XMPP::NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
JAXLLogger::debug("no catch");
}
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == XMPP::NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'compressed' && $stanza->ns == XMPP::NS_COMPRESSION_PROTOCOL) {
$this->xml->reset_parser();
$this->trans->compress();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
}
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_compression_result", 0);
break;
}
}
public function wait_for_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'failure' && $stanza->ns == XMPP::NS_SASL) {
- $reason = $stanza->childrens[0]->name;
+ $reason = $stanza->children[0]->name;
//JAXLLogger::debug("sasl failed with reason ".$reason."");
$this->handle_auth_failure($reason);
return "logged_out";
} elseif ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$this->send_challenge_response($challenge);
return "wait_for_sasl_response";
} elseif ($stanza->name == 'success' && $stanza->ns == XMPP::NS_SASL) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
JAXLLogger::debug("got unhandled sasl response");
}
return "wait_for_sasl_response";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_sasl_response", 0);
break;
}
}
public function wait_for_bind_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// TODO: chk on id
if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result'
&& ($jid = $stanza->exists('bind', XMPP::NS_BIND)->exists('jid'))) {
$this->full_jid = new XMPPJid($jid->text);
$this->send_session_pkt();
return "wait_for_session_response";
} else {
// FIXME:
}
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_bind_response", 0);
break;
}
}
public function wait_for_session_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$this->handle_auth_success();
return "logged_in";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_session_response", 0);
break;
}
}
public function logged_in($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// call abstract
if ($stanza->name == 'message') {
$this->handle_message($stanza);
} elseif ($stanza->name == 'presence') {
$this->handle_presence($stanza);
} elseif ($stanza->name == 'iq') {
$this->handle_iq($stanza);
} else {
$this->handle_other($event, $args);
}
return "logged_in";
break;
case "end_cb":
$this->send_end_stream();
return "logged_out";
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_in", 0);
break;
}
}
public function logged_out($event, $args)
{
switch ($event) {
case "end_cb":
$this->trans->disconnect();
return "disconnected";
break;
case "end_stream":
return "disconnected";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
case "connect":
return $this->do_connect($args);
break;
default:
// exit for any other event in logged_out state
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_out", 0);
break;
}
}
}
diff --git a/tests/JAXLXmlStreamTest.php b/tests/JAXLXmlStreamTest.php
index 0a1a92b..866e301 100644
--- a/tests/JAXLXmlStreamTest.php
+++ b/tests/JAXLXmlStreamTest.php
@@ -1,75 +1,75 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* @author abhinavsingh
*
*/
class JAXLXmlStreamTest extends PHPUnit_Framework_TestCase
{
public function xml_start_cb($node)
{
$this->assertEquals('stream', $node->name);
$this->assertEquals(XMPP::NS_XMPP, $node->ns);
}
public function xml_end_cb($node)
{
$this->assertEquals('stream', $node->name);
}
public function xml_stanza_cb($node)
{
$this->assertEquals('features', $node->name);
- $this->assertEquals(1, count($node->childrens));
+ $this->assertEquals(1, count($node->children));
}
public function test_xml_stream_callbacks()
{
$xml = new JAXLXmlStream();
$xml->set_callback(array(&$this, "xml_start_cb"), array(&$this, "xml_end_cb"), array(&$this, "xml_stanza_cb"));
$xml->parse('<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">');
$xml->parse('<features>');
$xml->parse('<mechanisms>');
$xml->parse('</mechanisms>');
$xml->parse('</features>');
$xml->parse('</stream:stream>');
}
}
diff --git a/tests/XMPPStanzaTest.php b/tests/XMPPStanzaTest.php
index 757ff70..e66e249 100644
--- a/tests/XMPPStanzaTest.php
+++ b/tests/XMPPStanzaTest.php
@@ -1,105 +1,105 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* @author abhinavsingh
*
*/
class XMPPStanzaTest extends PHPUnit_Framework_TestCase
{
public function test_xmpp_stanza_nested()
{
$xml = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]'));
$xml->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up()
->c('thread')->t('1234')->up()
->c('nested')
->c('nest')->t('nest1')->up()
->c('nest')->t('nest2')->up()
->c('nest')->t('nest3')->up()->up()
->c('c')->attrs(array('hash' => '84jsdmnskd'));
$stanza = new XMPPStanza($xml);
$this->assertEquals(
'<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested>' .
'<nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>',
$stanza->to_string()
);
}
public function test_xmpp_stanza_from_jaxl_xml()
{
// xml to stanza test
$xml = new JAXLXml('message', XMPP::NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q'));
$stanza = new XMPPStanza($xml);
$stanza->c('body')->t('hello world');
$this->assertEquals('XMPPStanza', get_class($stanza));
$this->assertEquals('JAXLXml', get_class($stanza->exists('body')));
$this->assertEquals('[email protected]', $stanza->to);
$this->assertEquals(
'<message xmlns="jabber:client" to="[email protected]" from="[email protected]/q">' .
'<body>hello world</body></message>',
$stanza->to_string()
);
}
public function testXMPPStanzaAndJAXLXmlAreInterchangeable()
{
$test_data = array(
'name' => 'msg',
'ns' => 'NAMESPACE',
'attrs' => array('a' => '1', 'b' => '2'),
'text' => 'Test message'
);
$xml = new JAXLXml($test_data['name'], $test_data['ns'], $test_data['attrs'], $test_data['text']);
$stanza = new XMPPStanza($xml);
$this->checkJAXLXmlAccess($xml, $test_data);
$this->checkJAXLXmlAccess($stanza, $test_data);
}
protected function checkJAXLXmlAccess(JAXLXmlAccess $xml_or_stanza, $test_data)
{
$this->assertEquals($test_data['name'], $xml_or_stanza->name);
$this->assertEquals($test_data['ns'], $xml_or_stanza->ns);
$this->assertEquals($test_data['attrs'], $xml_or_stanza->attrs);
$this->assertEquals($test_data['text'], $xml_or_stanza->text);
- $this->assertEquals(array(), $xml_or_stanza->childrens);
+ $this->assertEquals(array(), $xml_or_stanza->children);
return true;
}
}
|
jaxl/JAXL | 523ef802030a423a76ab4fe0f4e208885c1f478b | Add common Client interface | diff --git a/examples/register_user.php b/examples/register_user.php
index d82e8ed..fee6de1 100644
--- a/examples/register_user.php
+++ b/examples/register_user.php
@@ -1,168 +1,164 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 2) {
echo "Usage: $argv[0] domain".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'log_level' => JAXLLogger::DEBUG
));
$client->require_xep(array(
'0077' // InBand Registration
));
//
-// below are two states which become part of
-// our client's xmpp_stream lifecycle
-// consider as if these methods are directly
-// inside xmpp_stream state machine
+// Below are two states which become part of our client's xmpp_stream lifecycle
+// consider as if these methods are directly inside xmpp_stream state machine.
//
-// Note: $stanza = $args[0] is an instance of
-// JAXLXml in xmpp_stream state methods,
-// it is yet not ready for easy access
-// patterns available on XMPPStanza instances
+// Note: $stanza = $args[0] is an instance of JAXLXml in xmpp_stream state methods,
+// it is yet not ready for easy access patterns available on XMPPStanza instances.
//
$form = array();
function wait_for_register_response($event, $args)
{
global $client, $form;
if ($event == 'stanza_cb') {
$stanza = $args[0];
if ($stanza->name == 'iq') {
$form['type'] = $stanza->attrs['type'];
if ($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
} elseif ($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo sprintf(
"registration failed with error code: %s and type: %s".PHP_EOL,
$error->attrs['code'],
$error->attrs['type']
);
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
}
}
} else {
JAXLLogger::notice("unhandled event $event rcvd");
}
}
function wait_for_register_form($event, $args)
{
global $client, $form;
$stanza = $args[0];
$query = $stanza->exists('query', XEP0077::NS_INBAND_REGISTER);
if ($query) {
$instructions = $query->exists('instructions');
if ($instructions) {
echo $instructions->text.PHP_EOL;
}
foreach ($query->childrens as $k => $child) {
if ($child->name != 'instructions') {
$form[$child->name] = readline($child->name.":");
}
}
$client->xeps['0077']->set_form($stanza->attrs['from'], $form);
return "wait_for_register_response";
} else {
$client->end_stream();
return "logged_out";
}
}
//
// add necessary event callbacks here
//
$client->add_cb('on_stream_features', function ($stanza) {
global $client, $argv;
$client->xeps['0077']->get_form($argv[1]);
return "wait_for_register_form";
});
$client->add_cb('on_disconnect', function () {
global $form;
JAXLLogger::info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
});
//
// finally start configured xmpp stream
//
$client->start();
//
// if registration was successful
// try to connect with newly registered account
//
if ($form['type'] == 'result') {
JAXLLogger::info("connecting newly registered user account");
$client = new JAXL(array(
'jid' => $form['username'].'@'.$argv[1],
'pass' => $form['password'],
'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
$client->set_status('Available');
});
$client->start();
}
echo "done".PHP_EOL;
diff --git a/src/JAXL/core/jaxl_client_base.php b/src/JAXL/core/jaxl_client_base.php
new file mode 100644
index 0000000..6d4925d
--- /dev/null
+++ b/src/JAXL/core/jaxl_client_base.php
@@ -0,0 +1,18 @@
+<?php
+
+/**
+ * Common interface for JAXLSocketClient and XEP0206.
+ */
+interface JAXLClientBase
+{
+
+ /**
+ * @param mixed $data
+ */
+ public function send($data);
+
+ /**
+ * @param callable $recv_cb
+ */
+ public function set_callback($recv_cb);
+}
diff --git a/src/JAXL/core/jaxl_socket_client.php b/src/JAXL/core/jaxl_socket_client.php
index d77b390..f399f17 100644
--- a/src/JAXL/core/jaxl_socket_client.php
+++ b/src/JAXL/core/jaxl_socket_client.php
@@ -1,263 +1,263 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
-class JAXLSocketClient
+class JAXLSocketClient implements JAXLClientBase
{
private $host = null;
private $port = null;
private $transport = null;
/** @var resource */
private $stream_context = null;
private $blocking = false;
public $fd = null;
public $errno = null;
public $errstr = null;
private $timeout = 10;
private $ibuffer = "";
private $obuffer = "";
private $compressed = false;
private $recv_bytes = 0;
private $send_bytes = 0;
/** @var callable */
private $recv_cb = null;
private $recv_chunk_size = 1024;
private $writing = false;
/**
* @param resource $stream_context Resource created with stream_context_create().
*/
public function __construct($stream_context = null)
{
$this->stream_context = $stream_context;
}
public function __destruct()
{
//JAXLLogger::debug("cleaning up xmpp socket...");
$this->disconnect();
}
/**
- * Emit on on_read_ready.
+ * Emits on on_read_ready.
*
* @param callable $recv_cb
*/
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
/**
* @param string | resource $socket_path
*/
public function connect($socket_path)
{
if (gettype($socket_path) == "string") {
$path_parts = explode(":", $socket_path);
$this->transport = $path_parts[0];
$this->host = substr($path_parts[1], 2, strlen($path_parts[1]));
if (count($path_parts) == 3) {
$this->port = $path_parts[2];
}
JAXLLogger::info("trying ".$socket_path);
if ($this->stream_context) {
$this->fd = @stream_socket_client(
$socket_path,
$this->errno,
$this->errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
$this->stream_context
);
} else {
$this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout);
}
} elseif (is_resource($socket_path)) {
$this->fd = &$socket_path;
} else {
// Some error occurred.
}
if ($this->fd) {
JAXLLogger::debug("connected to ".$socket_path."");
stream_set_blocking($this->fd, $this->blocking);
// watch descriptor for read/write events
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_read_ready')
));
return true;
} else {
JAXLLogger::error(sprintf(
"unable to connect %s with error no: %s, error str: %s",
is_null($socket_path) ? 'NULL' : $socket_path,
is_null($this->errno) ? 'NULL' : $this->errno,
is_null($this->errstr) ? 'NULL' : $this->errstr
));
$this->disconnect();
return false;
}
}
public function disconnect()
{
JAXLLoop::unwatch($this->fd, array(
'read' => true,
'write' => true
));
if (is_resource($this->fd)) {
fclose($this->fd);
}
$this->fd = null;
}
public function compress()
{
$this->compressed = true;
//stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ);
//stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE);
}
public function crypt()
{
// set blocking (since tls negotiation fails if stream is non-blocking)
stream_set_blocking($this->fd, true);
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
}
}
}
// switch back to non-blocking
stream_set_blocking($this->fd, false);
return $ret;
}
/**
* @param string $data
*/
public function send($data)
{
$this->obuffer .= $data;
// add watch for write events
if ($this->writing) {
return;
}
JAXLLoop::watch($this->fd, array(
'write' => array(&$this, 'on_write_ready')
));
$this->writing = true;
}
public function on_read_ready($fd)
{
//JAXLLogger::debug("on read ready called");
$raw = @fread($fd, $this->recv_chunk_size);
$bytes = strlen($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($fd);
if ($meta['eof'] === true) {
JAXLLogger::warning("socket eof, disconnecting");
JAXLLoop::unwatch($fd, array(
'read' => true
));
$this->disconnect();
return;
}
}
$this->recv_bytes += $bytes;
$total = $this->ibuffer.$raw;
$this->ibuffer = "";
JAXLLogger::debug("read ".$bytes."/".$this->recv_bytes." of data");
if ($bytes > 0) {
JAXLLogger::debug($raw);
}
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $raw);
}
}
public function on_write_ready($fd)
{
//JAXLLogger::debug("on write ready called");
$total = strlen($this->obuffer);
$bytes = @fwrite($fd, $this->obuffer);
$this->send_bytes += $bytes;
JAXLLogger::debug("sent ".$bytes."/".$this->send_bytes." of data");
JAXLLogger::debug(substr($this->obuffer, 0, $bytes));
$this->obuffer = substr($this->obuffer, $bytes, $total-$bytes);
// unwatch for write if obuffer is empty
if (strlen($this->obuffer) === 0) {
JAXLLoop::unwatch($fd, array(
'write' => true
));
$this->writing = false;
}
//JAXLLogger::debug("current obuffer size: ".strlen($this->obuffer)."");
}
}
diff --git a/src/JAXL/jaxl.php b/src/JAXL/jaxl.php
index bc1a761..299ac90 100644
--- a/src/JAXL/jaxl.php
+++ b/src/JAXL/jaxl.php
@@ -1,779 +1,779 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$cfg_defaults = array(
'auth_type' => 'PLAIN',
'bosh_hold' => null,
'bosh_rid' => null,
'bosh_url' => null,
'bosh_wait' => null,
'domain' => null,
'force_tls' => false,
'host' => null,
'jid' => null,
'log_colorize' => $this->log_colorize,
'log_level' => $this->log_level,
'log_path' => JAXLLogger::$path,
'multi_client' => false,
'pass' => false,
'port' => null,
'priv_dir' => getcwd().'/.jaxl',
'protocol' => null,
'resource' => null,
'stream_context' => null,
'strict' => true
);
$this->cfg = array_merge($cfg_defaults, $config);
// setup logger
JAXLLogger::$path = $this->cfg['log_path'];
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
// env
if ($this->cfg['strict']) {
JAXLLogger::info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => false inside JAXL config to disable this");
JAXLException::addHandlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = ($this->cfg['jid'] !== null) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = $this->cfg['priv_dir'];
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
JAXLLogger::info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
if (($this->cfg['host'] === null || $this->cfg['port'] === null) && $jid) {
// this dns lookup is blocking
JAXLLogger::info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
if ($this->cfg['host'] === null) {
$this->cfg['host'] = $host;
}
if ($this->cfg['port'] === null) {
$this->cfg['port'] = $port;
}
}
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
JAXLLogger::debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
$transport = new JAXLSocketClient($this->cfg['stream_context']);
}
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
$this->cfg['pass'],
$this->cfg['resource'] !== null ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
$this->cfg['force_tls']
);
}
public function __destruct()
{
// delete pid file
JAXLLogger::info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
- * @return JAXLSocketClient|XEP0206
+ * @return JAXLClientBase
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$classname = 'XEP'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if ($this->cfg['protocol'] !== null) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
JAXLLogger::info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// If connection to the destination fails.
if ($this->trans->errno == 61 ||
$this->trans->errno == 110 ||
$this->trans->errno == 111
) {
JAXLLogger::debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
JAXLLogger::debug("got sighup");
break;
// interrupt program
case SIGINT:
JAXLLogger::debug("got sigint");
break;
// software termination signal
case SIGTERM:
JAXLLogger::debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
JAXLLogger::debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
JAXLLogger::debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
JAXLLogger::debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
JAXLLogger::debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
JAXLLogger::debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
$pref_auth = $this->cfg['auth_type'];
// check if preferred auth type exists in available mechanisms
if (isset($mechs[$pref_auth]) && $mechs[$pref_auth]) {
JAXLLogger::debug("pref_auth ".$pref_auth." exists");
} else {
JAXLLogger::debug("pref_auth ".$pref_auth." doesn't exists");
JAXLLogger::error("preferred auth type not supported, trying $pref_auth");
}
$this->send_auth_pkt(
$pref_auth,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//JAXLLogger::debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
diff --git a/src/JAXL/xep/xep_0206.php b/src/JAXL/xep/xep_0206.php
index 5fbfe61..e57e921 100644
--- a/src/JAXL/xep/xep_0206.php
+++ b/src/JAXL/xep/xep_0206.php
@@ -1,268 +1,273 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP0206 extends XMPPXep
+class XEP0206 extends XMPPXep implements JAXLClientBase
{
const NS_HTTP_BIND = 'http://jabber.org/protocol/httpbind';
const NS_BOSH = 'urn:xmpp:xbosh';
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
//
// event callbacks
//
-
+
/**
- * @param JAXLXmlAccess|string $body
+ * @param JAXLXmlAccess|string $data
*/
- public function send($body)
+ public function send($data)
{
- if ($body instanceof JAXLXmlAccess) {
- $body = $body->to_string();
+ if ($data instanceof JAXLXmlAccess) {
+ $data = $data->to_string();
} else {
- if (substr($body, 0, 15) == '<stream:stream ') {
+ if (substr($data, 0, 15) == '<stream:stream ') {
$this->restarted = true;
- $body = new JAXLXml('body', self::NS_HTTP_BIND, array(
+ $data = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
'xmlns:xmpp' => self::NS_BOSH
));
- $body = $body->to_string();
- } elseif (substr($body, 0, 16) == '</stream:stream>') {
- $body = new JAXLXml('body', self::NS_HTTP_BIND, array(
+ $data = $data->to_string();
+ } elseif (substr($data, 0, 16) == '</stream:stream>') {
+ $data = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
- $body = $body->to_string();
+ $data = $data->to_string();
} else {
- $body = $this->wrap($body);
+ $data = $this->wrap($data);
}
}
- JAXLLogger::debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
+ JAXLLogger::debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$data);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
- curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
+ curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $data);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
JAXLLogger::debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
JAXLLogger::debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
JAXLLogger::debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
JAXLLogger::error("no ch found");
exit;
}
}
-
+
+ /**
+ * Emits on recv and session_start.
+ *
+ * @param callable $recv_cb
+ */
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.
self::NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
$this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
$this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
$this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
'xmlns:xmpp' => self::NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
if ($this->jaxl->cfg['jid'] !== null) {
$attrs['from'] = $this->jaxl->cfg['jid'];
}
$body = new JAXLXml('body', self::NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
$body = new JAXLXml('body', self::NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
JAXLLogger::debug("disconnecting");
}
}
diff --git a/src/JAXL/xmpp/xmpp_stream.php b/src/JAXL/xmpp/xmpp_stream.php
index 4d193be..8c873ef 100644
--- a/src/JAXL/xmpp/xmpp_stream.php
+++ b/src/JAXL/xmpp/xmpp_stream.php
@@ -1,605 +1,605 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
- * @var JAXLSocketClient|XEP0206
+ * @var JAXLClientBase
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
- * @param JAXLSocketClient|XEP0206 $transport
+ * @param JAXLClientBase $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
$jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//JAXLLogger::debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
JAXLLogger::error(sprintf(
"got invalid return value from state handler '%s', sending end stream...",
$this->state
));
$this->send_end_stream();
$this->state = "logged_out";
JAXLLogger::notice(sprintf(
"state handler '%s' returned %s, kindly report this to developers",
$this->state,
serialize($r)
));
}
/**
* @param JAXLXmlAccess $stanza
*/
public function send(JAXLXmlAccess $stanza)
{
$this->trans->send($stanza->to_string());
}
/**
* @param string $data
*/
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.XMPP::NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.XMPP::NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.XMPP::NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', XMPP::NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', XMPP::NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', XMPP::NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', XMPP::NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
JAXLLogger::debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', XMPP::NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', XMPP::NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
JAXLLogger::debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//JAXLLogger::debug("stream started");
return "wait_for_stream_features";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', XMPP::NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', XMPP::NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', XMPP::NS_BIND) ? true : false;
$sess = $stanza->exists('session', XMPP::NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', XMPP::NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
JAXLLogger::debug("no catch");
}
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == XMPP::NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
|
jaxl/JAXL | 5561292f491988166699dd9b0ff9c578c7aab047 | Add abstract JAXLXmlAccess to easily get type hints | diff --git a/src/JAXL/core/jaxl_xml.php b/src/JAXL/core/jaxl_xml.php
index 3f34785..f96bd76 100644
--- a/src/JAXL/core/jaxl_xml.php
+++ b/src/JAXL/core/jaxl_xml.php
@@ -1,307 +1,300 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/
* Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml
*
* @author abhinavsingh
*
*/
-class JAXLXml
+class JAXLXml extends JAXLXmlAccess
{
- public $name;
- public $ns = null;
- public $attrs = array();
- public $xml = null;
- public $text = null;
-
- /** @var JAXLXml[] */
- public $childrens = array();
public $parent = null;
public $rover = null;
+ public $xml = null;
/**
* Accepts any of the following constructors:
*
* * JAXLXml($name, $ns, $attrs, $text)
* * JAXLXml($name, $ns, $attrs)
* * JAXLXml($name, $ns, $text)
* * JAXLXml($name, $attrs, $text)
* * JAXLXml($name, $attrs)
* * JAXLXml($name, $ns)
* * JAXLXml($name)
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
public function __construct($name)
{
$argv = func_get_args();
$argc = count($argv);
$this->name = $name;
switch ($argc) {
case 4:
$this->ns = $argv[1];
$this->attrs = $argv[2];
$this->text = $argv[3];
break;
case 3:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
$this->text = $argv[2];
} else {
$this->ns = $argv[1];
if (is_array($argv[2])) {
$this->attrs = $argv[2];
} else {
$this->text = $argv[2];
}
}
break;
case 2:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
} else {
$this->ns = $argv[1];
}
break;
default:
break;
}
$this->rover = &$this;
}
public function __destruct()
{
}
/**
* @param array $attrs
* @return JAXLXml
*/
public function attrs(array $attrs)
{
$this->rover->attrs = array_merge($this->rover->attrs, $attrs);
return $this;
}
/**
* @param array $attrs
* @return bool
*/
public function match_attrs(array $attrs)
{
$matches = true;
foreach ($attrs as $k => $v) {
if ($this->attrs[$k] !== $v) {
$matches = false;
break;
}
}
return $matches;
}
/**
* Set or append XML.
*
- * @param unknown $xml
+ * @param JAXLXmlAccess $xml
* @param bool $append
* @return JAXLXml
*/
- public function x($xml, $append = false)
+ public function x(JAXLXmlAccess $xml, $append = false)
{
if (!$append) {
$this->rover->xml = $xml;
} else {
if ($this->rover->xml === null) {
$this->rover->xml = '';
}
$this->rover->xml .= $xml;
}
return $this;
}
/**
* Set or append text.
*
* @param string $text
* @param bool $append
* @return JAXLXml
*/
public function t($text, $append = false)
{
if (!$append) {
$this->rover->text = $text;
} else {
if ($this->rover->text === null) {
$this->rover->text = '';
}
$this->rover->text .= $text;
}
return $this;
}
/**
* Create child.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
* @return JAXLXml
*/
public function c($name, $ns = null, array $attrs = array(), $text = null)
{
$node = new JAXLXml($name, $ns, $attrs, $text);
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
/**
* Append child node.
*
* @param JAXLXml $node
* @return JAXLXml
*/
public function cnode($node)
{
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
public function up()
{
if ($this->rover->parent) {
$this->rover = &$this->rover->parent;
}
return $this;
}
public function top()
{
$this->rover = &$this;
return $this;
}
/**
* @param string $name
* @param string $ns
* @param array $attrs
* @return JAXLXml|bool
*/
public function exists($name, $ns = null, array $attrs = array())
{
foreach ($this->childrens as $child) {
if ($ns) {
if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) {
return $child;
}
} elseif ($child->name == $name && $child->match_attrs($attrs)) {
return $child;
}
}
return false;
}
/**
* Update child with name ``$name``.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
public function update($name, $ns = null, array $attrs = array(), $text = null)
{
foreach ($this->childrens as $k => $child) {
if ($child->name == $name) {
$child->ns = $ns;
$child->attrs($attrs);
$child->text = $text;
$this->childrens[$k] = $child;
break;
}
}
}
/**
* @param string $parent_ns
* @return string
*/
public function to_string($parent_ns = null)
{
$xml = '';
$xml .= '<'.$this->name;
if ($this->ns && $this->ns != $parent_ns) {
$xml .= ' xmlns="'.$this->ns.'"';
}
foreach ($this->attrs as $k => $v) {
if (!is_null($v) && $v !== false) {
$xml .= ' '.$k.'="'.htmlspecialchars($v).'"';
}
}
$xml .= '>';
foreach ($this->childrens as $child) {
$xml .= $child->to_string($this->ns);
}
if ($this->xml !== null) {
$xml .= $this->xml;
}
if ($this->text !== null) {
$xml .= htmlspecialchars($this->text);
}
$xml .= '</'.$this->name.'>';
return $xml;
}
}
diff --git a/src/JAXL/core/jaxl_xml_access.php b/src/JAXL/core/jaxl_xml_access.php
new file mode 100644
index 0000000..2172211
--- /dev/null
+++ b/src/JAXL/core/jaxl_xml_access.php
@@ -0,0 +1,33 @@
+<?php
+
+/**
+ * @method JAXLXml attrs(array $attrs) Set or update attrs of element.
+ * @method bool match_attrs(array $attrs) Check that element matches by attrs.
+ * @method JAXLXml x(JAXLXmlAccess $xml, $append = false) Set or append XML.
+ * @method JAXLXml t($text, $append = false) Set or append text.
+ * @method JAXLXml c($name, $ns = null, array $attrs = array(), $text = null) Create child.
+ * @method JAXLXml cnode($node) Append child node.
+ * @method JAXLXml up()
+ * @method JAXLXml top()
+ * @method JAXLXml|bool exists($name, $ns = null, array $attrs = array())
+ * @method void update($name, $ns = null, array $attrs = array(), $text = null) Update child with name ``$name``.
+ * @method string to_string($parent_ns = null)
+ */
+abstract class JAXLXmlAccess
+{
+
+ /** @var string */
+ public $name = null;
+
+ /** @var string */
+ public $ns = null;
+
+ /** @var array */
+ public $attrs = array();
+
+ /** @var string */
+ public $text = null;
+
+ /** @var JAXLXml[] */
+ public $childrens = array();
+}
diff --git a/src/JAXL/xep/xep_0206.php b/src/JAXL/xep/xep_0206.php
index 6a8eb4d..5fbfe61 100644
--- a/src/JAXL/xep/xep_0206.php
+++ b/src/JAXL/xep/xep_0206.php
@@ -1,268 +1,268 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class XEP0206 extends XMPPXep
{
const NS_HTTP_BIND = 'http://jabber.org/protocol/httpbind';
const NS_BOSH = 'urn:xmpp:xbosh';
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
//
// event callbacks
//
/**
- * @param JAXLXml|XMPPStanza|string $body
+ * @param JAXLXmlAccess|string $body
*/
public function send($body)
{
- if (is_object($body)) {
+ if ($body instanceof JAXLXmlAccess) {
$body = $body->to_string();
} else {
if (substr($body, 0, 15) == '<stream:stream ') {
$this->restarted = true;
-
+
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
'xmlns:xmpp' => self::NS_BOSH
));
-
+
$body = $body->to_string();
} elseif (substr($body, 0, 16) == '</stream:stream>') {
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
-
+
$body = $body->to_string();
} else {
$body = $this->wrap($body);
}
}
JAXLLogger::debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
JAXLLogger::debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
JAXLLogger::debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
JAXLLogger::debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
JAXLLogger::error("no ch found");
exit;
}
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.
self::NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
$this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
$this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
$this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
'xmlns:xmpp' => self::NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
if ($this->jaxl->cfg['jid'] !== null) {
$attrs['from'] = $this->jaxl->cfg['jid'];
}
$body = new JAXLXml('body', self::NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
$body = new JAXLXml('body', self::NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
JAXLLogger::debug("disconnecting");
}
}
diff --git a/src/JAXL/xmpp/xmpp_stanza.php b/src/JAXL/xmpp/xmpp_stanza.php
index 79e48e5..e4bbb96 100644
--- a/src/JAXL/xmpp/xmpp_stanza.php
+++ b/src/JAXL/xmpp/xmpp_stanza.php
@@ -1,194 +1,207 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Generic xmpp stanza object which provide convinient access pattern over xml objects
* Also to be able to convert an existing xml object into stanza object (to get access patterns going)
* this class doesn't extend xml, but infact works on a reference of xml object
* If not provided during constructor, new xml object is created and saved as reference
*
* @author abhinavsingh
*
*/
-class XMPPStanza
+class XMPPStanza extends JAXLXmlAccess
{
/**
* @var JAXLXml
*/
private $xml;
/**
* @param JAXLXml|string $name
* @param array $attrs
* @param string $ns
*/
public function __construct($name, array $attrs = array(), $ns = XMPP::NS_JABBER_CLIENT)
{
+ // TRICKY: Remove JAXLXmlAccess properties, so magic method __get will
+ // be called for them. This needed to use JAXLXmlAccess as a type hint.
+ $this->name = null;
+ unset($this->name);
+ $this->ns = null;
+ unset($this->ns);
+ $this->attrs = null;
+ unset($this->attrs);
+ $this->text = null;
+ unset($this->text);
+ $this->childrens = null;
+ unset($this->childrens);
+
if ($name instanceof JAXLXml) {
$this->xml = $name;
} else {
$this->xml = new JAXLXml($name, $ns, $attrs);
}
}
public function __call($method, $args)
{
return call_user_func_array(array($this->xml, $method), $args);
}
public function __get($prop)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
return isset($this->xml->attrs[$prop]) ? $this->xml->attrs[$prop] : null;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val) {
return null;
}
$val = new XMPPJid($val);
return $val->$key;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val = $this->xml->exists($prop);
if (!$val) {
return null;
}
return $val->text;
break;
default:
return null;
break;
}
}
public function __set($prop, $val)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop = $val;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
$this->xml->attrs[$prop] = $val;
return true;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val1 = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val1) {
$val1 = '';
}
$val1 = new XMPPJid($val1);
$val1->$key = $val;
$this->xml->attrs[$attr] = $val1->to_string();
return true;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val1 = $this->xml->exists($prop);
if (!$val1) {
$this->xml->c($prop)->t($val)->up();
} else {
$this->xml->update($prop, $val1->ns, $val1->attrs, $val);
}
return true;
break;
default:
return null;
break;
}
}
}
diff --git a/src/JAXL/xmpp/xmpp_stream.php b/src/JAXL/xmpp/xmpp_stream.php
index 1083a42..4d193be 100644
--- a/src/JAXL/xmpp/xmpp_stream.php
+++ b/src/JAXL/xmpp/xmpp_stream.php
@@ -1,655 +1,655 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
* @var JAXLSocketClient|XEP0206
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
* @param JAXLSocketClient|XEP0206 $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
$jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//JAXLLogger::debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
JAXLLogger::error(sprintf(
"got invalid return value from state handler '%s', sending end stream...",
$this->state
));
$this->send_end_stream();
$this->state = "logged_out";
JAXLLogger::notice(sprintf(
"state handler '%s' returned %s, kindly report this to developers",
$this->state,
serialize($r)
));
}
/**
- * @param JAXLXml|XMPPStanza $stanza
+ * @param JAXLXmlAccess $stanza
*/
- public function send($stanza)
+ public function send(JAXLXmlAccess $stanza)
{
$this->trans->send($stanza->to_string());
}
/**
* @param string $data
*/
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.XMPP::NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.XMPP::NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.XMPP::NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', XMPP::NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', XMPP::NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', XMPP::NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', XMPP::NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
JAXLLogger::debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', XMPP::NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', XMPP::NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
JAXLLogger::debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//JAXLLogger::debug("stream started");
return "wait_for_stream_features";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', XMPP::NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', XMPP::NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', XMPP::NS_BIND) ? true : false;
$sess = $stanza->exists('session', XMPP::NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', XMPP::NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
JAXLLogger::debug("no catch");
}
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == XMPP::NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'compressed' && $stanza->ns == XMPP::NS_COMPRESSION_PROTOCOL) {
$this->xml->reset_parser();
$this->trans->compress();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
}
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_compression_result", 0);
break;
}
}
public function wait_for_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'failure' && $stanza->ns == XMPP::NS_SASL) {
$reason = $stanza->childrens[0]->name;
//JAXLLogger::debug("sasl failed with reason ".$reason."");
$this->handle_auth_failure($reason);
return "logged_out";
} elseif ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$this->send_challenge_response($challenge);
return "wait_for_sasl_response";
} elseif ($stanza->name == 'success' && $stanza->ns == XMPP::NS_SASL) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
JAXLLogger::debug("got unhandled sasl response");
}
return "wait_for_sasl_response";
break;
default:
JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
diff --git a/tests/XMPPStanzaTest.php b/tests/XMPPStanzaTest.php
index a50a14b..757ff70 100644
--- a/tests/XMPPStanzaTest.php
+++ b/tests/XMPPStanzaTest.php
@@ -1,81 +1,105 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* @author abhinavsingh
*
*/
class XMPPStanzaTest extends PHPUnit_Framework_TestCase
{
public function test_xmpp_stanza_nested()
{
$xml = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]'));
$xml->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up()
->c('thread')->t('1234')->up()
->c('nested')
->c('nest')->t('nest1')->up()
->c('nest')->t('nest2')->up()
->c('nest')->t('nest3')->up()->up()
->c('c')->attrs(array('hash' => '84jsdmnskd'));
$stanza = new XMPPStanza($xml);
$this->assertEquals(
'<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested>' .
'<nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>',
$stanza->to_string()
);
}
public function test_xmpp_stanza_from_jaxl_xml()
{
// xml to stanza test
$xml = new JAXLXml('message', XMPP::NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q'));
$stanza = new XMPPStanza($xml);
$stanza->c('body')->t('hello world');
$this->assertEquals('XMPPStanza', get_class($stanza));
$this->assertEquals('JAXLXml', get_class($stanza->exists('body')));
$this->assertEquals('[email protected]', $stanza->to);
$this->assertEquals(
'<message xmlns="jabber:client" to="[email protected]" from="[email protected]/q">' .
'<body>hello world</body></message>',
$stanza->to_string()
);
}
+
+ public function testXMPPStanzaAndJAXLXmlAreInterchangeable()
+ {
+ $test_data = array(
+ 'name' => 'msg',
+ 'ns' => 'NAMESPACE',
+ 'attrs' => array('a' => '1', 'b' => '2'),
+ 'text' => 'Test message'
+ );
+ $xml = new JAXLXml($test_data['name'], $test_data['ns'], $test_data['attrs'], $test_data['text']);
+ $stanza = new XMPPStanza($xml);
+ $this->checkJAXLXmlAccess($xml, $test_data);
+ $this->checkJAXLXmlAccess($stanza, $test_data);
+ }
+
+ protected function checkJAXLXmlAccess(JAXLXmlAccess $xml_or_stanza, $test_data)
+ {
+ $this->assertEquals($test_data['name'], $xml_or_stanza->name);
+ $this->assertEquals($test_data['ns'], $xml_or_stanza->ns);
+ $this->assertEquals($test_data['attrs'], $xml_or_stanza->attrs);
+ $this->assertEquals($test_data['text'], $xml_or_stanza->text);
+ $this->assertEquals(array(), $xml_or_stanza->childrens);
+ return true;
+ }
}
|
jaxl/JAXL | da91250a3b8c6b5e66947845593bf37e5b6bda0b | Change global log functions _error, ... to JAXLLogger::error and so on | diff --git a/docs/users/http_examples.rst b/docs/users/http_examples.rst
index 12286ee..2af0d78 100644
--- a/docs/users/http_examples.rst
+++ b/docs/users/http_examples.rst
@@ -1,98 +1,98 @@
HTTP Examples
=============
Writing HTTP Server
-------------------
Intialize an ``HTTPServer`` instance
.. code-block:: ruby
$http = new HTTPServer();
By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this.
Define a callback method that will accept all incoming ``HTTPRequest`` objects
.. code-block:: ruby
function on_request($request)
{
if ($request->method == 'GET') {
$body = json_encode($request);
$request->ok($body, array('Content-Type' => 'application:json'));
} else {
$request->not_found();
}
}
``on_request`` callback method will receive a ``HTTPRequest`` object instance.
For this example, we will simply echo back json encoded ``$request`` object for
every http GET request.
Start http server:
.. code-block:: ruby
$http->start('on_request');
We pass ``on_request`` method as first parameter to ``HTTPServer::start/1``.
If nothing is passed, requests will fail with a default 404 not found error message
Writing REST API Server
-----------------------
Intialize an ``HTTPServer`` instance
.. code-block:: ruby
$http = new HTTPServer();
By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this.
Define our REST resources callback methods:
.. code-block:: ruby
function index($request)
{
$request->send_response(
200, array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>'
);
$request->close();
}
function upload($request)
{
if ($request->method == 'GET') {
$request->send_response(
200, array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action=""><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>'
);
} elseif ($request->method == 'POST') {
if ($request->body === null && $request->expect) {
$request->recv_body();
} else {
// got upload body, save it
- _debug("file upload complete, got ".strlen($request->body)." bytes of data");
+ JAXLLogger::debug("file upload complete, got ".strlen($request->body)." bytes of data");
$request->close();
}
}
}
Next we need to register dispatch rules for our callbacks above:
.. code-block:: ruby
$index = array('index', '^/$');
$upload = array('upload', '^/upload', array('GET', 'POST'));
$rules = array($index, $upload);
$http->dispatch($rules);
Start REST api server:
.. code-block:: ruby
$http->start();
Make an HTTP request
--------------------
diff --git a/docs/users/logging.rst b/docs/users/logging.rst
index 068a9f1..1ff0736 100644
--- a/docs/users/logging.rst
+++ b/docs/users/logging.rst
@@ -1,33 +1,33 @@
Logging Interface
=================
``JAXLLogger`` provides all the logging facilities that we will ever require.
When logging to ``STDOUT`` it also colorizes the log message depending upon
its severity level. When logging to a file it can also do periodic log
rotation.
log levels
----------
* ERROR (red)
* WARNING (blue)
* NOTICE (yellow)
* INFO (green)
* DEBUG (white)
global logging methods
----------------------
Following global methods for logging are available:
- * ``_error($msg)``
- * ``_warning($msg)``
- * ``_notice($msg)``
- * ``_info($msg)``
- * ``_debug($msg)``
+ * ``error($msg)``
+ * ``warning($msg)``
+ * ``notice($msg)``
+ * ``info($msg)``
+ * ``debug($msg)``
log/2
-----------
All the above global logging methods internally use ``log($msg, $verbosity)``
to output colored log message on the terminal.
diff --git a/docs/users/xmpp_examples.rst b/docs/users/xmpp_examples.rst
index 927a310..0f11fdc 100644
--- a/docs/users/xmpp_examples.rst
+++ b/docs/users/xmpp_examples.rst
@@ -1,117 +1,117 @@
XMPP Examples
=============
Echo Bot Client
---------------
include ``jaxl.php`` and initialize a new ``JAXL`` instance:
.. code-block:: ruby
$client = new JAXL(array(
'jid' => '[email protected]',
'pass' => 'password'
));
We just initialized a new ``JAXL`` instance by passing our jabber client ``jid`` and ``pass``.
View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor.
Next we need to register callbacks on events of interest using ``JAXL::add_cb/2`` method as shown below:
.. code-block:: ruby
$client->add_cb('on_auth_success', function () {
global $client;
$client->set_status("available!"); // set your status
$client->get_vcard(); // fetch your vcard
$client->get_roster(); // fetch your roster list
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_disconnect', function () {
- _debug("got on_disconnect cb");
+ JAXLLogger::debug("got on_disconnect cb");
});
We just registered callbacks on ``on_auth_success``, ``on_chat_message`` and ``on_disconnect`` events
that will occur inside our configured ``JAXL`` instance lifecycle.
We also passed a method that will be called (with parameters if any) when the event has been detected.
See list of :ref:`available event callbacks <jaxl-instance>` that we can hook to inside ``JAXL`` instance lifecycle.
Received ``$msg`` parameter with ``on_chat_message`` event callback above, will be an instance of ``XMPPMsg`` which
extends ``XMPPStanza`` class, that allows us easy to use access patterns to common XMPP stanza attributes like
``to``, ``from``, ``type``, ``id`` to name a few.
We were also able to access our xmpp client full jabber id by calling ``$client->full_jid``. This attribute of
``JAXL`` instance is available from ``on_auth_success`` event. ``full_jid`` attribute is an instance of ``XMPPJid``.
To send our echo back ``$msg`` packet we called ``JAXL::send/1`` which accepts a single parameter which MUST be
an instance of ``JAXLXml``. Since ``XMPPStanza`` is a wrapper upon ``JAXLXml`` we can very well pass our modified
``$msg`` object to the send method.
Read more about various :ref:`XML Objects <xml-objects>` and how they make writing XMPP applications fun and easy.
You can also :ref:`add custom access patterns <xml-objects>` upon received ``XMPPStanza`` objects. Since all access
patterns are evaluated upon first access and cached for later usage, adding hundreds of custom access patterns that
retrieves information from 100th child of received XML packet will not be an issue.
We will finally start our xmpp client by calling:
.. code-block:: ruby
$client->start();
See list of :ref:`available options <jaxl-instance>` that can be passed to the ``JAXL::start/2`` method.
These options are particularly useful for debugging and monitoring.
Echo Bot BOSH Client
--------------------
Everything goes same for a cli BOSH client. To run above echo bot client example as a bosh client simply
pass additional parameters to ``JAXL`` constructor:
.. code-block:: ruby
$client = new JAXL(array(
'jid' => '[email protected]',
'pass' => 'password',
'bosh_url' => 'http://localhost:5280/http-bind'
));
You can even pass custom values for ``hold``, ``wait`` and other attributes.
View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor.
Echo Bot External Component
---------------------------
Again almost everything goes same for an external component except a few custom ``JAXL`` constructor
parameter as shown below:
.. code-block:: ruby
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required) destination socket
'host' => $argv[3],
'port' => $argv[4]
));
We will also need to include ``XEP0114`` which implements Jabber Component XMPP Extension.
.. code-block:: ruby
// (required)
$comp->require_xep(array(
'0114' // jabber component protocol
));
``JAXL::require_xep/1`` accepts an array of XEP numbers passed as strings.
diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php
index 0b99c3c..13d8ca9 100644
--- a/examples/echo_bosh_bot.php
+++ b/examples/echo_bosh_bot.php
@@ -1,107 +1,107 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 3) {
echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'bosh_url' => 'http://localhost:5280/http-bind',
// (optional) srv lookup is done if not provided
// for bosh client 'host' value is used for 'route' attribute
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
// for bosh client 'port' value is used for 'route' attribute
//'port' => 5222,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXLLogger::INFO
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
- _info("got on_auth_failure cb with reason $reason");
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_disconnect', function () {
- _info("got on_disconnect cb");
+ JAXLLogger::info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/echo_bot.php b/examples/echo_bot.php
index b3b2d86..ec667d9 100644
--- a/examples/echo_bot.php
+++ b/examples/echo_bot.php
@@ -1,148 +1,148 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// Run as:
// php examples/echo_bot.php root@localhost password
// php examples/echo_bot.php root@localhost password DIGEST-MD5
// php examples/echo_bot.php localhost "" ANONYMOUS
if ($argc < 3) {
echo "Usage: $argv[0] jid pass auth_type".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (optional) srv lookup is done if not provided
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
//'port' => 5222,
// (optional) defaults to false
//'force_tls' => true,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXLLogger::INFO
));
//
// required XEP's
//
$client->require_xep(array(
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
});
// by default JAXL instance catches incoming roster list results and updates
// roster list is parsed/cached and an event 'on_roster_update' is emitted
$client->add_cb('on_roster_update', function () {
//global $client;
//print_r($client->roster);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
- _info("got on_auth_failure cb with reason $reason");
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_presence_stanza', function ($stanza) {
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
- _info($stanza->from." is now ".$type." ($show)");
+ JAXLLogger::info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
});
$client->add_cb('on_disconnect', function () {
- _info("got on_disconnect cb");
+ JAXLLogger::info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start(array(
'--with-debug-shell' => true,
'--with-unix-sock' => true
));
echo "done".PHP_EOL;
diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php
index bcb106e..4ca3646 100644
--- a/examples/echo_component_bot.php
+++ b/examples/echo_component_bot.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc != 5) {
echo "Usage: $argv[0] jid pass host port".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'host' => $argv[3],
'port' => $argv[4],
'log_level' => JAXLLogger::INFO
));
//
// XEP's required (required)
//
$comp->require_xep(array(
'0114' // jabber component protocol
));
//
// add necessary event callbacks here
//
$comp->add_cb('on_auth_success', function () {
- _info("got on_auth_success cb");
+ JAXLLogger::info("got on_auth_success cb");
});
$comp->add_cb('on_auth_failure', function ($reason) {
global $comp;
$comp->send_end_stream();
- _info("got on_auth_failure cb with reason $reason");
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
});
$comp->add_cb('on_chat_message', function ($stanza) {
global $comp;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $comp->jid->to_string();
$comp->send($stanza);
});
$comp->add_cb('on_disconnect', function () {
- _info("got on_disconnect cb");
+ JAXLLogger::info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$comp->start();
echo "done".PHP_EOL;
diff --git a/examples/echo_unix_sock_server.php b/examples/echo_unix_sock_server.php
index ed9a38a..4f6df37 100644
--- a/examples/echo_unix_sock_server.php
+++ b/examples/echo_unix_sock_server.php
@@ -1,63 +1,63 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 2) {
echo "Usage: $argv[0] /path/to/server.sock".PHP_EOL;
exit;
}
JAXLLogger::$level = JAXLLogger::INFO;
$server = null;
function on_request($client, $raw)
{
global $server;
$server->send($client, $raw);
- _info("got client callback ".$raw);
+ JAXLLogger::info("got client callback ".$raw);
}
if (file_exists($argv[1])) {
unlink($argv[1]);
}
$server = new JAXLSocketServer('unix://'.$argv[1], null, 'on_request');
JAXLLoop::run();
echo "done".PHP_EOL;
diff --git a/examples/http_bind.php b/examples/http_bind.php
index a050e09..35f032e 100644
--- a/examples/http_bind.php
+++ b/examples/http_bind.php
@@ -1,65 +1,65 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if (!isset($_GET['jid']) || !isset($_GET['pass'])) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $_GET['jid'],
'pass' => $_GET['pass'],
'bosh_url' => 'http://localhost:5280/http-bind',
'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php
index 61ebb18..d7f9cbc 100644
--- a/examples/http_pre_bind.php
+++ b/examples/http_pre_bind.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// http pre bind php script
$body = file_get_contents("php://input");
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (!isset($attrs['to']) &&
!isset($attrs['rid']) &&
!isset($attrs['wait']) &&
!isset($attrs['hold'])
) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
$to = (string)$attrs['to'];
$rid = (int)$attrs['rid'];
$wait = (int)$attrs['wait'];
$hold = (int)$attrs['hold'];
list($host, $port) = JAXLUtil::get_dns_srv($to);
$client = new JAXL(array(
'domain' => $to,
'host' => $host,
'port' => $port,
'bosh_url' => 'http://localhost:5280/http-bind',
'bosh_rid' => $rid,
'bosh_wait' => $wait,
'bosh_hold' => $hold,
'auth_type' => 'ANONYMOUS',
'log_level' => JAXLLogger::INFO
));
$client->add_cb('on_auth_success', function () {
global $client;
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
echo sprintf(
'<body xmlns="%s" sid="%s" rid="%s" jid="%s"/>',
XEP0206::NS_HTTP_BIND,
$client->xeps['0206']->sid,
$client->xeps['0206']->rid,
$client->full_jid->to_string()
);
exit;
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
- _info("got on_auth_failure cb with reason $reason");
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php
index 05d194a..98cdb62 100644
--- a/examples/http_rest_server.php
+++ b/examples/http_rest_server.php
@@ -1,127 +1,127 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// configure logger
JAXLLogger::$level = JAXLLogger::INFO;
// print usage notice and parse addr/port parameters if passed
JAXLLogger::cliLog("Usage: $argv[0] port (default: 9699)", JAXLLogger::NOTICE);
$port = ($argc == 2 ? $argv[1] : 9699);
// initialize http server
$http = new HTTPServer($port);
// callback method for dispatch rule (see below)
function index($request)
{
$request->send_response(
200,
array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>'
);
$request->close();
}
// callback method for dispatch rule (see below)
function upload($request)
{
if ($request->method == 'GET') {
$request->ok(
array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" ' .
'action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" ' .
'value="upload"/></form></body></html>'
);
} elseif ($request->method == 'POST') {
if ($request->body === null && $request->expect) {
$request->recv_body();
} else {
// got upload body, save it
- _info("file upload complete, got ".strlen($request->body)." bytes of data");
+ JAXLLogger::info("file upload complete, got ".strlen($request->body)." bytes of data");
$upload_data = $request->multipart->form_data[0]['body'];
$request->ok(
$upload_data,
array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])
);
}
}
}
// add dispatch rules with callback method as first argument
$index = array('index', '^/$');
$upload = array('upload', '^/upload', array('GET', 'POST'));
// some REST CRUD style callback methods
// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules
function create_event($request)
{
- _info("got event create request");
+ JAXLLogger::info("got event create request");
$request->close();
}
function read_event($request, $pk)
{
- _info("got event read request for $pk");
+ JAXLLogger::info("got event read request for $pk");
$request->close();
}
function update_event($request, $pk)
{
- _info("got event update request for $pk");
+ JAXLLogger::info("got event update request for $pk");
$request->close();
}
function delete_event($request, $pk)
{
- _info("got event delete request for $pk");
+ JAXLLogger::info("got event delete request for $pk");
$request->close();
}
$event_create = array('create_event', '^/event/create/$', array('PUT'));
$event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD'));
$event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST'));
$event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE'));
// prepare rule set
$rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete);
$http->dispatch($rules);
// start http server
$http->start();
diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php
index 27b401f..3a0d3e8 100644
--- a/examples/muc_log_bot.php
+++ b/examples/muc_log_bot.php
@@ -1,147 +1,147 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 5) {
echo "Usage: $argv[0] host jid pass [email protected] nickname".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[2],
'pass' => $argv[3],
'host' => $argv[1],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0045', // MUC
'0203', // Delayed Delivery
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$_room_full_jid = $argv[4]."/".$argv[5];
$room_full_jid = new XMPPJid($_room_full_jid);
$client->add_cb('on_auth_success', function () {
global $client, $room_full_jid;
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// join muc room
$client->xeps['0045']->join_room($room_full_jid);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
- _info("got on_auth_failure cb with reason $reason");
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_groupchat_message', function ($stanza) {
global $client;
$from = new XMPPJid($stanza->from);
$delay = $stanza->exists('delay', XEP0203::NS_DELAYED_DELIVERY);
if ($from->resource) {
echo sprintf(
"message stanza rcvd from %s saying... %s, %s".PHP_EOL,
$from->resource,
$stanza->body,
$delay ? "delay timestamp ".$delay->attrs['stamp'] : "timestamp ".gmdate("Y-m-dTH:i:sZ")
);
} else {
$subject = $stanza->exists('subject');
if ($subject) {
echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".
$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL;
}
}
});
$client->add_cb('on_presence_stanza', function ($stanza) {
global $client, $room_full_jid;
$from = new XMPPJid($stanza->from);
// self-stanza received, we now have complete room roster
if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) {
if (($x = $stanza->exists('x', XEP0045::NS_MUC.'#user')) !== false) {
if (($status = $x->exists('status', null, array('code' => '110'))) !== false) {
$item = $x->exists('item');
- _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].
+ JAXLLogger::info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].
", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']);
} else {
- _info("xmlns #user have no x child element");
+ JAXLLogger::info("xmlns #user have no x child element");
}
} else {
- _warning("=======> odd case 1");
+ JAXLLogger::warning("=======> odd case 1");
}
} elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) {
// stanza from other users received
if (($x = $stanza->exists('x', XEP0045::NS_MUC.'#user')) !== false) {
$item = $x->exists('item');
echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".
$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL;
} else {
- _warning("=======> odd case 2");
+ JAXLLogger::warning("=======> odd case 2");
}
} else {
- _warning("=======> odd case 3");
+ JAXLLogger::warning("=======> odd case 3");
}
});
$client->add_cb('on_disconnect', function () {
- _info("got on_disconnect cb");
+ JAXLLogger::info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/multi_client.php b/examples/multi_client.php
index a07c5dc..578c0ba 100644
--- a/examples/multi_client.php
+++ b/examples/multi_client.php
@@ -1,129 +1,129 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// input multiple account credentials
$accounts = array();
$add_new = true;
while ($add_new) {
$jid = readline('Enter Jabber Id: ');
$pass = readline('Enter Password: ');
$accounts[] = array($jid, $pass);
$next = readline('Add another account (y/n): ');
$add_new = $next == 'y' ? true : false;
}
//
// common callbacks
//
function on_auth_success($client)
{
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
}
function on_auth_failure($client, $reason)
{
- _info("got on_auth_failure cb with reason $reason");
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
}
function on_chat_message($client, $stanza)
{
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
}
function on_presence_stanza($client, $stanza)
{
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
- _info($stanza->from." is now ".$type." ($show)");
+ JAXLLogger::info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
}
function on_disconnect($client)
{
- _info("got on_disconnect cb");
+ JAXLLogger::info("got on_disconnect cb");
}
//
// bootstrap all account instances
//
foreach ($accounts as $account) {
$client = new JAXL(array(
'jid' => $account[0],
'pass' => $account[1],
'log_level' => JAXLLogger::DEBUG,
// Enable multi client support.
// This will force 1st parameter of callbacks as connected client instance.
'multi_client' => true
));
$client->add_cb('on_auth_success', 'on_auth_success');
$client->add_cb('on_auth_failure', 'on_auth_failure');
$client->add_cb('on_chat_message', 'on_chat_message');
$client->add_cb('on_presence_stanza', 'on_presence_stanza');
$client->add_cb('on_disconnect', 'on_disconnect');
$client->connect($client->get_socket_path());
$client->start_stream();
}
// start core loop
JAXLLoop::run();
echo "done".PHP_EOL;
diff --git a/examples/pipes.php b/examples/pipes.php
index 37f720e..a1ba30c 100644
--- a/examples/pipes.php
+++ b/examples/pipes.php
@@ -1,55 +1,55 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// configure logger
JAXLLogger::$level = JAXLLogger::INFO;
// initialize
$pipe_name = getmypid();
$pipe = new JAXLPipe($pipe_name);
// add read event callback
$pipe->set_callback(function ($data) {
global $pipe;
- _info("read ".trim($data)." from pipe");
+ JAXLLogger::info("read ".trim($data)." from pipe");
});
JAXLLoop::run();
echo "done".PHP_EOL;
diff --git a/examples/publisher.php b/examples/publisher.php
index 3ee089f..4014245 100644
--- a/examples/publisher.php
+++ b/examples/publisher.php
@@ -1,102 +1,102 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 3) {
echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// publish
$item = new JAXLXml('item', null, array('id' => time()));
$item->c('entry', 'http://www.w3.org/2005/Atom');
$item->c('title')->t('Soliloquy')->up();
$item->c('summary')->t('To be, or not to be: that is the question')->up();
$item->c(
'link',
null,
array('rel' => 'alternate', 'type' => 'text/html', 'href' => 'http://denmark.lit/2003/12/13/atom03')
)->up();
$item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up();
$item->c('published')->t('2003-12-13T18:30:02Z')->up();
$item->c('updated')->t('2003-12-13T18:30:02Z')->up();
$client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
- _info("got on_auth_failure cb with reason $reason");
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_disconnect', function () {
- _info("got on_disconnect cb");
+ JAXLLogger::info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/register_user.php b/examples/register_user.php
index fb6cddf..d82e8ed 100644
--- a/examples/register_user.php
+++ b/examples/register_user.php
@@ -1,168 +1,168 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 2) {
echo "Usage: $argv[0] domain".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'log_level' => JAXLLogger::DEBUG
));
$client->require_xep(array(
'0077' // InBand Registration
));
//
// below are two states which become part of
// our client's xmpp_stream lifecycle
// consider as if these methods are directly
// inside xmpp_stream state machine
//
// Note: $stanza = $args[0] is an instance of
// JAXLXml in xmpp_stream state methods,
// it is yet not ready for easy access
// patterns available on XMPPStanza instances
//
$form = array();
function wait_for_register_response($event, $args)
{
global $client, $form;
if ($event == 'stanza_cb') {
$stanza = $args[0];
if ($stanza->name == 'iq') {
$form['type'] = $stanza->attrs['type'];
if ($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
} elseif ($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo sprintf(
"registration failed with error code: %s and type: %s".PHP_EOL,
$error->attrs['code'],
$error->attrs['type']
);
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
}
}
} else {
- _notice("unhandled event $event rcvd");
+ JAXLLogger::notice("unhandled event $event rcvd");
}
}
function wait_for_register_form($event, $args)
{
global $client, $form;
$stanza = $args[0];
$query = $stanza->exists('query', XEP0077::NS_INBAND_REGISTER);
if ($query) {
$instructions = $query->exists('instructions');
if ($instructions) {
echo $instructions->text.PHP_EOL;
}
foreach ($query->childrens as $k => $child) {
if ($child->name != 'instructions') {
$form[$child->name] = readline($child->name.":");
}
}
$client->xeps['0077']->set_form($stanza->attrs['from'], $form);
return "wait_for_register_response";
} else {
$client->end_stream();
return "logged_out";
}
}
//
// add necessary event callbacks here
//
$client->add_cb('on_stream_features', function ($stanza) {
global $client, $argv;
$client->xeps['0077']->get_form($argv[1]);
return "wait_for_register_form";
});
$client->add_cb('on_disconnect', function () {
global $form;
- _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
+ JAXLLogger::info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
});
//
// finally start configured xmpp stream
//
$client->start();
//
// if registration was successful
// try to connect with newly registered account
//
if ($form['type'] == 'result') {
- _info("connecting newly registered user account");
+ JAXLLogger::info("connecting newly registered user account");
$client = new JAXL(array(
'jid' => $form['username'].'@'.$argv[1],
'pass' => $form['password'],
'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
$client->set_status('Available');
});
$client->start();
}
echo "done".PHP_EOL;
diff --git a/examples/subscriber.php b/examples/subscriber.php
index fec9268..b3b0b18 100644
--- a/examples/subscriber.php
+++ b/examples/subscriber.php
@@ -1,97 +1,97 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 3) {
echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// subscribe
$client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node');
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
- _info("got on_auth_failure cb with reason $reason");
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_headline_message', function ($stanza) {
global $client;
if (($event = $stanza->exists('event', XEP0060::NS_PUBSUB.'#event'))) {
- _info("got pubsub event");
+ JAXLLogger::info("got pubsub event");
} else {
- _warning("unknown headline message rcvd");
+ JAXLLogger::warning("unknown headline message rcvd");
}
});
$client->add_cb('on_disconnect', function () {
- _info("got on_disconnect cb");
+ JAXLLogger::info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php
index d3924e6..029e8c9 100644
--- a/examples/xmpp_rest.php
+++ b/examples/xmpp_rest.php
@@ -1,75 +1,75 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// View explanation for this example here:
// https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ
if ($argc < 3) {
echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
// initialize xmpp client
$xmpp = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
// register callbacks on required xmpp events
$xmpp->add_cb('on_auth_success', function () {
global $xmpp;
- _info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string());
});
// initialize http server
$http = new HTTPServer();
// add generic callback
// you can also dispatch REST style callback
// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules
$http->cb = function ($request) {
// For demo purposes we simply return xmpp client full jid
global $xmpp;
$request->ok($xmpp->full_jid->to_string());
};
// This will start main JAXLLoop,
// hence we don't need to call $http->start() explicitly
$xmpp->start();
diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php
index 8fe2c91..734e5ed 100644
--- a/examples/xoauth2_gtalk_client.php
+++ b/examples/xoauth2_gtalk_client.php
@@ -1,98 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc != 3) {
echo "Usage: $argv[0] jid access_token".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// force tls
'force_tls' => true,
// (required) perform X-OAUTH2
'auth_type' => 'X-OAUTH2',
// (optional)
//'resource' => 'resource',
'log_level' => JAXLLogger::DEBUG
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
+ JAXLLogger::info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
- _info("got on_auth_failure cb with reason $reason");
+ JAXLLogger::info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_disconnect', function () {
- _info("got on_disconnect cb");
+ JAXLLogger::info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/src/JAXL/core/jaxl_clock.php b/src/JAXL/core/jaxl_clock.php
index eef7931..371c9d4 100644
--- a/src/JAXL/core/jaxl_clock.php
+++ b/src/JAXL/core/jaxl_clock.php
@@ -1,129 +1,129 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class JAXLClock
{
// current clock time in microseconds
private $tick = 0;
// current Unix timestamp with microseconds
public $time = null;
// scheduled jobs
public $jobs = array();
public function __construct()
{
$this->time = microtime(true);
}
public function __destruct()
{
- _info("shutting down clock server...");
+ JAXLLogger::info("shutting down clock server...");
}
public function tick($by = null)
{
// update clock
if ($by) {
$this->tick += $by;
$this->time += $by / pow(10, 6);
} else {
$time = microtime(true);
$by = $time - $this->time;
$this->tick += $by * pow(10, 6);
$this->time = $time;
}
// run scheduled jobs
foreach ($this->jobs as $ref => $job) {
if ($this->tick >= $job['scheduled_on'] + $job['after']) {
- //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".
+ //JAXLLogger::debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".
// $job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']);
call_user_func($job['cb'], $job['args']);
if (!$job['is_periodic']) {
unset($this->jobs[$ref]);
} else {
$job['scheduled_on'] = $this->tick;
$job['runs']++;
$this->jobs[$ref] = $job;
}
}
}
}
// calculate execution time of callback
public function tc($callback, $args = null)
{
}
// callback after $time microseconds
public function call_fun_after($time, $callback, $args = null)
{
$this->jobs[] = array(
'scheduled_on' => $this->tick,
'after' => $time,
'cb' => $callback,
'args' => $args,
'is_periodic' => false,
'runs' => 0
);
return count($this->jobs);
}
// callback periodically after $time microseconds
public function call_fun_periodic($time, $callback, $args = null)
{
$this->jobs[] = array(
'scheduled_on' => $this->tick,
'after' => $time,
'cb' => $callback,
'args' => $args,
'is_periodic' => true,
'runs' => 0
);
return count($this->jobs);
}
// cancel a previously scheduled callback
public function cancel_fun_call($ref)
{
unset($this->jobs[$ref-1]);
}
}
diff --git a/src/JAXL/core/jaxl_event.php b/src/JAXL/core/jaxl_event.php
index 96ba88c..bb6a90c 100644
--- a/src/JAXL/core/jaxl_event.php
+++ b/src/JAXL/core/jaxl_event.php
@@ -1,167 +1,167 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Following kind of events are possible:
* 1) hook i.e. if a callback for such an event is registered, calling function
* is responsible for the workflow from their on
* 2) filter i.e. calling function will manipulate passed arguments
* and modified arguments will be passed to next chain of filter
*
* As a rule of thumb, only 1 hook can be registered for an event, while more
* than 1 filter is allowed for an event hook and filter both cannot be applied
* on an event.
*
* @author abhinavsingh
*
*/
class JAXLEvent
{
protected $common = array();
protected $reg = array();
/**
* @param array $common
*/
public function __construct(array $common = array())
{
$this->common = $common;
}
public function __destruct()
{
}
/**
* Add callback on a event.
*
* Callback'd method must return `true` to be persistent, otherwise
* if returned `null` or `false`, callback will be removed automatically.
*
* @param string $ev
* @param callable $cb
* @param int $priority
* @return string Reference to be used while deleting callback.
*/
public function add($ev, $cb, $priority)
{
if (!isset($this->reg[$ev])) {
$this->reg[$ev] = array();
}
$ref = count($this->reg[$ev]);
$this->reg[$ev][] = array($priority, $cb);
return $ev."-".$ref;
}
/**
* Emit event to notify registered callbacks.
*
* TODO: Is a pqueue required here for performance enhancement in case we
* have too many cbs on a specific event?
*
* @param string $ev
* @param array $data
* @return array
*/
public function emit($ev, array $data = array())
{
$data = array_merge($this->common, $data);
$cbs = array();
if (!isset($this->reg[$ev])) {
return $data;
}
foreach ($this->reg[$ev] as $cb) {
if (!isset($cbs[$cb[0]])) {
$cbs[$cb[0]] = array();
}
$cbs[$cb[0]][] = $cb[1];
}
foreach ($cbs as $pri => $cb) {
foreach ($cb as $c) {
$ret = call_user_func_array($c, $data);
// This line is for fixing situation where callback function doesn't return an array type.
// In such cases next call of call_user_func_array will report error since $data is not
// an array type as expected.
// Things will change in future, atleast put the callback inside a try/catch block.
// Here we only check if there was a return, if yes we update $data with return value.
// This is bad design, need more thoughts, should work as of now.
if ($ret) {
$data = $ret;
}
}
}
unset($cbs);
return $data;
}
/**
* Remove previous registered callback.
*
* @param string $ref
*/
public function del($ref)
{
$ref = explode("-", $ref);
unset($this->reg[$ref[0]][$ref[1]]);
}
/**
* @param string $ev
* @return bool
*/
public function exists($ev)
{
$ret = isset($this->reg[$ev]);
- //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists"));
+ //JAXLLogger::debug("event ".$ev." callback ".($ret ? "exists" : "do not exists"));
return $ret;
}
/**
* @return array List of registered events.
*/
public function getRegistry()
{
return $this->reg;
}
}
diff --git a/src/JAXL/core/jaxl_exception.php b/src/JAXL/core/jaxl_exception.php
index 64ba648..e9a9293 100644
--- a/src/JAXL/core/jaxl_exception.php
+++ b/src/JAXL/core/jaxl_exception.php
@@ -1,100 +1,100 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* @author abhinavsingh
*/
class JAXLException extends Exception
{
public function __construct($message = null, $code = null, $file = null, $line = null)
{
- _notice("got jaxl exception construct with $message, $code, $file, $line");
+ JAXLLogger::notice("got jaxl exception construct with $message, $code, $file, $line");
if ($code === null) {
parent::__construct($message);
} else {
parent::__construct($message, $code);
}
if ($file !== null) {
$this->file = $file;
}
if ($line !== null) {
$this->line = $line;
}
}
public static function addHandlers()
{
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public static function error_handler($errno, $error, $file, $line, $vars)
{
- _debug("error handler called with $errno, $error, $file, $line");
+ JAXLLogger::debug("error handler called with $errno, $error, $file, $line");
if ($errno === 0 || ($errno & error_reporting()) === 0) {
return;
}
throw new JAXLException($error, $errno, $file, $line);
}
public static function exception_handler($e)
{
- _debug("exception handler catched ".json_encode($e));
+ JAXLLogger::debug("exception handler catched ".json_encode($e));
// TODO: Pretty print backtrace
//print_r(debug_backtrace());
}
public static function shutdown_handler()
{
try {
- _debug("got shutdown handler");
+ JAXLLogger::debug("got shutdown handler");
if (null !== ($error = error_get_last())) {
throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']);
}
} catch (Exception $e) {
- _debug("shutdown handler catched with exception ".json_encode($e));
+ JAXLLogger::debug("shutdown handler catched with exception ".json_encode($e));
}
}
}
diff --git a/src/JAXL/core/jaxl_fsm.php b/src/JAXL/core/jaxl_fsm.php
index 8d673ed..06682bb 100644
--- a/src/JAXL/core/jaxl_fsm.php
+++ b/src/JAXL/core/jaxl_fsm.php
@@ -1,98 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
abstract class JAXLFsm
{
protected $state = null;
// abstract method
abstract public function handle_invalid_state($r);
public function __construct($state)
{
$this->state = $state;
}
// returned value from state callbacks can be:
// 1) array() <-- is_callable method
// 2) array([0] => 'new_state', [1] => 'return value for current callback') <-- is_not_callable method
// 3) array([0] => 'new_state')
// 4) 'new_state'
//
// for case 1) new state will be an array
// for other cases new state will be a string
public function __call($event, $args)
{
if ($this->state) {
// call state method
- _debug(sprintf(
+ JAXLLogger::debug(sprintf(
"calling state handler '%s' for incoming event '%s'",
is_array($this->state) ? $this->state[1] : $this->state,
$event
));
if (is_callable($this->state)) {
$call = $this->state;
} else {
$call = method_exists($this, $this->state) ? array(&$this, $this->state): $this->state;
}
$r = call_user_func($call, $event, $args);
// 4 cases of possible return value
if (is_callable($r)) {
$this->state = $r;
} elseif (is_array($r) && count($r) == 2) {
list($this->state, $ret) = $r;
} elseif (is_array($r) && count($r) == 1) {
$this->state = $r[0];
} elseif (is_string($r)) {
$this->state = $r;
} else {
$this->handle_invalid_state($r);
}
- _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'");
+ JAXLLogger::debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'");
// return case
if (!is_callable($r) && is_array($r) && count($r) == 2) {
return $ret;
}
} else {
- _debug("invalid state found, nothing called for event ".$event."");
+ JAXLLogger::debug("invalid state found, nothing called for event ".$event."");
}
}
}
diff --git a/src/JAXL/core/jaxl_logger.php b/src/JAXL/core/jaxl_logger.php
index 38d46b7..6cb9030 100644
--- a/src/JAXL/core/jaxl_logger.php
+++ b/src/JAXL/core/jaxl_logger.php
@@ -1,137 +1,140 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-// generic global logging shortcuts for different level of verbosity
-function _error($msg)
-{
- JAXLLogger::log($msg, JAXLLogger::ERROR);
-}
-function _warning($msg)
-{
- JAXLLogger::log($msg, JAXLLogger::WARNING);
-}
-function _notice($msg)
-{
- JAXLLogger::log($msg, JAXLLogger::NOTICE);
-}
-function _info($msg)
-{
- JAXLLogger::log($msg, JAXLLogger::INFO);
-}
-function _debug($msg)
-{
- JAXLLogger::log($msg, JAXLLogger::DEBUG);
-}
-
class JAXLLogger
{
// Log levels.
const ERROR = 1;
const WARNING = 2;
const NOTICE = 3;
const INFO = 4;
const DEBUG = 5;
public static $colorize = true;
public static $level = self::DEBUG;
public static $path = null;
public static $max_log_size = 1000;
protected static $colors = array(
self::ERROR => 31, // red
self::WARNING => 34, // blue
self::NOTICE => 33, // yellow
self::INFO => 32, // green
self::DEBUG => 37 // white
);
public static function log($msg, $verbosity = self::ERROR)
{
if ($verbosity <= self::$level) {
$bt = debug_backtrace();
array_shift($bt);
$callee = array_shift($bt);
$msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg;
$size = strlen($msg);
if ($size > self::$max_log_size) {
$msg = substr($msg, 0, self::$max_log_size) . ' ...';
}
if (isset(self::$path)) {
error_log($msg . PHP_EOL, 3, self::$path);
} else {
error_log(self::colorize($msg, $verbosity));
}
}
}
+ public static function error($msg)
+ {
+ self::log($msg, self::ERROR);
+ }
+
+ public static function warning($msg)
+ {
+ self::log($msg, self::WARNING);
+ }
+
+ public static function notice($msg)
+ {
+ self::log($msg, self::NOTICE);
+ }
+
+ public static function info($msg)
+ {
+ self::log($msg, self::INFO);
+ }
+
+ public static function debug($msg)
+ {
+ self::log($msg, self::DEBUG);
+ }
+
// Generic global terminal output colorize method.
// Finally sends colorized message to terminal using error_log/1
// this method is mainly to escape $msg from file:line and time
// prefix done by debug, error, ... methods.
public static function cliLog($msg, $verbosity)
{
error_log(self::colorize($msg, $verbosity));
}
/**
* @param string $msg
* @param int $verbosity
* @return string
*/
public static function colorize($msg, $verbosity)
{
if (self::$colorize) {
return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m";
} else {
return $msg;
}
}
/**
* @param array $colors
*/
public static function setColors(array $colors)
{
foreach ($colors as $k => $v) {
self::$colors[$k] = $v;
}
}
}
diff --git a/src/JAXL/core/jaxl_loop.php b/src/JAXL/core/jaxl_loop.php
index 1ac58d4..560abcb 100644
--- a/src/JAXL/core/jaxl_loop.php
+++ b/src/JAXL/core/jaxl_loop.php
@@ -1,168 +1,168 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLLoop
{
/**
* @var JAXLClock
*/
public static $clock = null;
private static $is_running = false;
private static $active_read_fds = 0;
private static $active_write_fds = 0;
private static $read_fds = array();
private static $read_cbs = array();
private static $write_fds = array();
private static $write_cbs = array();
private static $secs = 0;
private static $usecs = 30000;
private function __construct()
{
}
private function __clone()
{
}
public static function watch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
self::$read_fds[$fdid] = $fd;
self::$read_cbs[$fdid] = $opts['read'];
++self::$active_read_fds;
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
self::$write_fds[$fdid] = $fd;
self::$write_cbs[$fdid] = $opts['write'];
++self::$active_write_fds;
}
- _debug("Watch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
+ JAXLLogger::debug("Watch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function unwatch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
if (isset(self::$read_fds[$fdid])) {
unset(self::$read_fds[$fdid]);
unset(self::$read_cbs[$fdid]);
--self::$active_read_fds;
}
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
if (isset(self::$write_fds[$fdid])) {
unset(self::$write_fds[$fdid]);
unset(self::$write_cbs[$fdid]);
--self::$active_write_fds;
}
}
- _debug("Unwatch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
+ JAXLLogger::debug("Unwatch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function run()
{
if (!self::$is_running) {
self::$is_running = true;
self::$clock = new JAXLClock();
while ((self::$active_read_fds + self::$active_write_fds) > 0) {
self::select();
}
- _debug("no more active fd's to select");
+ JAXLLogger::debug("no more active fd's to select");
self::$is_running = false;
}
}
public static function select()
{
$read = self::$read_fds;
$write = self::$write_fds;
$except = null;
$changed = @stream_select($read, $write, $except, self::$secs, self::$usecs);
if ($changed === false) {
- _error("error in the event loop, shutting down...");
+ JAXLLogger::error("error in the event loop, shutting down...");
/*foreach (self::$read_fds as $fd) {
if (is_resource($fd)) {
print_r(stream_get_meta_data($fd));
}
}*/
exit;
} elseif ($changed > 0) {
// read callback
foreach ($read as $r) {
$fdid = array_search($r, self::$read_fds);
if (isset(self::$read_fds[$fdid])) {
call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]);
}
}
// write callback
foreach ($write as $w) {
$fdid = array_search($w, self::$write_fds);
if (isset(self::$write_fds[$fdid])) {
call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]);
}
}
self::$clock->tick();
} elseif ($changed === 0) {
- //_debug("nothing changed while selecting for read");
+ //JAXLLogger::debug("nothing changed while selecting for read");
self::$clock->tick((self::$secs * pow(10, 6)) + self::$usecs);
}
}
}
diff --git a/src/JAXL/core/jaxl_pipe.php b/src/JAXL/core/jaxl_pipe.php
index 81641bb..fbc8d0d 100644
--- a/src/JAXL/core/jaxl_pipe.php
+++ b/src/JAXL/core/jaxl_pipe.php
@@ -1,140 +1,140 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* bidirectional communication pipes for processes
*
* This is how this will be (when complete):
* $pipe = new JAXLPipe() will return an array of size 2
* $pipe[0] represents the read end of the pipe
* $pipe[1] represents the write end of the pipe
*
* Proposed functionality might even change (currently consider this as experimental)
*
* @author abhinavsingh
*
*/
class JAXLPipe
{
protected $perm = 0600;
/** @var callable */
protected $recv_cb = null;
protected $fd = null;
/** @var JAXLSocketClient */
protected $client = null;
/** @var string */
public $name = null;
/** @var string */
private $pipes_folder = null;
/**
* @param string $name
* @param callable $read_cb TODO: Currently not used
*/
public function __construct($name, $read_cb = null)
{
// TODO: see JAXL->cfg['priv_dir']
$this->pipes_folder = getcwd().'/.jaxl/pipes';
if (!is_dir($this->pipes_folder)) {
mkdir($this->pipes_folder, 0777, true);
}
$this->ev = new JAXLEvent();
$this->name = $name;
// TODO: If someone's need the read callback and extends the JAXLPipe
// to obtain it, one can't because this property is private.
$this->read_cb = $read_cb;
$pipe_path = $this->get_pipe_file_path();
if (!file_exists($pipe_path)) {
posix_mkfifo($pipe_path, $this->perm);
$this->fd = fopen($pipe_path, 'r+');
if (!$this->fd) {
- _error("unable to open pipe");
+ JAXLLogger::error("unable to open pipe");
} else {
- _debug("pipe opened using path $pipe_path");
- _notice("Usage: $ echo 'Hello World!' > $pipe_path");
+ JAXLLogger::debug("pipe opened using path $pipe_path");
+ JAXLLogger::notice("Usage: $ echo 'Hello World!' > $pipe_path");
$this->client = new JAXLSocketClient();
$this->client->connect($this->fd);
$this->client->set_callback(array(&$this, 'on_data'));
}
} else {
- _error("pipe with name $name already exists");
+ JAXLLogger::error("pipe with name $name already exists");
}
}
public function __destruct()
{
if (is_resource($this->fd)) {
fclose($this->fd);
}
if (file_exists($this->get_pipe_file_path())) {
unlink($this->get_pipe_file_path());
}
- _debug("unlinking pipe file");
+ JAXLLogger::debug("unlinking pipe file");
}
/**
* @return string
*/
public function get_pipe_file_path()
{
return $this->pipes_folder.'/jaxl_'.$this->name.'.pipe';
}
/**
* @param callable $recv_cb
*/
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function on_data($data)
{
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $data);
}
}
}
diff --git a/src/JAXL/core/jaxl_sock5.php b/src/JAXL/core/jaxl_sock5.php
index b63670e..3ba8709 100644
--- a/src/JAXL/core/jaxl_sock5.php
+++ b/src/JAXL/core/jaxl_sock5.php
@@ -1,140 +1,140 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class JAXLSock5
{
/** @var JAXLSocketClient */
private $client = null;
/** @var string */
protected $transport = null;
/** @var string */
protected $ip = null;
/** @var string|int */
protected $port = null;
/**
* @param string $transport
*/
public function __construct($transport = 'tcp')
{
$this->transport = $transport;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function __destruct()
{
}
/**
* @param string $ip
* @param int $port
* @return bool
*/
public function connect($ip, $port = 1080)
{
$this->ip = $ip;
$this->port = $port;
$sock_path = $this->sock_path();
if ($this->client->connect($sock_path)) {
- _debug("established connection to $sock_path");
+ JAXLLogger::debug("established connection to $sock_path");
return true;
} else {
- _error("unable to connect $sock_path");
+ JAXLLogger::error("unable to connect $sock_path");
return false;
}
}
//
// Three phases of SOCK5
//
// Negotiation pkt consists of 3 part:
// 0x05 => Sock protocol version
// 0x01 => Number of method identifier octet
//
// Following auth methods are defined:
// 0x00 => No authentication required
// 0x01 => GSSAPI
// 0x02 => USERNAME/PASSWORD
// 0x03 to 0x7F => IANA ASSIGNED
// 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS
// 0xFF => NO ACCEPTABLE METHODS
public function negotiate()
{
$pkt = pack("C3", 0x05, 0x01, 0x00);
$this->client->send($pkt);
// enter sub-negotiation state
}
public function relay_request()
{
// enter wait for reply state
}
public function send_data()
{
}
//
// Socket client callback
//
public function on_response($raw)
{
- _debug($raw);
+ JAXLLogger::debug($raw);
}
//
// Private
//
protected function sock_path()
{
return $this->transport.'://'.$this->ip.':'.$this->port;
}
}
diff --git a/src/JAXL/core/jaxl_socket_client.php b/src/JAXL/core/jaxl_socket_client.php
index f36bee9..d77b390 100644
--- a/src/JAXL/core/jaxl_socket_client.php
+++ b/src/JAXL/core/jaxl_socket_client.php
@@ -1,263 +1,263 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLSocketClient
{
private $host = null;
private $port = null;
private $transport = null;
/** @var resource */
private $stream_context = null;
private $blocking = false;
public $fd = null;
public $errno = null;
public $errstr = null;
private $timeout = 10;
private $ibuffer = "";
private $obuffer = "";
private $compressed = false;
private $recv_bytes = 0;
private $send_bytes = 0;
/** @var callable */
private $recv_cb = null;
private $recv_chunk_size = 1024;
private $writing = false;
/**
* @param resource $stream_context Resource created with stream_context_create().
*/
public function __construct($stream_context = null)
{
$this->stream_context = $stream_context;
}
public function __destruct()
{
- //_debug("cleaning up xmpp socket...");
+ //JAXLLogger::debug("cleaning up xmpp socket...");
$this->disconnect();
}
/**
* Emit on on_read_ready.
*
* @param callable $recv_cb
*/
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
/**
* @param string | resource $socket_path
*/
public function connect($socket_path)
{
if (gettype($socket_path) == "string") {
$path_parts = explode(":", $socket_path);
$this->transport = $path_parts[0];
$this->host = substr($path_parts[1], 2, strlen($path_parts[1]));
if (count($path_parts) == 3) {
$this->port = $path_parts[2];
}
- _info("trying ".$socket_path);
+ JAXLLogger::info("trying ".$socket_path);
if ($this->stream_context) {
$this->fd = @stream_socket_client(
$socket_path,
$this->errno,
$this->errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
$this->stream_context
);
} else {
$this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout);
}
} elseif (is_resource($socket_path)) {
$this->fd = &$socket_path;
} else {
// Some error occurred.
}
if ($this->fd) {
- _debug("connected to ".$socket_path."");
+ JAXLLogger::debug("connected to ".$socket_path."");
stream_set_blocking($this->fd, $this->blocking);
// watch descriptor for read/write events
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_read_ready')
));
return true;
} else {
- _error(sprintf(
+ JAXLLogger::error(sprintf(
"unable to connect %s with error no: %s, error str: %s",
is_null($socket_path) ? 'NULL' : $socket_path,
is_null($this->errno) ? 'NULL' : $this->errno,
is_null($this->errstr) ? 'NULL' : $this->errstr
));
$this->disconnect();
return false;
}
}
public function disconnect()
{
JAXLLoop::unwatch($this->fd, array(
'read' => true,
'write' => true
));
if (is_resource($this->fd)) {
fclose($this->fd);
}
$this->fd = null;
}
public function compress()
{
$this->compressed = true;
//stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ);
//stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE);
}
public function crypt()
{
// set blocking (since tls negotiation fails if stream is non-blocking)
stream_set_blocking($this->fd, true);
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
}
}
}
// switch back to non-blocking
stream_set_blocking($this->fd, false);
return $ret;
}
/**
* @param string $data
*/
public function send($data)
{
$this->obuffer .= $data;
// add watch for write events
if ($this->writing) {
return;
}
JAXLLoop::watch($this->fd, array(
'write' => array(&$this, 'on_write_ready')
));
$this->writing = true;
}
public function on_read_ready($fd)
{
- //_debug("on read ready called");
+ //JAXLLogger::debug("on read ready called");
$raw = @fread($fd, $this->recv_chunk_size);
$bytes = strlen($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($fd);
if ($meta['eof'] === true) {
- _warning("socket eof, disconnecting");
+ JAXLLogger::warning("socket eof, disconnecting");
JAXLLoop::unwatch($fd, array(
'read' => true
));
$this->disconnect();
return;
}
}
$this->recv_bytes += $bytes;
$total = $this->ibuffer.$raw;
$this->ibuffer = "";
- _debug("read ".$bytes."/".$this->recv_bytes." of data");
+ JAXLLogger::debug("read ".$bytes."/".$this->recv_bytes." of data");
if ($bytes > 0) {
- _debug($raw);
+ JAXLLogger::debug($raw);
}
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $raw);
}
}
public function on_write_ready($fd)
{
- //_debug("on write ready called");
+ //JAXLLogger::debug("on write ready called");
$total = strlen($this->obuffer);
$bytes = @fwrite($fd, $this->obuffer);
$this->send_bytes += $bytes;
- _debug("sent ".$bytes."/".$this->send_bytes." of data");
- _debug(substr($this->obuffer, 0, $bytes));
+ JAXLLogger::debug("sent ".$bytes."/".$this->send_bytes." of data");
+ JAXLLogger::debug(substr($this->obuffer, 0, $bytes));
$this->obuffer = substr($this->obuffer, $bytes, $total-$bytes);
// unwatch for write if obuffer is empty
if (strlen($this->obuffer) === 0) {
JAXLLoop::unwatch($fd, array(
'write' => true
));
$this->writing = false;
}
- //_debug("current obuffer size: ".strlen($this->obuffer)."");
+ //JAXLLogger::debug("current obuffer size: ".strlen($this->obuffer)."");
}
}
diff --git a/src/JAXL/core/jaxl_socket_server.php b/src/JAXL/core/jaxl_socket_server.php
index c686f8b..0274815 100644
--- a/src/JAXL/core/jaxl_socket_server.php
+++ b/src/JAXL/core/jaxl_socket_server.php
@@ -1,276 +1,276 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class JAXLSocketServer
{
public $fd = null;
private $clients = array();
private $recv_chunk_size = 1024;
private $send_chunk_size = 8092;
private $accept_cb = null;
private $request_cb = null;
private $blocking = false;
private $backlog = 200;
public function __construct($path, $accept_cb, $request_cb)
{
$this->accept_cb = $accept_cb;
$this->request_cb = $request_cb;
$ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog)));
$this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx);
if ($this->fd !== false) {
if (@stream_set_blocking($this->fd, $this->blocking)) {
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_server_accept_ready')
));
- _info("socket ready to accept on path ".$path);
+ JAXLLogger::info("socket ready to accept on path ".$path);
} else {
- _error("unable to set non block flag");
+ JAXLLogger::error("unable to set non block flag");
}
} else {
- _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr);
+ JAXLLogger::error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr);
}
}
public function __destruct()
{
- _info("shutting down socket server");
+ JAXLLogger::info("shutting down socket server");
}
public function read($client_id)
{
- //_debug("reactivating read on client sock");
+ //JAXLLogger::debug("reactivating read on client sock");
$this->add_read_cb($client_id);
}
/**
* @param int $client_id
* @param string $data
*/
public function send($client_id, $data)
{
$this->clients[$client_id]['obuffer'] .= $data;
$this->add_write_cb($client_id);
}
public function close($client_id)
{
$this->clients[$client_id]['close'] = true;
$this->add_write_cb($client_id);
}
public function on_server_accept_ready($server)
{
- //_debug("got server accept");
+ //JAXLLogger::debug("got server accept");
$client = @stream_socket_accept($server, 0, $addr);
if (!$client) {
- _error("unable to accept new client conn");
+ JAXLLogger::error("unable to accept new client conn");
return;
}
if (@stream_set_blocking($client, $this->blocking)) {
$client_id = (int) $client;
$this->clients[$client_id] = array(
'fd' => $client,
'ibuffer' => '',
'obuffer' => '',
'addr' => trim($addr),
'close' => false,
'closed' => false,
'reading' => false,
'writing' => false
);
- _debug("accepted connection from client#".$client_id.", addr:".$addr);
+ JAXLLogger::debug("accepted connection from client#".$client_id.", addr:".$addr);
// if accept callback is registered
// callback and let user land take further control of what to do
if ($this->accept_cb) {
call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']);
} else {
// if no accept callback is registered
// close the accepted connection
if (is_resource($client)) {
fclose($client);
}
$this->clients[$client_id]['closed'] = true;
unset($this->clients[$client_id]);
}
} else {
- _error("unable to set non block flag");
+ JAXLLogger::error("unable to set non block flag");
}
}
public function on_client_read_ready($client)
{
// deactive socket for read
$client_id = (int) $client;
- //_debug("client#$client_id is read ready");
+ //JAXLLogger::debug("client#$client_id is read ready");
$this->del_read_cb($client_id);
$raw = fread($client, $this->recv_chunk_size);
$bytes = strlen($raw);
- _debug("recv $bytes bytes from client#$client_id");
- //_debug($raw);
+ JAXLLogger::debug("recv $bytes bytes from client#$client_id");
+ //JAXLLogger::debug($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($client);
if ($meta['eof'] === true) {
- _debug("socket eof client#".$client_id.", closing");
+ JAXLLogger::debug("socket eof client#".$client_id.", closing");
$this->del_read_cb($client_id);
if (is_resource($client)) {
fclose($client);
}
unset($this->clients[$client_id]);
return;
}
}
$total = $this->clients[$client_id]['ibuffer'] . $raw;
if ($this->request_cb) {
call_user_func($this->request_cb, $client_id, $total);
}
$this->clients[$client_id]['ibuffer'] = '';
}
public function on_client_write_ready($client)
{
$client_id = (int) $client;
- _debug("client#$client_id is write ready");
+ JAXLLogger::debug("client#$client_id is write ready");
try {
// send in chunks
$total = $this->clients[$client_id]['obuffer'];
$written = @fwrite($client, substr($total, 0, $this->send_chunk_size));
if ($written === false) {
// fwrite failed
- _warning("====> fwrite failed");
+ JAXLLogger::warning("====> fwrite failed");
$this->clients[$client_id]['obuffer'] = $total;
} elseif ($written == strlen($total) || $written == $this->send_chunk_size) {
// full chunk written
- //_debug("full chunk written");
+ //JAXLLogger::debug("full chunk written");
$this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size);
} else {
// partial chunk written
- //_debug("partial chunk $written written");
+ //JAXLLogger::debug("partial chunk $written written");
$this->clients[$client_id]['obuffer'] = substr($total, $written);
}
// if no more stuff to write, remove write handler
if (strlen($this->clients[$client_id]['obuffer']) === 0) {
$this->del_write_cb($client_id);
// if scheduled for close and not closed do it and clean up
if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) {
if (is_resource($client)) {
fclose($client);
}
$this->clients[$client_id]['closed'] = true;
unset($this->clients[$client_id]);
- _debug("closed client#".$client_id);
+ JAXLLogger::debug("closed client#".$client_id);
}
}
} catch (JAXLException $e) {
- _debug("====> got fwrite exception");
+ JAXLLogger::debug("====> got fwrite exception");
}
}
//
// client sock event register utils
//
protected function add_read_cb($client_id)
{
if ($this->clients[$client_id]['reading']) {
return;
}
JAXLLoop::watch($this->clients[$client_id]['fd'], array(
'read' => array(&$this, 'on_client_read_ready')
));
$this->clients[$client_id]['reading'] = true;
}
protected function add_write_cb($client_id)
{
if ($this->clients[$client_id]['writing']) {
return;
}
JAXLLoop::watch($this->clients[$client_id]['fd'], array(
'write' => array(&$this, 'on_client_write_ready')
));
$this->clients[$client_id]['writing'] = true;
}
protected function del_read_cb($client_id)
{
if (!$this->clients[$client_id]['reading']) {
return;
}
JAXLLoop::unwatch($this->clients[$client_id]['fd'], array(
'read' => true
));
$this->clients[$client_id]['reading'] = false;
}
protected function del_write_cb($client_id)
{
if (!$this->clients[$client_id]['writing']) {
return;
}
JAXLLoop::unwatch($this->clients[$client_id]['fd'], array(
'write' => true
));
$this->clients[$client_id]['writing'] = false;
}
}
diff --git a/src/JAXL/core/jaxl_xml_stream.php b/src/JAXL/core/jaxl_xml_stream.php
index f0df146..fe2dcd6 100644
--- a/src/JAXL/core/jaxl_xml_stream.php
+++ b/src/JAXL/core/jaxl_xml_stream.php
@@ -1,198 +1,198 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLXmlStream
{
private $delimiter = '\\';
private $ns;
private $parser;
private $stanza;
private $depth = -1;
private $start_cb;
private $stanza_cb;
private $end_cb;
public function __construct()
{
$this->init_parser();
}
private function init_parser()
{
$this->depth = -1;
$this->parser = xml_parser_create_ns("UTF-8", $this->delimiter);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
xml_set_character_data_handler($this->parser, array(&$this, "handle_character"));
xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag"));
}
public function __destruct()
{
- //_debug("cleaning up xml parser...");
+ //JAXLLogger::debug("cleaning up xml parser...");
@xml_parser_free($this->parser);
}
public function reset_parser()
{
$this->parse_final(null);
@xml_parser_free($this->parser);
$this->parser = null;
$this->init_parser();
}
public function set_callback($start_cb, $end_cb, $stanza_cb)
{
$this->start_cb = $start_cb;
$this->end_cb = $end_cb;
$this->stanza_cb = $stanza_cb;
}
public function parse($str)
{
xml_parse($this->parser, $str, false);
}
public function parse_final($str)
{
xml_parse($this->parser, $str, true);
}
protected function handle_start_tag($parser, $name, array $attrs)
{
$name = $this->explode($name);
//echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL;
// replace ns with prefix
foreach ($attrs as $key => $v) {
$k = $this->explode($key);
// no ns specified
if ($k[0] == null) {
$attrs[$k[1]] = $v;
} elseif ($k[0] == XMPP::NS_XML) {
// xml ns
unset($attrs[$key]);
$attrs['xml:'.$k[1]] = $v;
} else {
- _error("==================> unhandled ns prefix on attribute");
+ JAXLLogger::error("==================> unhandled ns prefix on attribute");
// remove attribute else will cause error with bad stanza format
// report to developer if above error message is ever encountered
unset($attrs[$key]);
}
}
if ($this->depth <= 0) {
$this->depth = 0;
$this->ns = $name[1];
if ($this->start_cb) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
call_user_func($this->start_cb, $stanza);
}
} else {
if (!$this->stanza) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
$this->stanza = &$stanza;
} else {
$this->stanza->c($name[1], $name[0], $attrs);
}
}
++$this->depth;
}
protected function handle_end_tag($parser, $name)
{
$name = explode($this->delimiter, $name);
$name = count($name) == 1 ? array('', $name[0]) : $name;
//echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL;
if ($this->depth == 1) {
if ($this->end_cb) {
$stanza = new JAXLXml($name[1], $this->ns);
call_user_func($this->end_cb, $stanza);
}
} elseif ($this->depth > 1) {
if ($this->stanza) {
$this->stanza->up();
}
if ($this->depth == 2) {
if ($this->stanza_cb) {
call_user_func($this->stanza_cb, $this->stanza);
$this->stanza = null;
}
}
}
--$this->depth;
}
protected function handle_character($parser, $data)
{
//echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL;
if ($this->stanza) {
$this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), true);
}
}
private function implode($data)
{
return implode($this->delimiter, $data);
}
private function explode($data)
{
$data = explode($this->delimiter, $data);
$data = count($data) == 1 ? array(null, $data[0]) : $data;
return $data;
}
}
diff --git a/src/JAXL/http/http_client.php b/src/JAXL/http/http_client.php
index b98623e..f4c8055 100644
--- a/src/JAXL/http/http_client.php
+++ b/src/JAXL/http/http_client.php
@@ -1,155 +1,155 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class HTTPClient
{
/** @var string */
private $url = null;
private $parts = array();
private $headers = array();
private $data = null;
public $method = null;
/** @var JAXLSocketClient */
private $client = null;
/**
* @param string $url
* @param array $headers TODO: Currently not used.
* @param unknown $data TODO: Currently not used.
*/
public function __construct($url, array $headers = array(), $data = null)
{
$this->url = $url;
$this->headers = $headers;
$this->data = $data;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function start($method = 'GET')
{
$this->method = $method;
$this->parts = parse_url($this->url);
$transport = $this->transport();
$ip = $this->ip();
$port = $this->port();
$socket_path = $transport.'://'.$ip.':'.$port;
if ($this->client->connect($socket_path)) {
- _debug("connection to $this->url established");
+ JAXLLogger::debug("connection to $this->url established");
// send request data
$this->send_request();
// start main loop
JAXLLoop::run();
} else {
- _debug("unable to open $this->url");
+ JAXLLogger::debug("unable to open $this->url");
}
}
public function on_response($raw)
{
- _info("got http response");
+ JAXLLogger::info("got http response");
}
protected function send_request()
{
$this->client->send($this->line().HTTPServer::HTTP_CRLF);
$this->client->send($this->ua().HTTPServer::HTTP_CRLF);
$this->client->send($this->host().HTTPServer::HTTP_CRLF);
$this->client->send(HTTPServer::HTTP_CRLF);
}
//
// private methods on uri parts
//
private function line()
{
return $this->method.' '.$this->uri().' HTTP/1.1';
}
private function ua()
{
return 'User-Agent: jaxl_http_client/3.x';
}
private function host()
{
return 'Host: '.$this->parts['host'].':'.$this->port();
}
private function transport()
{
return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl');
}
private function ip()
{
return gethostbyname($this->parts['host']);
}
private function port()
{
return isset($this->parts['port']) ? $this->parts['port'] : 80;
}
private function uri()
{
$uri = $this->parts['path'];
if (isset($this->parts['query'])) {
$uri .= '?'.$this->parts['query'];
}
if (isset($this->parts['fragment'])) {
$uri .= '#'.$this->parts['fragment'];
}
return $uri;
}
}
diff --git a/src/JAXL/http/http_dispatcher.php b/src/JAXL/http/http_dispatcher.php
index 441a498..4c9ac83 100644
--- a/src/JAXL/http/http_dispatcher.php
+++ b/src/JAXL/http/http_dispatcher.php
@@ -1,88 +1,88 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class HTTPDispatcher
{
protected $rules = array();
public function __construct()
{
$this->rules = array();
}
public function add_rule($rule)
{
$s = count($rule);
if ($s > 4) {
- _debug("invalid rule");
+ JAXLLogger::debug("invalid rule");
return;
}
// fill up defaults
if ($s == 3) {
$rule[] = array();
} elseif ($s == 2) {
$rule[] = array('GET');
$rule[] = array();
} else {
- _debug("invalid rule");
+ JAXLLogger::debug("invalid rule");
return;
}
$this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]);
}
public function dispatch($request)
{
foreach ($this->rules as $rule) {
- //_debug("matching $request->path with pattern $rule->pattern");
+ //JAXLLogger::debug("matching $request->path with pattern $rule->pattern");
if (($matches = $rule->match($request->path, $request->method)) !== false) {
- _debug("matching rule found, dispatching");
+ JAXLLogger::debug("matching rule found, dispatching");
$params = array($request);
// TODO: a bad way to restrict on 'pk', fix me for generalization
if (isset($matches['pk'])) {
$params[] = $matches['pk'];
}
call_user_func_array($rule->cb, $params);
return true;
}
}
return false;
}
}
diff --git a/src/JAXL/http/http_multipart.php b/src/JAXL/http/http_multipart.php
index 869ca96..4e984da 100644
--- a/src/JAXL/http/http_multipart.php
+++ b/src/JAXL/http/http_multipart.php
@@ -1,169 +1,169 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class HTTPMultiPart extends JAXLFsm
{
public $boundary = null;
public $form_data = array();
public $index = -1;
public function handle_invalid_state($r)
{
- _error("got invalid event $r");
+ JAXLLogger::error("got invalid event $r");
}
public function __construct($boundary)
{
$this->boundary = $boundary;
parent::__construct('wait_for_boundary_start');
}
public function state()
{
return $this->state;
}
public function wait_for_boundary_start($event, $data)
{
if ($event == 'process') {
if ($data[0] == '--'.$this->boundary) {
$this->index += 1;
$this->form_data[$this->index] = array(
'meta' => array(),
'headers' => array(),
'body' => ''
);
return array('wait_for_content_disposition', true);
} else {
- _warning("invalid boundary start $data[0] while expecting $this->boundary");
+ JAXLLogger::warning("invalid boundary start $data[0] while expecting $this->boundary");
return array('wait_for_boundary_start', false);
}
} else {
- _warning("invalid $event rcvd");
+ JAXLLogger::warning("invalid $event rcvd");
return array('wait_for_boundary_start', false);
}
}
public function wait_for_content_disposition($event, $data)
{
if ($event == 'process') {
$disposition = explode(":", $data[0]);
if (strtolower(trim($disposition[0])) == 'content-disposition') {
$this->form_data[$this->index]['headers'][$disposition[0]] = trim($disposition[1]);
$meta = explode(";", $disposition[1]);
if (trim(array_shift($meta)) == 'form-data') {
foreach ($meta as $k) {
list($k, $v) = explode("=", $k);
$this->form_data[$this->index]['meta'][$k] = $v;
}
return array('wait_for_content_type', true);
} else {
- _warning("first part of meta is not form-data");
+ JAXLLogger::warning("first part of meta is not form-data");
return array('wait_for_content_disposition', false);
}
} else {
- _warning("not a valid content-disposition line");
+ JAXLLogger::warning("not a valid content-disposition line");
return array('wait_for_content_disposition', false);
}
} else {
- _warning("invalid $event rcvd");
+ JAXLLogger::warning("invalid $event rcvd");
return array('wait_for_content_disposition', false);
}
}
public function wait_for_content_type($event, $data)
{
if ($event == 'process') {
$type = explode(":", $data[0]);
if (strtolower(trim($type[0])) == 'content-type') {
$this->form_data[$this->index]['headers'][$type[0]] = trim($type[1]);
$this->form_data[$this->index]['meta']['type'] = $type[1];
return array('wait_for_content_body', true);
} else {
- _debug("not a valid content-type line");
+ JAXLLogger::debug("not a valid content-type line");
return array('wait_for_content_type', false);
}
} else {
- _warning("invalid $event rcvd");
+ JAXLLogger::warning("invalid $event rcvd");
return array('wait_for_content_type', false);
}
}
public function wait_for_content_body($event, $data)
{
if ($event == 'process') {
if ($data[0] == '--'.$this->boundary) {
- _debug("start of new multipart/form-data detected");
+ JAXLLogger::debug("start of new multipart/form-data detected");
return array('wait_for_content_disposition', true);
} elseif ($data[0] == '--'.$this->boundary.'--') {
- _debug("end of multipart form data detected");
+ JAXLLogger::debug("end of multipart form data detected");
return array('wait_for_empty_line', true);
} else {
$this->form_data[$this->index]['body'] .= $data[0];
return array('wait_for_content_body', true);
}
} else {
- _warning("invalid $event rcvd");
+ JAXLLogger::warning("invalid $event rcvd");
return array('wait_for_content_body', false);
}
}
public function wait_for_empty_line($event, $data)
{
if ($event == 'process') {
if ($data[0] == '') {
return array('done', true);
} else {
- _warning("invalid empty line $data[0] received");
+ JAXLLogger::warning("invalid empty line $data[0] received");
return array('wait_for_empty_line', false);
}
} else {
- _warning("got $event in done state with data $data[0]");
+ JAXLLogger::warning("got $event in done state with data $data[0]");
return array('wait_for_empty_line', false);
}
}
public function done($event, $data)
{
- _warning("got unhandled event $event with data $data[0]");
+ JAXLLogger::warning("got unhandled event $event with data $data[0]");
return array('done', false);
}
}
diff --git a/src/JAXL/http/http_request.php b/src/JAXL/http/http_request.php
index aaa719d..7f9cacf 100644
--- a/src/JAXL/http/http_request.php
+++ b/src/JAXL/http/http_request.php
@@ -1,509 +1,509 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
//
// These methods are available only once
// $request FSM has reached 'headers_received' state
//
// following shortcuts are available
// on received $request object:
//
// $request->{status_code_name}($headers, $body)
// $request->{status_code_name}($body, $headers)
//
// $request->{status_code_name}($headers)
// $request->{status_code_name}($body)
//
// following specific methods are also available:
//
// $request->send_line($code)
// $request->send_header($key, $value)
// $request->send_headers($headers)
// $request->send_message($string)
//
// all the above methods can also be directly performed using:
//
// $request->send_response($code, $headers = array(), $body = null)
//
// Note: All the send_* methods do not manage connection close/keep-alive logic,
// it is upto you to do that, by default connection will usually be dropped
// on client disconnect if not handled by you.
//
class HTTPRequest extends JAXLFsm
{
// peer identifier
public $sock = null;
public $ip = null;
public $port = null;
// request line
public $version = null;
public $method = null;
public $resource = null;
public $path = null;
public $query = array();
// headers and body
public $headers = array();
public $body = null;
public $recvd_body_len = 0;
// is true if 'Expect: 100-Continue'
// request header has been seen
public $expect = false;
// set if there is Content-Type: multipart/form-data; boundary=...
// header already seen
public $multipart = null;
// callback for send/read/close actions on accepted sock
private $send_cb = null;
private $read_cb = null;
private $close_cb = null;
private $shortcuts = array(
'ok' => 200, // 2xx
'redirect' => 302, 'not_modified' => 304, // 3xx
'not_found' => 404, 'bad_request' => 400, // 4xx
'internal_error' => 500, // 5xx
'recv_body' => true, 'close' => true // others
);
public function __construct($sock, $addr)
{
$this->sock = $sock;
$addr = explode(":", $addr);
$this->ip = $addr[0];
if (count($addr) == 2) {
$this->port = $addr[1];
}
parent::__construct("setup");
}
public function __destruct()
{
- _debug("http request going down in ".$this->state." state");
+ JAXLLogger::debug("http request going down in ".$this->state." state");
}
public function state()
{
return $this->state;
}
//
// abstract method implementation
//
public function handle_invalid_state($r)
{
- _debug("handle invalid state called with");
+ JAXLLogger::debug("handle invalid state called with");
var_dump($r);
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case 'set_sock_cb':
$this->send_cb = $args[0];
$this->read_cb = $args[1];
$this->close_cb = $args[2];
return 'wait_for_request_line';
break;
default:
- _warning("uncatched $event");
+ JAXLLogger::warning("uncatched $event");
return 'setup';
}
}
public function wait_for_request_line($event, $args)
{
switch ($event) {
case 'line':
$this->line($args[0], $args[1], $args[2]);
return 'wait_for_headers';
break;
default:
- _warning("uncatched $event");
+ JAXLLogger::warning("uncatched $event");
return 'wait_for_request_line';
}
}
public function wait_for_headers($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'maybe_headers_received';
default:
- _warning("uncatched $event");
+ JAXLLogger::warning("uncatched $event");
return 'wait_for_headers';
}
}
public function maybe_headers_received($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'headers_received';
break;
case 'body':
return $this->wait_for_body($event, $args);
break;
default:
- _warning("uncatched $event");
+ JAXLLogger::warning("uncatched $event");
return 'maybe_headers_received';
}
}
public function wait_for_body($event, $args)
{
switch ($event) {
case 'body':
$content_length = $this->headers['Content-Length'];
$rcvd = $args[0];
$rcvd_len = strlen($rcvd);
$this->recvd_body_len += $rcvd_len;
if ($this->body === null) {
$this->body = $rcvd;
} else {
$this->body .= $rcvd;
}
if ($this->multipart) {
// boundary start, content_disposition, form data, boundary start, ....., boundary end
// these define various states of a multipart/form-data
$form_data = explode(HTTPServer::HTTP_CRLF, $rcvd);
foreach ($form_data as $data) {
- //_debug("passing $data to multipart fsm");
+ //JAXLLogger::debug("passing $data to multipart fsm");
if (!$this->multipart->process($data)) {
- _debug("multipart fsm returned false");
+ JAXLLogger::debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
}
}
if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') {
- _debug("rcvd body len: $this->recvd_body_len/$content_length");
+ JAXLLogger::debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
- _debug("all data received, switching state for dispatch");
+ JAXLLogger::debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'set_header':
$content_length = $this->headers['Content-Length'];
$body = implode(":", $args);
$rcvd_len = strlen($body);
$this->recvd_body_len += $rcvd_len;
if (!$this->multipart->process($body)) {
- _debug("multipart fsm returned false");
+ JAXLLogger::debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
- _debug("rcvd body len: $this->recvd_body_len/$content_length");
+ JAXLLogger::debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
- _debug("all data received, switching state for dispatch");
+ JAXLLogger::debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'empty_line':
$content_length = $this->headers['Content-Length'];
if (!$this->multipart->process('')) {
- _debug("multipart fsm returned false");
+ JAXLLogger::debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
- _debug("rcvd body len: $this->recvd_body_len/$content_length");
+ JAXLLogger::debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
- _debug("all data received, switching state for dispatch");
+ JAXLLogger::debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
default:
- _warning("uncatched $event");
+ JAXLLogger::warning("uncatched $event");
return 'wait_for_body';
}
}
// headers and may be body received
public function headers_received($event, $args)
{
switch ($event) {
case 'empty_line':
return 'headers_received';
break;
default:
if (substr($event, 0, 5) == 'send_') {
$protected = '_'.$event;
if (method_exists($this, $protected)) {
call_user_func_array(array(&$this, $protected), $args);
return 'headers_received';
} else {
- _debug("non-existant method $event called");
+ JAXLLogger::debug("non-existant method $event called");
return 'headers_received';
}
} elseif (isset($this->shortcuts[$event])) {
return $this->handle_shortcut($event, $args);
} else {
- _warning("uncatched $event ".$args[0]);
+ JAXLLogger::warning("uncatched $event ".$args[0]);
return 'headers_received';
}
}
}
public function closed($event, $args)
{
- _warning("uncatched $event");
+ JAXLLogger::warning("uncatched $event");
}
// sets input headers
// called internally for every header received
protected function set_header($k, $v)
{
$k = trim($k);
$v = ltrim($v);
// is expect header?
if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') {
$this->expect = true;
}
// is multipart form data?
if (strtolower($k) == 'content-type') {
$ctype = explode(';', $v);
if (count($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') {
$boundary = explode('=', trim($ctype[1]));
if (strtolower(trim($boundary[0])) == 'boundary') {
- _debug("multipart with boundary $boundary[1] detected");
+ JAXLLogger::debug("multipart with boundary $boundary[1] detected");
$this->multipart = new HTTPMultiPart(ltrim($boundary[1]));
}
}
}
$this->headers[trim($k)] = trim($v);
}
// shortcut handler
protected function handle_shortcut($event, $args)
{
- _debug("executing shortcut '$event'");
+ JAXLLogger::debug("executing shortcut '$event'");
switch ($event) {
// http status code shortcuts
case 'ok':
case 'redirect':
case 'not_modified':
case 'bad_request':
case 'not_found':
case 'internal_error':
list($headers, $body) = $this->parse_shortcut_args($args);
$code = $this->shortcuts[$event];
$this->send_response($code, $headers, $body);
$this->close();
return 'closed';
break;
// others
case 'recv_body':
// send expect header if required
if ($this->expect) {
$this->expect = false;
$this->send_line(100);
}
// read data
$this->read();
return 'wait_for_body';
break;
case 'close':
$this->close();
return 'closed';
break;
}
}
private function parse_shortcut_args($args)
{
if (count($args) == 0) {
$body = null;
$headers = array();
}
if (count($args) == 1) {
// http headers or body only received
if (is_array($args[0])) {
// http headers only
$headers = $args[0];
$body = null;
} else {
// body only
$body = $args[0];
$headers = array();
}
} elseif (count($args) == 2) {
// body and http headers both received
if (is_array($args[0])) {
// header first
$body = $args[1];
$headers = $args[0];
} else {
// body first
$body = $args[0];
$headers = $args[1];
}
}
return array($headers, $body);
}
//
// send methods
// available only on 'headers_received' state
//
protected function send_line($code)
{
$raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTPServer::HTTP_CRLF;
$this->send($raw);
}
protected function send_header($k, $v)
{
$raw = $k.': '.$v.HTTPServer::HTTP_CRLF;
$this->send($raw);
}
protected function send_headers($code, $headers)
{
foreach ($headers as $k => $v) {
$this->send_header($k, $v);
}
}
protected function send_body($body)
{
$this->send($body);
}
protected function send_response($code, array $headers = array(), $body = null)
{
// send out response line
$this->send_line($code);
// set content length of body exists and is not already set
if ($body && !isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($body);
}
// send out headers
$this->send_headers($code, $headers);
// send body
// prefixed with an empty line
- _debug("sending out HTTP_CRLF prefixed body");
+ JAXLLogger::debug("sending out HTTP_CRLF prefixed body");
if ($body) {
$this->send_body(HTTPServer::HTTP_CRLF.$body);
}
}
//
// internal methods
//
// initializes status line elements
private function line($method, $resource, $version)
{
$this->method = $method;
$this->resource = $resource;
$resource = explode("?", $resource);
$this->path = $resource[0];
if (count($resource) == 2) {
$query = $resource[1];
$query = explode("&", $query);
foreach ($query as $q) {
$q = explode("=", $q);
if (count($q) == 1) {
$q[1] = "";
}
$this->query[$q[0]] = $q[1];
}
}
$this->version = $version;
}
private function send($raw)
{
call_user_func($this->send_cb, $this->sock, $raw);
}
private function read()
{
call_user_func($this->read_cb, $this->sock);
}
private function close()
{
call_user_func($this->close_cb, $this->sock);
}
}
diff --git a/src/JAXL/http/http_server.php b/src/JAXL/http/http_server.php
index cecd782..a50a3d1 100644
--- a/src/JAXL/http/http_server.php
+++ b/src/JAXL/http/http_server.php
@@ -1,199 +1,199 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class HTTPServer
{
// Carriage return and line feed.
const HTTP_CRLF = "\r\n";
// 1xx informational
const HTTP_100 = 'Continue';
const HTTP_101 = 'Switching Protocols';
// 2xx success
const HTTP_200 = 'OK';
// 3xx redirection
const HTTP_301 = 'Moved Permanently';
const HTTP_304 = 'Not Modified';
// 4xx client error
const HTTP_400 = 'Bad Request';
const HTTP_403 = 'Forbidden';
const HTTP_404 = 'Not Found';
const HTTP_405 = 'Method Not Allowed';
const HTTP_499 = 'Client Closed Request'; // Nginx
// 5xx server error
const HTTP_500 = 'Internal Server Error';
const HTTP_503 = 'Service Unavailable';
/** @var JAXLSocketServer */
private $server = null;
/** @var callable */
public $cb = null;
private $dispatcher = null;
private $requests = array();
public function __construct($port = 9699, $address = "127.0.0.1")
{
$path = 'tcp://'.$address.':'.$port;
$this->server = new JAXLSocketServer(
$path,
array(&$this, 'on_accept'),
array(&$this, 'on_request')
);
$this->dispatcher = new HTTPDispatcher();
}
public function __destruct()
{
$this->server = null;
}
public function dispatch($rules)
{
foreach ($rules as $rule) {
$this->dispatcher->add_rule($rule);
}
}
/**
* @param callable $cb
*/
public function start($cb = null)
{
$this->cb = $cb;
JAXLLoop::run();
}
public function on_accept($sock, $addr)
{
- _debug("on_accept for client#$sock, addr:$addr");
+ JAXLLogger::debug("on_accept for client#$sock, addr:$addr");
// initialize new request obj
$request = new HTTPRequest($sock, $addr);
// setup sock cb
$request->set_sock_cb(
array(&$this->server, 'send'),
array(&$this->server, 'read'),
array(&$this->server, 'close')
);
// cache request object
$this->requests[$sock] = &$request;
// reactive client for further read
$this->server->read($sock);
}
public function on_request($sock, $raw)
{
- _debug("on_request for client#$sock");
+ JAXLLogger::debug("on_request for client#$sock");
$request = $this->requests[$sock];
// 'wait_for_body' state is reached when ever
// application calls recv_body() method
// on received $request object
if ($request->state() == 'wait_for_body') {
$request->body($raw);
} else {
// break on crlf
$lines = explode(HTTP_CRLF, $raw);
// parse request line
if ($request->state() == 'wait_for_request_line') {
list($method, $resource, $version) = explode(" ", $lines[0]);
$request->line($method, $resource, $version);
unset($lines[0]);
- _info($request->ip." ".$request->method." ".$request->resource." ".$request->version);
+ JAXLLogger::info($request->ip." ".$request->method." ".$request->resource." ".$request->version);
}
// parse headers
foreach ($lines as $line) {
$line_parts = explode(":", $line);
if (count($line_parts) > 1) {
if (strlen($line_parts[0]) > 0) {
$k = $line_parts[0];
unset($line_parts[0]);
$v = implode(":", $line_parts);
$request->set_header($k, $v);
}
} elseif (strlen(trim($line_parts[0])) == 0) {
$request->empty_line();
} else {
// if exploded line array size is 1
// and there is something in $line_parts[0]
// must be request body
$request->body($line);
}
}
}
// if request has reached 'headers_received' state?
if ($request->state() == 'headers_received') {
// dispatch to any matching rule found
- _debug("delegating to dispatcher for further routing");
+ JAXLLogger::debug("delegating to dispatcher for further routing");
$dispatched = $this->dispatcher->dispatch($request);
// if no dispatch rule matched call generic callback
if (!$dispatched && $this->cb) {
- _debug("no dispatch rule matched, sending to generic callback");
+ JAXLLogger::debug("no dispatch rule matched, sending to generic callback");
call_user_func($this->cb, $request);
} elseif (!$dispatched) {
// elseif not dispatched and not generic callbacked
// send 404 not_found
// TODO: send 404 if no callback is registered for this request
- _debug("dropping request since no matching dispatch rule or generic callback was specified");
+ JAXLLogger::debug("dropping request since no matching dispatch rule or generic callback was specified");
$request->not_found('404 Not Found');
}
} else {
// if state is not 'headers_received'
// reactivate client socket for read event
$this->server->read($sock);
}
}
}
diff --git a/src/JAXL/jaxl.php b/src/JAXL/jaxl.php
index 6c035b4..304da09 100644
--- a/src/JAXL/jaxl.php
+++ b/src/JAXL/jaxl.php
@@ -1,858 +1,858 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$cfg_defaults = array(
'auth_type' => 'PLAIN',
'bosh_hold' => null,
'bosh_rid' => null,
'bosh_url' => null,
'bosh_wait' => null,
'domain' => null,
'force_tls' => false,
'host' => null,
'jid' => null,
'log_colorize' => $this->log_colorize,
'log_level' => $this->log_level,
'log_path' => JAXLLogger::$path,
'multi_client' => false,
'pass' => false,
'port' => null,
'priv_dir' => getcwd().'/.jaxl',
'protocol' => null,
'resource' => null,
'stream_context' => null,
'strict' => true
);
$this->cfg = array_merge($cfg_defaults, $config);
// setup logger
JAXLLogger::$path = $this->cfg['log_path'];
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
// env
if ($this->cfg['strict']) {
- _info("strict mode enabled, adding exception handlers. ' .
+ JAXLLogger::info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => false inside JAXL config to disable this");
JAXLException::addHandlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = ($this->cfg['jid'] !== null) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = $this->cfg['priv_dir'];
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
- _info("created pid file ".$this->get_pid_file_path());
+ JAXLLogger::info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
if (($this->cfg['host'] === null || $this->cfg['port'] === null) && $jid) {
// this dns lookup is blocking
- _info("dns srv lookup for ".$jid->domain);
+ JAXLLogger::info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
if ($this->cfg['host'] === null) {
$this->cfg['host'] = $host;
}
if ($this->cfg['port'] === null) {
$this->cfg['port'] = $port;
}
}
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
- _debug("including bosh xep");
+ JAXLLogger::debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
$transport = new JAXLSocketClient($this->cfg['stream_context']);
}
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
$this->cfg['pass'],
$this->cfg['resource'] !== null ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
$this->cfg['force_tls']
);
}
public function __destruct()
{
// delete pid file
- _info("cleaning up pid and unix sock files");
+ JAXLLogger::info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLSocketClient|XEP0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$classname = 'XEP'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if ($this->cfg['protocol'] !== null) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
- _info("Will try to restart in ".$retry_after." seconds");
+ JAXLLogger::info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
- _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
+ JAXLLogger::debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
- _debug("got sighup");
+ JAXLLogger::debug("got sighup");
break;
// interrupt program
case SIGINT:
- _debug("got sigint");
+ JAXLLogger::debug("got sigint");
break;
// software termination signal
case SIGTERM:
- _debug("got sigterm");
+ JAXLLogger::debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
- _debug("evaling raw string rcvd over unix sock: ".$_raw);
+ JAXLLogger::debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
- _debug("got unhandled sasl response, should never happen here");
+ JAXLLogger::debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
- _debug("not catched $event, should never happen here");
+ JAXLLogger::debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
- _debug("got unhandled sasl response, should never happen here");
+ JAXLLogger::debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
- _debug("not catched $event, should never happen here");
+ JAXLLogger::debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
$pref_auth = $this->cfg['auth_type'];
// check if preferred auth type exists in available mechanisms
if (isset($mechs[$pref_auth]) && $mechs[$pref_auth]) {
- _debug("pref_auth ".$pref_auth." exists");
+ JAXLLogger::debug("pref_auth ".$pref_auth." exists");
} else {
- _debug("pref_auth ".$pref_auth." doesn't exists");
- _error("preferred auth type not supported, trying $pref_auth");
+ JAXLLogger::debug("pref_auth ".$pref_auth." doesn't exists");
+ JAXLLogger::error("preferred auth type not supported, trying $pref_auth");
}
$this->send_auth_pkt(
$pref_auth,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
- //_debug("on stanza id callbackd");
+ //JAXLLogger::debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
- _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
+ JAXLLogger::warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
}
diff --git a/src/JAXL/xep/xep_0114.php b/src/JAXL/xep/xep_0114.php
index 14c0db7..219dc06 100644
--- a/src/JAXL/xep/xep_0114.php
+++ b/src/JAXL/xep/xep_0114.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class XEP0114 extends XMPPXep
{
const NS_JABBER_COMPONENT_ACCEPT = 'jabber:component:accept';
//
// abstract method
//
public function init()
{
return array(
'on_connect' => 'start_stream',
'on_stream_start' => 'start_handshake',
'on_handshake_stanza' => 'logged_in',
'on_error_stanza' => 'logged_out'
);
}
//
// event callbacks
//
public function start_stream()
{
$xml = sprintf(
'<stream:stream xmlns:stream="%s" to="%s" xmlns="%s">',
XMPP::NS_XMPP,
$this->jaxl->jid->to_string(),
self::NS_JABBER_COMPONENT_ACCEPT
);
$this->jaxl->send_raw($xml);
}
public function start_handshake($stanza)
{
- _debug("starting component handshake");
+ JAXLLogger::debug("starting component handshake");
$id = $stanza->id;
$hash = strtolower(sha1($id.$this->jaxl->pass));
$stanza = new JAXLXml('handshake', null, $hash);
$this->jaxl->send($stanza);
}
public function logged_in($stanza)
{
- _debug("component handshake complete");
+ JAXLLogger::debug("component handshake complete");
$this->jaxl->handle_auth_success();
return array("logged_in", 1);
}
public function logged_out($stanza)
{
if ($stanza->name == "error" && $stanza->ns == XMPP::NS_XMPP) {
$reason = $stanza->childrens[0]->name;
$this->jaxl->handle_auth_failure($reason);
$this->jaxl->send_end_stream();
return array("logged_out", 0);
} else {
- _debug("uncatched stanza received in logged_out");
+ JAXLLogger::debug("uncatched stanza received in logged_out");
}
}
}
diff --git a/src/JAXL/xep/xep_0206.php b/src/JAXL/xep/xep_0206.php
index a33150e..6a8eb4d 100644
--- a/src/JAXL/xep/xep_0206.php
+++ b/src/JAXL/xep/xep_0206.php
@@ -1,268 +1,268 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class XEP0206 extends XMPPXep
{
const NS_HTTP_BIND = 'http://jabber.org/protocol/httpbind';
const NS_BOSH = 'urn:xmpp:xbosh';
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
//
// event callbacks
//
/**
* @param JAXLXml|XMPPStanza|string $body
*/
public function send($body)
{
if (is_object($body)) {
$body = $body->to_string();
} else {
if (substr($body, 0, 15) == '<stream:stream ') {
$this->restarted = true;
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
'xmlns:xmpp' => self::NS_BOSH
));
$body = $body->to_string();
} elseif (substr($body, 0, 16) == '</stream:stream>') {
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
$body = $body->to_string();
} else {
$body = $this->wrap($body);
}
}
- _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
+ JAXLLogger::debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
- _debug("recving for $this->rid");
+ JAXLLogger::debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
- _debug("mrc=$mrc running=$running");
+ JAXLLogger::debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
- _debug("recvd for $this->rid ".$data);
+ JAXLLogger::debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
- _error("no ch found");
+ JAXLLogger::error("no ch found");
exit;
}
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.
self::NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
$this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
$this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
$this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
'xmlns:xmpp' => self::NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
if ($this->jaxl->cfg['jid'] !== null) {
$attrs['from'] = $this->jaxl->cfg['jid'];
}
$body = new JAXLXml('body', self::NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
$body = new JAXLXml('body', self::NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
- _debug("disconnecting");
+ JAXLLogger::debug("disconnecting");
}
}
diff --git a/src/JAXL/xmpp/xmpp_stream.php b/src/JAXL/xmpp/xmpp_stream.php
index 29b0f5a..1083a42 100644
--- a/src/JAXL/xmpp/xmpp_stream.php
+++ b/src/JAXL/xmpp/xmpp_stream.php
@@ -1,757 +1,764 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
* @var JAXLSocketClient|XEP0206
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
* @param JAXLSocketClient|XEP0206 $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
$jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
- //_debug("cleaning up xmpp stream...");
+ //JAXLLogger::debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
- _error("got invalid return value from state handler '".$this->state."', sending end stream...");
+ JAXLLogger::error(sprintf(
+ "got invalid return value from state handler '%s', sending end stream...",
+ $this->state
+ ));
$this->send_end_stream();
$this->state = "logged_out";
- _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers");
+ JAXLLogger::notice(sprintf(
+ "state handler '%s' returned %s, kindly report this to developers",
+ $this->state,
+ serialize($r)
+ ));
}
/**
* @param JAXLXml|XMPPStanza $stanza
*/
public function send($stanza)
{
$this->trans->send($stanza->to_string());
}
/**
* @param string $data
*/
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.XMPP::NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.XMPP::NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.XMPP::NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', XMPP::NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', XMPP::NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', XMPP::NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', XMPP::NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
- _debug("calculating response to challenge");
+ JAXLLogger::debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', XMPP::NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', XMPP::NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
- //_debug("stream started");
+ //JAXLLogger::debug("stream started");
return "wait_for_stream_features";
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', XMPP::NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', XMPP::NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', XMPP::NS_BIND) ? true : false;
$sess = $stanza->exists('session', XMPP::NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', XMPP::NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
- _debug("no catch");
+ JAXLLogger::debug("no catch");
}
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == XMPP::NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'compressed' && $stanza->ns == XMPP::NS_COMPRESSION_PROTOCOL) {
$this->xml->reset_parser();
$this->trans->compress();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
}
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_compression_result", 0);
break;
}
}
public function wait_for_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'failure' && $stanza->ns == XMPP::NS_SASL) {
$reason = $stanza->childrens[0]->name;
- //_debug("sasl failed with reason ".$reason."");
+ //JAXLLogger::debug("sasl failed with reason ".$reason."");
$this->handle_auth_failure($reason);
return "logged_out";
} elseif ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$this->send_challenge_response($challenge);
return "wait_for_sasl_response";
} elseif ($stanza->name == 'success' && $stanza->ns == XMPP::NS_SASL) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
- _debug("got unhandled sasl response");
+ JAXLLogger::debug("got unhandled sasl response");
}
return "wait_for_sasl_response";
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_sasl_response", 0);
break;
}
}
public function wait_for_bind_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// TODO: chk on id
if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result'
&& ($jid = $stanza->exists('bind', XMPP::NS_BIND)->exists('jid'))) {
$this->full_jid = new XMPPJid($jid->text);
$this->send_session_pkt();
return "wait_for_session_response";
} else {
// FIXME:
}
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_bind_response", 0);
break;
}
}
public function wait_for_session_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$this->handle_auth_success();
return "logged_in";
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_session_response", 0);
break;
}
}
public function logged_in($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// call abstract
if ($stanza->name == 'message') {
$this->handle_message($stanza);
} elseif ($stanza->name == 'presence') {
$this->handle_presence($stanza);
} elseif ($stanza->name == 'iq') {
$this->handle_iq($stanza);
} else {
$this->handle_other($event, $args);
}
return "logged_in";
break;
case "end_cb":
$this->send_end_stream();
return "logged_out";
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
default:
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_in", 0);
break;
}
}
public function logged_out($event, $args)
{
switch ($event) {
case "end_cb":
$this->trans->disconnect();
return "disconnected";
break;
case "end_stream":
return "disconnected";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
case "connect":
return $this->do_connect($args);
break;
default:
// exit for any other event in logged_out state
- _debug("uncatched $event");
+ JAXLLogger::debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_out", 0);
break;
}
}
}
|
jaxl/JAXL | 1fbd9e2fb24bb781892bfe3fb50c722887531117 | Change global function _colorize to JAXLLogger::cliLog | diff --git a/docs/users/logging.rst b/docs/users/logging.rst
index 6abc18b..068a9f1 100644
--- a/docs/users/logging.rst
+++ b/docs/users/logging.rst
@@ -1,30 +1,33 @@
Logging Interface
=================
``JAXLLogger`` provides all the logging facilities that we will ever require.
-When logging to ``STDOUT`` it also colorizes the log message depending upon its severity level.
-When logging to a file it can also do periodic log rotation.
+When logging to ``STDOUT`` it also colorizes the log message depending upon
+its severity level. When logging to a file it can also do periodic log
+rotation.
log levels
----------
* ERROR (red)
* WARNING (blue)
* NOTICE (yellow)
* INFO (green)
* DEBUG (white)
global logging methods
----------------------
+
Following global methods for logging are available:
* ``_error($msg)``
* ``_warning($msg)``
* ``_notice($msg)``
* ``_info($msg)``
* ``_debug($msg)``
-_colorize/2
+log/2
-----------
-All the above global logging methods internally use ``_colorize($msg, $verbosity)`` to output colored
-log message on the terminal.
+
+All the above global logging methods internally use ``log($msg, $verbosity)``
+to output colored log message on the terminal.
diff --git a/examples/echo_http_server.php b/examples/echo_http_server.php
index e91de77..f4ea632 100644
--- a/examples/echo_http_server.php
+++ b/examples/echo_http_server.php
@@ -1,59 +1,59 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// configure logger
JAXLLogger::$level = JAXLLogger::INFO;
// print usage notice and parse addr/port parameters if passed
-_colorize("Usage: $argv[0] port (default: 9699)", JAXLLogger::NOTICE);
+JAXLLogger::cliLog("Usage: $argv[0] port (default: 9699)", JAXLLogger::NOTICE);
$port = ($argc == 2 ? $argv[1] : 9699);
// initialize http server
$http = new HTTPServer($port);
// catch all incoming requests here
function on_request($request)
{
$body = json_encode($request);
$request->ok($body, array('Content-Type' => 'application/json'));
}
// start http server
$http->start('on_request');
diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php
index 824ea87..05d194a 100644
--- a/examples/http_rest_server.php
+++ b/examples/http_rest_server.php
@@ -1,127 +1,127 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// configure logger
JAXLLogger::$level = JAXLLogger::INFO;
// print usage notice and parse addr/port parameters if passed
-_colorize("Usage: $argv[0] port (default: 9699)", JAXLLogger::NOTICE);
+JAXLLogger::cliLog("Usage: $argv[0] port (default: 9699)", JAXLLogger::NOTICE);
$port = ($argc == 2 ? $argv[1] : 9699);
// initialize http server
$http = new HTTPServer($port);
// callback method for dispatch rule (see below)
function index($request)
{
$request->send_response(
200,
array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>'
);
$request->close();
}
// callback method for dispatch rule (see below)
function upload($request)
{
if ($request->method == 'GET') {
$request->ok(
array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" ' .
'action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" ' .
'value="upload"/></form></body></html>'
);
} elseif ($request->method == 'POST') {
if ($request->body === null && $request->expect) {
$request->recv_body();
} else {
// got upload body, save it
_info("file upload complete, got ".strlen($request->body)." bytes of data");
$upload_data = $request->multipart->form_data[0]['body'];
$request->ok(
$upload_data,
array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])
);
}
}
}
// add dispatch rules with callback method as first argument
$index = array('index', '^/$');
$upload = array('upload', '^/upload', array('GET', 'POST'));
// some REST CRUD style callback methods
// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules
function create_event($request)
{
_info("got event create request");
$request->close();
}
function read_event($request, $pk)
{
_info("got event read request for $pk");
$request->close();
}
function update_event($request, $pk)
{
_info("got event update request for $pk");
$request->close();
}
function delete_event($request, $pk)
{
_info("got event delete request for $pk");
$request->close();
}
$event_create = array('create_event', '^/event/create/$', array('PUT'));
$event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD'));
$event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST'));
$event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE'));
// prepare rule set
$rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete);
$http->dispatch($rules);
// start http server
$http->start();
diff --git a/src/JAXL/core/jaxl_logger.php b/src/JAXL/core/jaxl_logger.php
index 1a5acff..38d46b7 100644
--- a/src/JAXL/core/jaxl_logger.php
+++ b/src/JAXL/core/jaxl_logger.php
@@ -1,137 +1,137 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// generic global logging shortcuts for different level of verbosity
function _error($msg)
{
JAXLLogger::log($msg, JAXLLogger::ERROR);
}
function _warning($msg)
{
JAXLLogger::log($msg, JAXLLogger::WARNING);
}
function _notice($msg)
{
JAXLLogger::log($msg, JAXLLogger::NOTICE);
}
function _info($msg)
{
JAXLLogger::log($msg, JAXLLogger::INFO);
}
function _debug($msg)
{
JAXLLogger::log($msg, JAXLLogger::DEBUG);
}
-// generic global terminal output colorize method
-// finally sends colorized message to terminal using error_log/1
-// this method is mainly to escape $msg from file:line and time
-// prefix done by _debug, _error, ... methods
-function _colorize($msg, $verbosity)
-{
- error_log(JAXLLogger::colorize($msg, $verbosity));
-}
-
class JAXLLogger
{
// Log levels.
const ERROR = 1;
const WARNING = 2;
const NOTICE = 3;
const INFO = 4;
const DEBUG = 5;
public static $colorize = true;
public static $level = self::DEBUG;
public static $path = null;
public static $max_log_size = 1000;
protected static $colors = array(
self::ERROR => 31, // red
self::WARNING => 34, // blue
self::NOTICE => 33, // yellow
self::INFO => 32, // green
self::DEBUG => 37 // white
);
public static function log($msg, $verbosity = self::ERROR)
{
if ($verbosity <= self::$level) {
$bt = debug_backtrace();
array_shift($bt);
$callee = array_shift($bt);
$msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg;
-
+
$size = strlen($msg);
if ($size > self::$max_log_size) {
$msg = substr($msg, 0, self::$max_log_size) . ' ...';
}
-
+
if (isset(self::$path)) {
error_log($msg . PHP_EOL, 3, self::$path);
} else {
error_log(self::colorize($msg, $verbosity));
}
}
}
+ // Generic global terminal output colorize method.
+ // Finally sends colorized message to terminal using error_log/1
+ // this method is mainly to escape $msg from file:line and time
+ // prefix done by debug, error, ... methods.
+ public static function cliLog($msg, $verbosity)
+ {
+ error_log(self::colorize($msg, $verbosity));
+ }
+
/**
* @param string $msg
* @param int $verbosity
* @return string
*/
public static function colorize($msg, $verbosity)
{
if (self::$colorize) {
return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m";
} else {
return $msg;
}
}
/**
* @param array $colors
*/
public static function setColors(array $colors)
{
foreach ($colors as $k => $v) {
self::$colors[$k] = $v;
}
}
}
diff --git a/src/JAXL/jaxlctl.php b/src/JAXL/jaxlctl.php
index 82e649d..72e2160 100755
--- a/src/JAXL/jaxlctl.php
+++ b/src/JAXL/jaxlctl.php
@@ -1,180 +1,180 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// TODO: an abstract JAXLCtlCommand class
// with seperate class per command
// a mechanism to register new commands
class JAXLCtl
{
protected $ipc = null;
protected $buffer = '';
protected $buffer_cb = null;
protected $cli = null;
public $dots = "....... ";
protected $symbols = array();
public function __construct($command, $params)
{
global $exe;
if (method_exists($this, $command)) {
$r = call_user_func_array(array(&$this, $command), $params);
if (count($r) == 2) {
list($buffer_cb, $quit_cb) = $r;
$this->buffer_cb = $buffer_cb;
$this->cli = new JAXLCli(array(&$this, 'onTerminalInput'), $quit_cb);
$this->run();
} else {
- _colorize("oops! internal command error", JAXLLogger::ERROR);
+ JAXLLogger::cliLog("oops! internal command error", JAXLLogger::ERROR);
exit;
}
} else {
- _colorize("error: invalid command '$command' received", JAXLLogger::ERROR);
- _colorize("type '$exe help' for list of available commands", JAXLLogger::NOTICE);
+ JAXLLogger::cliLog("error: invalid command '$command' received", JAXLLogger::ERROR);
+ JAXLLogger::cliLog("type '$exe help' for list of available commands", JAXLLogger::NOTICE);
exit;
}
}
public function run()
{
JAXLCli::prompt();
JAXLLoop::run();
}
public function onTerminalInput($raw)
{
$raw = trim($raw);
$last = substr($raw, -1, 1);
if ($last == ";") {
// dispatch to buffer callback
call_user_func($this->buffer_cb, $this->buffer.$raw);
$this->buffer = '';
} elseif ($last == '\\') {
$this->buffer .= substr($raw, 0, -1);
echo $this->dots;
} else {
// buffer command
$this->buffer .= $raw."; ";
echo $this->dots;
}
}
public static function printHelp()
{
global $exe;
- _colorize("Usage: $exe command [options...]".PHP_EOL, JAXLLogger::INFO);
- _colorize("Commands:", JAXLLogger::NOTICE);
- _colorize(" help This help text", JAXLLogger::DEBUG);
- _colorize(" debug Attach a debug console to a running JAXL daemon", JAXLLogger::DEBUG);
- _colorize(" shell Open up Jaxl shell emulator", JAXLLogger::DEBUG);
+ JAXLLogger::cliLog("Usage: $exe command [options...]".PHP_EOL, JAXLLogger::INFO);
+ JAXLLogger::cliLog("Commands:", JAXLLogger::NOTICE);
+ JAXLLogger::cliLog(" help This help text", JAXLLogger::DEBUG);
+ JAXLLogger::cliLog(" debug Attach a debug console to a running JAXL daemon", JAXLLogger::DEBUG);
+ JAXLLogger::cliLog(" shell Open up Jaxl shell emulator", JAXLLogger::DEBUG);
echo PHP_EOL;
}
protected function help()
{
JAXLCtl::printHelp();
exit;
}
//
// shell command
//
protected function shell()
{
return array(array(&$this, 'onShellInput'), array(&$this, 'onShellQuit'));
}
private function eval_($raw, $symbols)
{
extract($symbols);
eval($raw);
$g = get_defined_vars();
unset($g['raw']);
unset($g['symbols']);
return $g;
}
public function onShellInput($raw)
{
$this->symbols = $this->eval_($raw, $this->symbols);
JAXLCli::prompt();
}
public function onShellQuit()
{
exit;
}
//
// debug command
//
protected function debug($sock_path)
{
$this->ipc = new JAXLSocketClient();
$this->ipc->set_callback(array(&$this, 'onDebugResponse'));
$this->ipc->connect('unix://'.$sock_path);
return array(array(&$this, 'onDebugInput'), array(&$this, 'onDebugQuit'));
}
public function onDebugResponse($raw)
{
$ret = unserialize($raw);
print_r($ret);
echo PHP_EOL;
JAXLCli::prompt();
}
public function onDebugInput($raw)
{
$this->ipc->send($this->buffer.$raw);
}
public function onDebugQuit()
{
$this->ipc->disconnect();
exit;
}
}
|
jaxl/JAXL | 63b355ee33179f1d29d1d1aceeec4128802f2b35 | Move handlers setup to JAXLException | diff --git a/src/JAXL/core/jaxl_exception.php b/src/JAXL/core/jaxl_exception.php
index d225f35..64ba648 100644
--- a/src/JAXL/core/jaxl_exception.php
+++ b/src/JAXL/core/jaxl_exception.php
@@ -1,93 +1,100 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* @author abhinavsingh
*/
class JAXLException extends Exception
{
public function __construct($message = null, $code = null, $file = null, $line = null)
{
_notice("got jaxl exception construct with $message, $code, $file, $line");
if ($code === null) {
parent::__construct($message);
} else {
parent::__construct($message, $code);
}
if ($file !== null) {
$this->file = $file;
}
if ($line !== null) {
$this->line = $line;
}
}
+ public static function addHandlers()
+ {
+ set_error_handler(array('JAXLException', 'error_handler'));
+ set_exception_handler(array('JAXLException', 'exception_handler'));
+ register_shutdown_function(array('JAXLException', 'shutdown_handler'));
+ }
+
public static function error_handler($errno, $error, $file, $line, $vars)
{
_debug("error handler called with $errno, $error, $file, $line");
if ($errno === 0 || ($errno & error_reporting()) === 0) {
return;
}
throw new JAXLException($error, $errno, $file, $line);
}
public static function exception_handler($e)
{
_debug("exception handler catched ".json_encode($e));
// TODO: Pretty print backtrace
//print_r(debug_backtrace());
}
public static function shutdown_handler()
{
try {
_debug("got shutdown handler");
if (null !== ($error = error_get_last())) {
throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']);
}
} catch (Exception $e) {
_debug("shutdown handler catched with exception ".json_encode($e));
}
}
}
diff --git a/src/JAXL/jaxl.php b/src/JAXL/jaxl.php
index beeac6f..6c035b4 100644
--- a/src/JAXL/jaxl.php
+++ b/src/JAXL/jaxl.php
@@ -1,779 +1,772 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$cfg_defaults = array(
'auth_type' => 'PLAIN',
'bosh_hold' => null,
'bosh_rid' => null,
'bosh_url' => null,
'bosh_wait' => null,
'domain' => null,
'force_tls' => false,
'host' => null,
'jid' => null,
'log_colorize' => $this->log_colorize,
'log_level' => $this->log_level,
'log_path' => JAXLLogger::$path,
'multi_client' => false,
'pass' => false,
'port' => null,
'priv_dir' => getcwd().'/.jaxl',
'protocol' => null,
'resource' => null,
'stream_context' => null,
'strict' => true
);
$this->cfg = array_merge($cfg_defaults, $config);
// setup logger
JAXLLogger::$path = $this->cfg['log_path'];
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
// env
if ($this->cfg['strict']) {
- $this->add_exception_handlers();
+ _info("strict mode enabled, adding exception handlers. ' .
+ 'Set 'strict' => false inside JAXL config to disable this");
+ JAXLException::addHandlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = ($this->cfg['jid'] !== null) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = $this->cfg['priv_dir'];
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
if (($this->cfg['host'] === null || $this->cfg['port'] === null) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
if ($this->cfg['host'] === null) {
$this->cfg['host'] = $host;
}
if ($this->cfg['port'] === null) {
$this->cfg['port'] = $port;
}
}
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
$transport = new JAXLSocketClient($this->cfg['stream_context']);
}
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
$this->cfg['pass'],
$this->cfg['resource'] !== null ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
$this->cfg['force_tls']
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
- public function add_exception_handlers()
- {
- _info("strict mode enabled, adding exception handlers. ' .
- 'Set 'strict' => false inside JAXL config to disable this");
- set_error_handler(array('JAXLException', 'error_handler'));
- set_exception_handler(array('JAXLException', 'exception_handler'));
- register_shutdown_function(array('JAXLException', 'shutdown_handler'));
- }
-
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLSocketClient|XEP0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$classname = 'XEP'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if ($this->cfg['protocol'] !== null) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
$pref_auth = $this->cfg['auth_type'];
// check if preferred auth type exists in available mechanisms
if (isset($mechs[$pref_auth]) && $mechs[$pref_auth]) {
_debug("pref_auth ".$pref_auth." exists");
} else {
_debug("pref_auth ".$pref_auth." doesn't exists");
_error("preferred auth type not supported, trying $pref_auth");
}
$this->send_auth_pkt(
$pref_auth,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
|
jaxl/JAXL | cbaf4dc822abf4fe0be0562d47e4dcbe21fb9c4b | Fix undefined $mech, remove unused code | diff --git a/src/JAXL/jaxl.php b/src/JAXL/jaxl.php
index 0cc7237..beeac6f 100644
--- a/src/JAXL/jaxl.php
+++ b/src/JAXL/jaxl.php
@@ -168,700 +168,698 @@ class JAXL extends XMPPStream
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = $this->cfg['priv_dir'];
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
if (($this->cfg['host'] === null || $this->cfg['port'] === null) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
if ($this->cfg['host'] === null) {
$this->cfg['host'] = $host;
}
if ($this->cfg['port'] === null) {
$this->cfg['port'] = $port;
}
}
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
$transport = new JAXLSocketClient($this->cfg['stream_context']);
}
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
$this->cfg['pass'],
$this->cfg['resource'] !== null ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
$this->cfg['force_tls']
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => false inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLSocketClient|XEP0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$classname = 'XEP'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if ($this->cfg['protocol'] !== null) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
-
- // check if preferred auth type exists in available mechanisms
+
$pref_auth = $this->cfg['auth_type'];
- $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
- _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
-
- // if pref auth exists, try it
- if ($pref_auth_exists) {
- $mech = $pref_auth;
+
+ // check if preferred auth type exists in available mechanisms
+ if (isset($mechs[$pref_auth]) && $mechs[$pref_auth]) {
+ _debug("pref_auth ".$pref_auth." exists");
} else {
- _error("preferred auth type not supported, trying $mech");
+ _debug("pref_auth ".$pref_auth." doesn't exists");
+ _error("preferred auth type not supported, trying $pref_auth");
}
$this->send_auth_pkt(
- $mech,
+ $pref_auth,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
}
|
jaxl/JAXL | 318d12d341e29baacee1abc1cffeb78cff271227 | Add config defaults | diff --git a/src/JAXL/jaxl.php b/src/JAXL/jaxl.php
index e0b890e..0cc7237 100644
--- a/src/JAXL/jaxl.php
+++ b/src/JAXL/jaxl.php
@@ -1,858 +1,867 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
- $this->cfg = $config;
-
+ $cfg_defaults = array(
+ 'auth_type' => 'PLAIN',
+ 'bosh_hold' => null,
+ 'bosh_rid' => null,
+ 'bosh_url' => null,
+ 'bosh_wait' => null,
+ 'domain' => null,
+ 'force_tls' => false,
+ 'host' => null,
+ 'jid' => null,
+ 'log_colorize' => $this->log_colorize,
+ 'log_level' => $this->log_level,
+ 'log_path' => JAXLLogger::$path,
+ 'multi_client' => false,
+ 'pass' => false,
+ 'port' => null,
+ 'priv_dir' => getcwd().'/.jaxl',
+ 'protocol' => null,
+ 'resource' => null,
+ 'stream_context' => null,
+ 'strict' => true
+ );
+ $this->cfg = array_merge($cfg_defaults, $config);
+
// setup logger
- if (isset($this->cfg['log_path'])) {
- JAXLLogger::$path = $this->cfg['log_path'];
- }
- //else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
- if (isset($this->cfg['log_level'])) {
- JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
- } else {
- JAXLLogger::$level = $this->log_level;
- }
- if (isset($this->cfg['log_colorize'])) {
- JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
- } else {
- JAXLLogger::$colorize = $this->log_colorize;
- }
-
+ JAXLLogger::$path = $this->cfg['log_path'];
+ JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
+ JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
+
// env
- $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
- if ($strict) {
+ if ($this->cfg['strict']) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
-
+
// jid object
- $jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
-
+ $jid = ($this->cfg['jid'] !== null) ? new XMPPJid($this->cfg['jid']) : null;
+
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
- $this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : getcwd()."/.jaxl";
+ $this->priv_dir = $this->cfg['priv_dir'];
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
-
+
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
-
+
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
- $host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
- $port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
- if ((!$host || !$port) && $jid) {
+ if (($this->cfg['host'] === null || $this->cfg['port'] === null) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
+ if ($this->cfg['host'] === null) {
+ $this->cfg['host'] = $host;
+ }
+ if ($this->cfg['port'] === null) {
+ $this->cfg['port'] = $port;
+ }
}
- $this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
- $this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
-
+
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
- //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
- $stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
- $transport = new JAXLSocketClient($stream_context);
+ $transport = new JAXLSocketClient($this->cfg['stream_context']);
}
- $this->cfg['multi_client'] = isset($this->cfg['multi_client']) ? $this->cfg['multi_client'] : false;
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
- isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
- isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
- isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
+ $this->cfg['pass'],
+ $this->cfg['resource'] !== null ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
+ $this->cfg['force_tls']
);
}
-
+
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
-
+
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
- 'Set 'strict' => TRUE inside JAXL config to disable this");
+ 'Set 'strict' => false inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
-
+
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLSocketClient|XEP0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$classname = 'XEP'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
- if (isset($this->cfg['protocol'])) {
+ if ($this->cfg['protocol'] !== null) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
- $pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
+ $pref_auth = $this->cfg['auth_type'];
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', XEP0030::NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
}
diff --git a/src/JAXL/xep/xep_0206.php b/src/JAXL/xep/xep_0206.php
index 12a8830..a33150e 100644
--- a/src/JAXL/xep/xep_0206.php
+++ b/src/JAXL/xep/xep_0206.php
@@ -1,268 +1,268 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class XEP0206 extends XMPPXep
{
const NS_HTTP_BIND = 'http://jabber.org/protocol/httpbind';
const NS_BOSH = 'urn:xmpp:xbosh';
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
//
// event callbacks
//
/**
* @param JAXLXml|XMPPStanza|string $body
*/
public function send($body)
{
if (is_object($body)) {
$body = $body->to_string();
} else {
if (substr($body, 0, 15) == '<stream:stream ') {
$this->restarted = true;
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
'xmlns:xmpp' => self::NS_BOSH
));
$body = $body->to_string();
} elseif (substr($body, 0, 16) == '</stream:stream>') {
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
$body = $body->to_string();
} else {
$body = $this->wrap($body);
}
}
_debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
_debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
_debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
_debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
_error("no ch found");
exit;
}
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.
self::NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
$this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
$this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
$this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
'xmlns:xmpp' => self::NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
- if (isset($this->jaxl->cfg['jid'])) {
+ if ($this->jaxl->cfg['jid'] !== null) {
$attrs['from'] = $this->jaxl->cfg['jid'];
}
$body = new JAXLXml('body', self::NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
$body = new JAXLXml('body', self::NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
_debug("disconnecting");
}
}
diff --git a/tests/JAXLTest.php b/tests/JAXLTest.php
index 7057221..dcd0fb0 100644
--- a/tests/JAXLTest.php
+++ b/tests/JAXLTest.php
@@ -1,57 +1,84 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* @author abhinavsingh
*
*/
class JAXLTest extends PHPUnit_Framework_TestCase
{
public function testProtocolOption()
{
$config = array(
'host' => 'domain.tld',
'port' => 5223,
'protocol' => 'tcp'
);
$jaxl = new JAXL($config);
$this->assertEquals('tcp://domain.tld:5223', $jaxl->get_socket_path());
$this->assertInstanceOf('JAXLSocketClient', $jaxl->getTransport());
}
+
+ public function testConfig()
+ {
+ $config = array();
+ $jaxl = new JAXL($config);
+
+ $this->assertEquals('PLAIN', $jaxl->cfg['auth_type']);
+ $this->assertNull($jaxl->cfg['bosh_hold']);
+ $this->assertNull($jaxl->cfg['bosh_rid']);
+ $this->assertNull($jaxl->cfg['bosh_url']);
+ $this->assertNull($jaxl->cfg['bosh_wait']);
+ $this->assertNull($jaxl->cfg['domain']);
+ $this->assertEquals($jaxl->force_tls, $jaxl->cfg['force_tls']);
+ $this->assertNull($jaxl->cfg['host']);
+ $this->assertNull($jaxl->cfg['jid']);
+ $this->assertEquals($jaxl->log_colorize, $jaxl->cfg['log_colorize']);
+ $this->assertEquals($jaxl->log_level, $jaxl->cfg['log_level']);
+ $this->assertEquals(JAXLLogger::$path, $jaxl->cfg['log_path']);
+ $this->assertFalse($jaxl->cfg['multi_client']);
+ $this->assertFalse($jaxl->cfg['pass']);
+ $this->assertNull($jaxl->cfg['port']);
+ $this->assertContains('.jaxl', $jaxl->cfg['priv_dir']);
+ $this->assertNull($jaxl->cfg['protocol']);
+ $this->assertNull($jaxl->cfg['resource']);
+ $this->assertNull($jaxl->cfg['stream_context']);
+ $this->assertTrue($jaxl->cfg['strict']);
+ }
}
|
jaxl/JAXL | ce7bc8c9e6848c6877016a3ebf8135404ef39bf7 | Bump version to v3.0.3 | diff --git a/README.md b/README.md
index 97f3e56..2f812e5 100644
--- a/README.md
+++ b/README.md
@@ -1,51 +1,51 @@
-Jaxl v3.0.2
+Jaxl v3.0.3
-----------
Jaxl v3.x is a successor of v2.x (and is NOT backward compatible),
carrying a lot of code from v2.x while throwing away the ugly parts.
A lot of components have been re-written keeping in mind the feedback from
the developer community over the last 4 years. Also Jaxl shares a few
philosophies from my experience with erlang and python languages.
Jaxl is an asynchronous, non-blocking I/O, event based PHP library
for writing custom TCP/IP client and server implementations.
From it's previous versions, library inherits a full blown stable support
-for [XMPP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.2/xmpp).
-In v3.0, support for [HTTP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.2/http)
+for [XMPP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.3/xmpp).
+In v3.0, support for [HTTP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.3/http)
has also been added.
-At the heart of every protocol stack sits the [Core stack](https://github.com/jaxl/JAXL/tree/v3.0.2/core).
+At the heart of every protocol stack sits the [Core stack](https://github.com/jaxl/JAXL/tree/v3.0.3/core).
It contains all the building blocks for everything that we aim to do with Jaxl library.
Both XMPP and HTTP protocol stacks are written on top of the Core stack.
Infact the source code of protocol implementations knows nothing
about the standard (inbuilt) PHP socket and stream methods.
-[Examples](https://github.com/jaxl/JAXL/tree/v3.0.2/examples/)
+[Examples](https://github.com/jaxl/JAXL/tree/v3.0.3/examples/)
[Documentation](http://jaxl.readthedocs.org/)
[Group and Mailing List](https://groups.google.com/forum/#!forum/jaxl)
[Create a bug/issue](https://github.com/jaxl/JAXL/issues/new)
[Author](http://abhinavsingh.com/)
## Contributing
JAXL since v3.0.1 adopt [PSR-2](http://www.php-fig.org/psr/psr-2/).
To make it easier to maintain the code contribute your changes after they have
passed [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer)
and [PHPUnit](https://github.com/sebastianbergmann/phpunit). If possible, add
a unit tests for your changes into the *tests* folder.
To know current errors and failed tests, run:
```ShellSession
./vendor/bin/phpcs
./vendor/bin/phpunit
```
## License
The product licensed under the BSD 3-Clause license.
See [LICENSE](https://github.com/jaxl/JAXL/blob/master/LICENSE).
diff --git a/docs/conf.py b/docs/conf.py
index 2371394..101da34 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,242 +1,242 @@
# -*- coding: utf-8 -*-
#
# Jaxl documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 15 03:08:42 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode']
# , 'sphinxcontrib.phpdomain'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Jaxl'
copyright = u'2012, Abhinav Singh'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '3.0'
# The full version, including alpha/beta/rc tags.
-release = '3.0.2'
+release = '3.0.3'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'pastie'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Jaxldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Jaxl.tex', u'Jaxl Documentation',
u'Abhinav Singh', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'jaxl', u'Jaxl Documentation',
[u'Abhinav Singh'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Jaxl', u'Jaxl Documentation',
u'Abhinav Singh', 'Jaxl', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
diff --git a/docs/users/getting_started.rst b/docs/users/getting_started.rst
index 8f7f271..6f57e96 100644
--- a/docs/users/getting_started.rst
+++ b/docs/users/getting_started.rst
@@ -1,144 +1,149 @@
Getting Started
===============
Requirements
------------
No external component or library is required.
You simply need a standard PHP installation to work with Jaxl.
Library has been developed and tested extensively on
linux operating systems. But there is no reason why it should
not work on other OS. File an `issue <https://github.com/jaxl/JAXL/issues/new>`_ if you face any glitches.
Install
-------
Use `Composer <https://getcomposer.org>`_ to install:
-composer require "jaxl/jaxl=^3.0.2"
+php composer.phar require "jaxl/jaxl=^3.0.3"
+php composer.phar update
+
+Then use autoloader in your application:
+
+require dirname(__FILE__) . '/vendor/autoload.php';
Library Structure
-----------------
Jaxl library comprises of following packages:
* ``jaxl-core``
contains generic networking and eventing components
* ``jaxl-xmpp``
contains xmpp rfc implementation
* ``jaxl-xmpp-xep``
contains various xmpp xep implementation
* ``jaxl-http``
contains http rfc implementation
* ``jaxl-docs``
this documentation comes from this package
* ``jaxl-tests``
test suites for all the above packages
Inside Jaxl everything that you will interact with will be an object which
will emit events and callbacks which we will be able to catch in our applications
for custom processing and routing. Listed below are a few main objects:
#. Core Stack
* ``JAXLLoop``
main select loop
* ``JAXLClock``
timed job/callback dispatcher
* ``JAXLEvent``
event registry and emitter
* ``JAXLFsm``
generic finite state machine
* ``JAXLSocketClient``
generic tcp/udp client
* ``JAXLSocketServer``
generic tcp/udp server
* ``JAXLXmlStream``
streaming XML parser
* ``JAXLXml``
custom XML object implementation
* ``JAXLLogger``
logging facility
#. XMPP Stack
* ``XMPPStream``
base xmpp rfc implementation
* ``XMPPStanza``
provides easy access patterns over xmpp stanza (wraps ``JAXLXml``)
* ``XMPPIq``
xmpp iq stanza object (extends ``XMPPStanza``)
* ``XMPPMsg``
xmpp msg stanza object (extends ``XMPPStanza``)
* ``XMPPPres``
xmpp pres stanza object (extends ``XMPPStanza``)
* ``XMPPXep``
abstract xmpp extension (extended by XEP implementations)
* ``XMPPJid``
xmpp jid object
#. HTTP Stack
* ``HTTPServer``
http server implementation
* ``HTTPClient``
http client implementation
* ``HTTPRequest``
http request object
* ``HTTPResponse``
http response object
Questions, Bugs and Issues
--------------------------
If you have any questions kindly post them on `google groups <https://groups.google.com/forum/#!forum/jaxl>`_. Groups are the quickest
way to get an answer to your questions which is actively monitored by core developers.
If you are facing a bug or issue, please report that it on `github issue tracker <https://github.com/abhinavsingh/JAXL/issues/new>`_.
You can even :ref:`contribute to the library <developer-introduction>` if you already have fixed the bug.
diff --git a/jaxl.php b/jaxl.php
index 4057939..98908db 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,579 +1,579 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
- const version = '3.0.2';
+ const version = '3.0.3';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory in JAXL_CWD for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// If connection to the destination fails.
if ($this->trans->errno == 61 ||
$this->trans->errno == 110 ||
$this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
|
jaxl/JAXL | 5874a31e9ca83c7e28b2c3bc8c24875a691d6ad2 | Fix undefined $mech | diff --git a/docs/users/logging.rst b/docs/users/logging.rst
index 687d606..46ae49e 100644
--- a/docs/users/logging.rst
+++ b/docs/users/logging.rst
@@ -1,29 +1,33 @@
Logging Interface
=================
+
``JAXLLogger`` provides all the logging facilities that we will ever require.
-When logging to ``STDOUT`` it also colorizes the log message depending upon its severity level.
-When logging to a file it can also do periodic log rotation.
+When logging to ``STDOUT`` it also colorizes the log message depending upon
+its severity level. When logging to a file it can also do periodic log
+rotation.
log levels
----------
* JAXL_ERROR (red)
* JAXL_WARNING (blue)
* JAXL_NOTICE (yellow)
* JAXL_INFO (green)
* JAXL_DEBUG (white)
global logging methods
----------------------
+
Following global methods for logging are available:
* ``_error($msg)``
* ``_warning($msg)``
* ``_notice($msg)``
* ``_info($msg)``
* ``_debug($msg)``
-_colorize/2
------------
-All the above global logging methods internally use ``_colorize($msg, $verbosity)`` to output colored
-log message on the terminal.
\ No newline at end of file
+log/2
+-----
+
+All the above global logging methods internally use ``JAXLLogger::log($msg, $verbosity)``
+to output colored log message on the terminal.
diff --git a/jaxl.php b/jaxl.php
index 7531ef3..4057939 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,872 +1,871 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const version = '3.0.2';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
-
- // create .jaxl directory in JAXL_CWD
- // for our /tmp, /run and /log folders
+
+ // Create .jaxl directory in JAXL_CWD for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
-
+
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
-
+
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
-
+
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
-
+
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
-
+
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
-
+
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
-
+
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
- // if connection to the destination fails
-
- if ($this->trans->errno == 61
- || $this->trans->errno == 110
- || $this->trans->errno == 111
+ // If connection to the destination fails.
+ if ($this->trans->errno == 61 ||
+ $this->trans->errno == 110 ||
+ $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
+ $mech = $pref_auth;
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
-
+
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
-
+
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
-
+
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
-
+
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
-
+
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
-
+
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
-
+
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
diff --git a/jaxlctl b/jaxlctl
index ce5af32..0c2a084 100755
--- a/jaxlctl
+++ b/jaxlctl
@@ -1,200 +1,207 @@
#!/usr/bin/env php
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
error_reporting(E_ALL | E_STRICT);
-date_default_timezone_set('UTC');
+
+if (PHP_SAPI !== 'cli') {
+ echo 'Warning: script should be invoked via the CLI version of PHP, not the '.PHP_SAPI.' SAPI'.PHP_EOL;
+}
+
+if (!ini_get('date.timezone')) {
+ ini_set('date.timezone', 'UTC');
+}
$params = $argv;
$exe = array_shift($params);
$command = array_shift($params);
require_once 'jaxl.php';
JAXLLogger::$level = JAXL_INFO;
// TODO: an abstract JAXLCtlCommand class
// with seperate class per command
// a mechanism to register new commands
class JAXLCtl
{
protected $ipc = null;
protected $buffer = '';
protected $buffer_cb = null;
protected $cli = null;
public $dots = "....... ";
protected $symbols = array();
public function __construct($command, $params)
{
global $exe;
if (method_exists($this, $command)) {
$r = call_user_func_array(array(&$this, $command), $params);
if (count($r) == 2) {
list($buffer_cb, $quit_cb) = $r;
$this->buffer_cb = $buffer_cb;
$this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb);
$this->run();
} else {
_colorize("oops! internal command error", JAXL_ERROR);
exit;
}
} else {
_colorize("error: invalid command '$command' received", JAXL_ERROR);
_colorize("type '$exe help' for list of available commands", JAXL_NOTICE);
exit;
}
}
public function run()
{
JAXLCli::prompt();
JAXLLoop::run();
}
public function on_terminal_input($raw)
{
$raw = trim($raw);
$last = substr($raw, -1, 1);
if ($last == ";") {
// dispatch to buffer callback
call_user_func($this->buffer_cb, $this->buffer.$raw);
$this->buffer = '';
} elseif ($last == '\\') {
$this->buffer .= substr($raw, 0, -1);
echo $this->dots;
} else {
// buffer command
$this->buffer .= $raw."; ";
echo $this->dots;
}
}
public static function print_help()
{
global $exe;
_colorize("Usage: $exe command [options...]\n", JAXL_INFO);
_colorize("Commands:", JAXL_NOTICE);
_colorize(" help This help text", JAXL_DEBUG);
_colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG);
_colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG);
echo "\n";
}
protected function help()
{
JAXLCtl::print_help();
exit;
}
//
// shell command
//
protected function shell()
{
return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit'));
}
private function _eval($raw, $symbols)
{
extract($symbols);
eval($raw);
$g = get_defined_vars();
unset($g['raw']);
unset($g['symbols']);
return $g;
}
public function on_shell_input($raw)
{
$this->symbols = $this->_eval($raw, $this->symbols);
JAXLCli::prompt();
}
public function on_shell_quit()
{
exit;
}
//
// debug command
//
protected function debug($sock_path)
{
$this->ipc = new JAXLSocketClient();
$this->ipc->set_callback(array(&$this, 'on_debug_response'));
$this->ipc->connect('unix://'.$sock_path);
return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit'));
}
public function on_debug_response($raw)
{
$ret = unserialize($raw);
print_r($ret);
echo "\n";
JAXLCli::prompt();
}
public function on_debug_input($raw)
{
$this->ipc->send($this->buffer.$raw);
}
public function on_debug_quit()
{
$this->ipc->disconnect();
exit;
}
}
// we atleast need a command argument
if ($argc < 2) {
JAXLCtl::print_help();
exit;
}
$ctl = new JAXLCtl($command, $params);
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/xep/xep_0206.php b/xep/xep_0206.php
index 7fa3f09..edd5f93 100644
--- a/xep/xep_0206.php
+++ b/xep/xep_0206.php
@@ -1,270 +1,270 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind');
define('NS_BOSH', 'urn:xmpp:xbosh');
class XEP_0206 extends XMPPXep
{
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
-
+
//
// event callbacks
//
-
+
/**
* @param JAXLXml|XMPPStanza|string $body
*/
public function send($body)
{
if (is_object($body)) {
$body = $body->to_string();
} else {
if (substr($body, 0, 15) == '<stream:stream ') {
$this->restarted = true;
$body = new JAXLXml('body', NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
'xmlns:xmpp' => NS_BOSH
));
$body = $body->to_string();
} elseif (substr($body, 0, 16) == '</stream:stream>') {
$body = new JAXLXml('body', NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
$body = $body->to_string();
} else {
$body = $this->wrap($body);
}
}
_debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
_debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
_debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
_debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
_error("no ch found");
exit;
}
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
$this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
$this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
$this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
'xmlns:xmpp' => NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
if (isset($this->jaxl->cfg['jid'])) {
$attrs['from'] = $this->jaxl->cfg['jid'];
}
$body = new JAXLXml('body', NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
$body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
_debug("disconnecting");
}
}
|
jaxl/JAXL | 9831ba4d7fbf0256f3ffd60f60b8a3bf65845db6 | Add type hints | diff --git a/core/jaxl_event.php b/core/jaxl_event.php
index 91a3168..1a54a35 100644
--- a/core/jaxl_event.php
+++ b/core/jaxl_event.php
@@ -1,156 +1,159 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Following kind of events are possible:
* 1) hook i.e. if a callback for such an event is registered, calling function
* is responsible for the workflow from their on
* 2) filter i.e. calling function will manipulate passed arguments
* and modified arguments will be passed to next chain of filter
*
* As a rule of thumb, only 1 hook can be registered for an event, while more
* than 1 filter is allowed for an event hook and filter both cannot be applied
* on an event.
*
* @author abhinavsingh
*
*/
class JAXLEvent
{
protected $common = array();
public $reg = array();
+ /**
+ * @param array $common
+ */
public function __construct($common)
{
$this->common = $common;
}
public function __destruct()
{
}
/**
* Add callback on a event.
*
* Callback'd method must return `true` to be persistent, otherwise
* if returned `null` or `false`, callback will be removed automatically.
*
* @param string $ev
* @param callable $cb
* @param int $priority
* @return string Reference to be used while deleting callback.
*/
public function add($ev, $cb, $priority)
{
if (!isset($this->reg[$ev])) {
$this->reg[$ev] = array();
}
$ref = count($this->reg[$ev]);
$this->reg[$ev][] = array($priority, $cb);
return $ev."-".$ref;
}
/**
* Emit event to notify registered callbacks.
*
* TODO: Is a pqueue required here for performance enhancement in case we
* have too many cbs on a specific event?
*
* @param string $ev
* @param array $data
* @return array
*/
public function emit($ev, array $data = array())
{
$data = array_merge($this->common, $data);
$cbs = array();
if (!isset($this->reg[$ev])) {
return $data;
}
foreach ($this->reg[$ev] as $cb) {
if (!isset($cbs[$cb[0]])) {
$cbs[$cb[0]] = array();
}
$cbs[$cb[0]][] = $cb[1];
}
foreach ($cbs as $pri => $cb) {
foreach ($cb as $c) {
$ret = call_user_func_array($c, $data);
// This line is for fixing situation where callback function doesn't return an array type.
// In such cases next call of call_user_func_array will report error since $data is not
// an array type as expected.
// Things will change in future, atleast put the callback inside a try/catch block.
// Here we only check if there was a return, if yes we update $data with return value.
// This is bad design, need more thoughts, should work as of now.
if ($ret) {
$data = $ret;
}
}
}
unset($cbs);
return $data;
}
/**
* Remove previous registered callback.
*
* @param string $ref
*/
public function del($ref)
{
$ref = explode("-", $ref);
unset($this->reg[$ref[0]][$ref[1]]);
}
/**
* @param string $ev
* @return bool
*/
public function exists($ev)
{
$ret = isset($this->reg[$ev]);
//_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists"));
return $ret;
}
}
diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php
index 22b3c83..32cb37c 100644
--- a/core/jaxl_pipe.php
+++ b/core/jaxl_pipe.php
@@ -1,136 +1,139 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
/**
* bidirectional communication pipes for processes
*
* This is how this will be (when complete):
* $pipe = new JAXLPipe() will return an array of size 2
* $pipe[0] represents the read end of the pipe
* $pipe[1] represents the write end of the pipe
*
* Proposed functionality might even change (currently consider this as experimental)
*
* @author abhinavsingh
*
*/
class JAXLPipe
{
protected $perm = 0600;
/** @var callable */
protected $recv_cb = null;
protected $fd = null;
/** @var JAXLSocketClient */
protected $client = null;
/** @var string */
public $name = null;
/**
* @param string $name
* @param callable $read_cb TODO: Currently not used
*/
public function __construct($name, $read_cb = null)
{
$pipes_folder = JAXL_CWD.'/.jaxl/pipes';
if (!is_dir($pipes_folder)) {
mkdir($pipes_folder);
}
$this->ev = new JAXLEvent();
$this->name = $name;
// TODO: If someone's need the read callback and extends the JAXLPipe
// to obtain it, one can't because this property is private.
$this->read_cb = $read_cb;
$pipe_path = $this->get_pipe_file_path();
if (!file_exists($pipe_path)) {
posix_mkfifo($pipe_path, $this->perm);
$this->fd = fopen($pipe_path, 'r+');
if (!$this->fd) {
_error("unable to open pipe");
} else {
_debug("pipe opened using path $pipe_path");
_notice("Usage: $ echo 'Hello World!' > $pipe_path");
$this->client = new JAXLSocketClient();
$this->client->connect($this->fd);
$this->client->set_callback(array(&$this, 'on_data'));
}
} else {
_error("pipe with name $name already exists");
}
}
public function __destruct()
{
if (is_resource($this->fd)) {
fclose($this->fd);
}
if (file_exists($this->get_pipe_file_path())) {
unlink($this->get_pipe_file_path());
}
_debug("unlinking pipe file");
}
+ /**
+ * @return string
+ */
public function get_pipe_file_path()
{
return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe';
}
/**
* @param callable $recv_cb
*/
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function on_data($data)
{
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $data);
}
}
}
diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php
index 57c1cf4..224bc3a 100644
--- a/core/jaxl_xml.php
+++ b/core/jaxl_xml.php
@@ -1,282 +1,292 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/
* Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml
*
* @author abhinavsingh
*
*/
class JAXLXml
{
public $name;
public $ns = null;
public $attrs = array();
public $text = null;
/** @var JAXLXml[] */
public $childrens = array();
public $parent = null;
public $rover = null;
/**
* Accepts any of the following constructors:
*
* * JAXLXml($name, $ns, $attrs, $text)
* * JAXLXml($name, $ns, $attrs)
* * JAXLXml($name, $ns, $text)
* * JAXLXml($name, $attrs, $text)
* * JAXLXml($name, $attrs)
* * JAXLXml($name, $ns)
* * JAXLXml($name)
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
public function __construct()
{
$argv = func_get_args();
$argc = count($argv);
$this->name = $argv[0];
switch ($argc) {
case 4:
$this->ns = $argv[1];
$this->attrs = $argv[2];
$this->text = $argv[3];
break;
case 3:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
$this->text = $argv[2];
} else {
$this->ns = $argv[1];
if (is_array($argv[2])) {
$this->attrs = $argv[2];
} else {
$this->text = $argv[2];
}
}
break;
case 2:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
} else {
$this->ns = $argv[1];
}
break;
default:
break;
}
$this->rover = &$this;
}
public function __destruct()
{
}
/**
+ * Set or update attrs of element.
+ *
* @param array $attrs
* @return JAXLXml
*/
public function attrs(array $attrs)
{
$this->rover->attrs = array_merge($this->rover->attrs, $attrs);
return $this;
}
/**
+ * Check that element matches by attrs.
+ *
* @param array $attrs
* @return bool
*/
public function match_attrs(array $attrs)
{
$matches = true;
foreach ($attrs as $k => $v) {
if ($this->attrs[$k] !== $v) {
$matches = false;
break;
}
}
return $matches;
}
/**
* Set or append text.
*
* @param string $text
* @param bool $append
* @return JAXLXml
*/
public function t($text, $append = false)
{
if (!$append) {
$this->rover->text = $text;
} else {
if ($this->rover->text === null) {
$this->rover->text = '';
}
$this->rover->text .= $text;
}
return $this;
}
/**
* Create child.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
* @return JAXLXml
*/
public function c($name, $ns = null, array $attrs = array(), $text = null)
{
$node = new JAXLXml($name, $ns, $attrs, $text);
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
/**
* Append child node.
*
* @param JAXLXml $node
* @return JAXLXml
*/
public function cnode($node)
{
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
+ /**
+ * @return JAXLXml
+ */
public function up()
{
if ($this->rover->parent) {
$this->rover = &$this->rover->parent;
}
return $this;
}
+ /**
+ * @return JAXLXml
+ */
public function top()
{
$this->rover = &$this;
return $this;
}
/**
* @param string $name
* @param string $ns
* @param array $attrs
* @return JAXLXml|bool
*/
public function exists($name, $ns = null, array $attrs = array())
{
foreach ($this->childrens as $child) {
if ($ns) {
if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) {
return $child;
}
} elseif ($child->name == $name && $child->match_attrs($attrs)) {
return $child;
}
}
return false;
}
/**
* Update child with name ``$name``.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
public function update($name, $ns = null, array $attrs = array(), $text = null)
{
foreach ($this->childrens as $k => $child) {
if ($child->name == $name) {
$child->ns = $ns;
$child->attrs($attrs);
$child->text = $text;
$this->childrens[$k] = $child;
break;
}
}
}
/**
* @param string $parent_ns
* @return string
*/
public function to_string($parent_ns = null)
{
$xml = '';
$xml .= '<'.$this->name;
if ($this->ns && $this->ns != $parent_ns) {
$xml .= ' xmlns="'.$this->ns.'"';
}
foreach ($this->attrs as $k => $v) {
if (!is_null($v) && $v !== false) {
$xml .= ' '.$k.'="'.htmlspecialchars($v).'"';
}
}
$xml .= '>';
foreach ($this->childrens as $child) {
$xml .= $child->to_string($this->ns);
}
if ($this->text) {
$xml .= htmlspecialchars($this->text);
}
$xml .= '</'.$this->name.'>';
return $xml;
}
}
diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php
index d4dc97e..683f051 100644
--- a/core/jaxl_xml_stream.php
+++ b/core/jaxl_xml_stream.php
@@ -1,199 +1,198 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLXmlStream
{
private $delimiter = '\\';
private $ns;
private $parser;
private $stanza;
private $depth = -1;
private $start_cb;
private $stanza_cb;
private $end_cb;
public function __construct()
{
$this->init_parser();
}
private function init_parser()
{
$this->depth = -1;
$this->parser = xml_parser_create_ns("UTF-8", $this->delimiter);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
xml_set_character_data_handler($this->parser, array(&$this, "handle_character"));
xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag"));
}
public function __destruct()
{
//_debug("cleaning up xml parser...");
@xml_parser_free($this->parser);
}
public function reset_parser()
{
$this->parse_final(null);
@xml_parser_free($this->parser);
$this->parser = null;
$this->init_parser();
}
public function set_callback($start_cb, $end_cb, $stanza_cb)
{
$this->start_cb = $start_cb;
$this->end_cb = $end_cb;
$this->stanza_cb = $stanza_cb;
}
public function parse($str)
{
xml_parse($this->parser, $str, false);
}
public function parse_final($str)
{
xml_parse($this->parser, $str, true);
}
protected function handle_start_tag($parser, $name, array $attrs)
{
$name = $this->explode($name);
//echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL;
// replace ns with prefix
foreach ($attrs as $key => $v) {
$k = $this->explode($key);
// no ns specified
if ($k[0] == null) {
$attrs[$k[1]] = $v;
} elseif ($k[0] == NS_XML) {
// xml ns
-
unset($attrs[$key]);
$attrs['xml:'.$k[1]] = $v;
} else {
_error("==================> unhandled ns prefix on attribute");
// remove attribute else will cause error with bad stanza format
// report to developer if above error message is ever encountered
unset($attrs[$key]);
}
}
if ($this->depth <= 0) {
$this->depth = 0;
$this->ns = $name[1];
if ($this->start_cb) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
call_user_func($this->start_cb, $stanza);
}
} else {
if (!$this->stanza) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
$this->stanza = &$stanza;
} else {
$this->stanza->c($name[1], $name[0], $attrs);
}
}
++$this->depth;
}
protected function handle_end_tag($parser, $name)
{
$name = explode($this->delimiter, $name);
$name = count($name) == 1 ? array('', $name[0]) : $name;
//echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL;
if ($this->depth == 1) {
if ($this->end_cb) {
$stanza = new JAXLXml($name[1], $this->ns);
call_user_func($this->end_cb, $stanza);
}
} elseif ($this->depth > 1) {
if ($this->stanza) {
$this->stanza->up();
}
if ($this->depth == 2) {
if ($this->stanza_cb) {
call_user_func($this->stanza_cb, $this->stanza);
$this->stanza = null;
}
}
}
--$this->depth;
}
protected function handle_character($parser, $data)
{
//echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL;
if ($this->stanza) {
$this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), true);
}
}
private function implode($data)
{
return implode($this->delimiter, $data);
}
private function explode($data)
{
$data = explode($this->delimiter, $data);
$data = count($data) == 1 ? array(null, $data[0]) : $data;
return $data;
}
}
diff --git a/docs/users/jaxl_instance.rst b/docs/users/jaxl_instance.rst
index e27883e..216439e 100644
--- a/docs/users/jaxl_instance.rst
+++ b/docs/users/jaxl_instance.rst
@@ -1,158 +1,159 @@
.. _jaxl-instance:
JAXL Instance
=============
+
``JAXL`` instance configure/manage other :ref:`sub-packages <jaxl-instance>`.
It provides an event based callback methodology on various underlying object. Whenever required
``JAXL`` instance will itself perform the configured defaults.
Constructor options
-------------------
#. ``jid``
#. ``pass``
#. ``resource``
If not passed Jaxl will use a random resource value
#. ``auth_type``
DIGEST-MD5, PLAIN (default), CRAM-MD5, ANONYMOUS
#. ``host``
#. ``port``
#. ``bosh_url``
#. ``log_path``
#. ``log_level``
``JAXL_ERROR``, ``JAXL_WARNING``, ``JAXL_NOTICE``, ``JAXL_INFO`` (default), ``JAXL_DEBUG``
#. ``force_tls``
#. ``stream_context``
#. ``priv_dir``
Jaxl creates 4 directories names ``log``, ``tmp``, ``run`` and ``sock`` inside a private directory
which defaults to ``JAXL_CWD.'/.jaxl'``. If this option is passed, it will overwrite default private
directory.
.. note::
Jaxl currently doesn't check upon the permissions of passed ``priv_dir``. Make sure Jaxl library
have sufficient permissions to create above mentioned directories.
Available Event Callbacks
-------------------------
Following ``$ev`` are available on ``JAXL`` lifecycle for registering callbacks:
#. ``on_connect``
``JAXL`` instance has connected successfully
#. ``on_connect_error``
``JAXL`` instance failed to connect
#. ``on_stream_start``
``JAXL`` instance has successfully initiated XMPP stream with the jabber server
#. ``on_stream_features``
``JAXL`` instance has received supported stream features
#. ``on_auth_success``
authentication successful
#. ``on_auth_failure``
authentication failed
#. ``on_presence_stanza``
``JAXL`` instance has received a presence stanza
#. ``on_{$type}_message``
``JAXL`` instance has received a message stanza. ``$type`` can be ``chat``, ``groupchat``, ``headline``, ``normal``, ``error``
#. ``on_stanza_id_{$id}``
Useful when dealing with iq stanza. This event is fired when ``JAXL`` instance has received response to a particular
xmpp stanza id
#. ``on_{$name}_stanza``
Useful when dealing with custom xmpp stanza
#. ``on_disconnect``
``JAXL`` instance has disconnected from the jabber server
Available Methods
-----------------
Following methods are available on initialized ``JAXL`` instance object:
#. ``get_pid_file_path()``
returns path of ``JAXL`` instance pid file
#. ``get_sock_file_path()``
returns path to ``JAXL`` ipc unix socket domain
#. ``require_xep($xeps = array())``
autoload and initialize passed XEP's
#. ``add_cb($ev, $cb, $priority = 1)``
add a callback to function ``$cb`` on event ``$ev``, returns a reference of added callback
#. ``del_cb($ref)``
delete previously registered event callback
#. ``set_status($status, $show, $priority)``
send a presence status stanza
#. ``send_chat_msg($to, $body, $thread = null, $subject = null)``
send a message stanza of type chat
#. ``get_vcard($jid = null, $cb = null)``
fetch vcard for bare ``$jid``, passed ``$cb`` will be called with received vcard stanza
#. ``get_roster($cb = null)``
fetch roster list of connected jabber client, passed ``$cb`` will be called with received roster stanza
#. ``start($opts = array())``
start configured ``JAXL`` instance, optionally accepts two options specified below:
#. ``--with-debug-shell``
start ``JAXL`` instance and enter an interactive console
#. ``--with-unix-sock``
start ``JAXL`` instance with support for IPC and remote debugging
#. ``send($stanza)``
send an instance of JAXLXml packet over connected socket
#. ``send_raw($data)``
send raw payload over connected socket
#. ``get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)``
#. ``get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)``
- #. ``get_iq_pkt($attrs, $payload)``
\ No newline at end of file
+ #. ``get_iq_pkt($attrs, $payload)``
diff --git a/docs/users/xml_objects.rst b/docs/users/xml_objects.rst
index 9323f10..a92c58b 100644
--- a/docs/users/xml_objects.rst
+++ b/docs/users/xml_objects.rst
@@ -1,121 +1,122 @@
.. _xml-objects:
Xml Objects
===========
Jaxl library works with custom XML implementation which is similar to
inbuild PHP XML functions but is lightweight and easy to work with.
JAXLXml
-------
``JAXLXml`` is the base XML object. Open up :ref:`Jaxl interactive shell <jaxl-instance>` and try some xml object creation/manipulation:
>>> ./jaxlctl shell
jaxl 1>
jaxl 1> $xml = new JAXLXml(
....... 'dummy',
....... 'dummy:packet',
....... array('attr1' => '[email protected]', 'attr2' => ''),
....... 'Hello World!'
....... );
jaxl 2> echo $xml->to_string();
<dummy xmlns="dummy:packet" attr1="[email protected]" attr2="">Hello World!</dummy>
jaxl 3>
``JAXLXml`` constructor instance accepts following parameters:
* ``JAXLXml($name, $ns, $attrs, $text)``
* ``JAXLXml($name, $ns, $attrs)``
* ``JAXLXml($name, $ns, $text)``
* ``JAXLXml($name, $attrs, $text)``
* ``JAXLXml($name, $attrs)``
* ``JAXLXml($name, $ns)``
* ``JAXLXml($name)``
``JAXLXml`` draws inspiration from StropheJS XML Builder class. Below are available methods
for modifying and manipulating an ``JAXLXml`` object:
* ``t($text, $append = false)``
update text of current rover
* ``c($name, $ns = null, $attrs = array(), $text = null)``
append a child node at current rover
* ``cnode($node)``
append a JAXLXml child node at current rover
* ``up()``
move rover to one step up the xml tree
* ``top()``
move rover back to top element in the xml tree
* ``exists($name, $ns = null, $attrs = array())``
checks if a child with $name exists, return child ``JAXLXml`` if found otherwise false. This function returns at first matching child.
* ``update($name, $ns = null, $attrs = array(), $text = null)``
update specified child element
* ``attrs($attrs)``
merge new attrs with attributes of current rover
* ``match_attrs($attrs)``
pass a kv pair of ``$attrs``, return bool if all passed keys matches their respective values in the xml packet
* ``to_string()``
get string representation of the object
``JAXLXml`` maintains a rover which points to the current level down the XML tree where
manipulation is performed.
XMPPStanza
----------
+
In the world of XMPP where everything incoming and outgoing payload is an ``JAXLXml`` instance code can become nasty,
developers can get lost in dirty XML manipulations spreaded all over the application code base and what not.
XML structures are not only unreadable for humans but even for machine.
While an instance of ``JAXLXml`` provide direct access to XML ``name``, ``ns`` and ``text``, it can become painful and
time consuming when trying to retrieve or modify a particular ``attrs`` or ``childrens``. I was fed up of doing
``getAttributeByName``, ``setAttributeByName``, ``getChild`` etc everytime i had to access common XMPP Stanza attributes.
``XMPPStanza`` is a wrapper on top of ``JAXLXml`` objects. Preserving all the functionalities of base ``JAXLXml``
instance it also provide direct access to most common XMPP Stanza attributes like ``to``, ``from``, ``id``, ``type`` etc.
It also provides a framework for adding custom access patterns.
``XMPPMsg``, ``XMPPPres`` and ``XMPPIq`` extends ``XMPPStanza`` and also add a few custom access patterns like
``body``, ``thread``, ``subject``, ``status``, ``show`` etc.
Here is a list of default access patterns:
#. ``name``
#. ``ns``
#. ``text``
#. ``attrs``
#. ``childrens``
#. ``to``
#. ``from``
#. ``id``
#. ``type``
#. ``to_node``
#. ``to_domain``
#. ``to_resource``
#. ``from_node``
#. ``from_domain``
#. ``from_resource``
#. ``status``
#. ``show``
#. ``priority``
#. ``body``
#. ``thread``
#. ``subject``
diff --git a/xmpp/README.md b/xmpp/README.md
index d79589d..3db54cb 100644
--- a/xmpp/README.md
+++ b/xmpp/README.md
@@ -1,12 +1,13 @@
Jaxl XMPP Stack:
----------------
+
XMPP Stack implementation includes:
* XMPPStream - RFC 6120 and RFC 6121
* XMPPXep - Abstract XMPP Extension class
* XMPPStanza - Generic Stanza object
* XMPPPres - Generic Presence object
* XMPPMsg - Generic Message object
* XMPPIq - Generic IQ object
* XMPPJid - JabberId object
-* XMPPRosterItem - A XMPP Roster Item representation
\ No newline at end of file
+* XMPPRosterItem - A XMPP Roster Item representation
diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php
index b07e831..bc6e205 100644
--- a/xmpp/xmpp_stanza.php
+++ b/xmpp/xmpp_stanza.php
@@ -1,198 +1,233 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
/**
* Generic xmpp stanza object which provide convinient access pattern over xml objects
* Also to be able to convert an existing xml object into stanza object (to get access patterns going)
* this class doesn't extend xml, but infact works on a reference of xml object
* If not provided during constructor, new xml object is created and saved as reference
*
* @author abhinavsingh
*
+ * Access to common xml attributes:
+ *
+ * @property string $to
+ * @property string $from
+ * @property string $id
+ * @property string $type
+ *
+ * Access to parts of common xml attributes:
+ *
+ * @property string $to_node
+ * @property string $to_domain
+ * @property string $to_resource
+ * @property string $from_node
+ * @property string $from_domain
+ * @property string $from_resource
+ *
+ * Access to first child element text:
+ *
+ * @property string $status
+ * @property string $show
+ * @property string $priority
+ * @property string $body
+ * @property string $thread
+ * @property string $subject
+ *
+ * @method JAXLXml attrs(array $attrs) Set or update attrs of element.
+ * @method bool match_attrs(array $attrs) Check that element matches by attrs.
+ * @method JAXLXml t($text, $append = false) Set or append text.
+ * @method JAXLXml c($name, $ns = null, array $attrs = array(), $text = null) Create child.
+ * @method JAXLXml cnode($node) Append child node.
+ * @method JAXLXml up()
+ * @method JAXLXml top()
+ * @method JAXLXml|bool exists($name, $ns = null, array $attrs = array())
+ * @method void update($name, $ns = null, array $attrs = array(), $text = null) Update child with name ``$name``.
+ * @method string to_string($parent_ns = null)
*/
class XMPPStanza
{
/**
* @var JAXLXml
*/
private $xml;
/**
* @param JAXLXml|string $name
* @param array $attrs
* @param string $ns
*/
public function __construct($name, array $attrs = array(), $ns = NS_JABBER_CLIENT)
{
if ($name instanceof JAXLXml) {
$this->xml = $name;
} else {
$this->xml = new JAXLXml($name, $ns, $attrs);
}
}
public function __call($method, $args)
{
return call_user_func_array(array($this->xml, $method), $args);
}
public function __get($prop)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
return isset($this->xml->attrs[$prop]) ? $this->xml->attrs[$prop] : null;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val) {
return null;
}
$val = new XMPPJid($val);
return $val->$key;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val = $this->xml->exists($prop);
if (!$val) {
return null;
}
return $val->text;
break;
default:
return null;
break;
}
}
public function __set($prop, $val)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop = $val;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
$this->xml->attrs[$prop] = $val;
return true;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val1 = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val1) {
$val1 = '';
}
$val1 = new XMPPJid($val1);
$val1->$key = $val;
$this->xml->attrs[$attr] = $val1->to_string();
return true;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val1 = $this->xml->exists($prop);
if (!$val1) {
$this->xml->c($prop)->t($val)->up();
} else {
$this->xml->update($prop, $val1->ns, $val1->attrs, $val);
}
return true;
break;
default:
return null;
break;
}
}
}
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php
index b366fdb..99794b5 100644
--- a/xmpp/xmpp_stream.php
+++ b/xmpp/xmpp_stream.php
@@ -1,617 +1,617 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
require_once JAXL_CWD.'/core/jaxl_xml_stream.php';
require_once JAXL_CWD.'/core/jaxl_util.php';
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/xmpp/xmpp_msg.php';
require_once JAXL_CWD.'/xmpp/xmpp_pres.php';
require_once JAXL_CWD.'/xmpp/xmpp_iq.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
* @var JAXLSocketClient|XEP_0206
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
- * @param string $transport
+ * @param JAXLSocketClient|XEP_0206 $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
$jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//_debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
_error("got invalid return value from state handler '".$this->state."', sending end stream...");
$this->send_end_stream();
$this->state = "logged_out";
_notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers");
}
/**
* @param JAXLXml|XMPPStanza $stanza
*/
public function send($stanza)
{
$this->trans->send($stanza->to_string());
}
/**
* @param string $data
*/
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
_debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//_debug("stream started");
return "wait_for_stream_features";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', NS_BIND) ? true : false;
$sess = $stanza->exists('session', NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
_debug("no catch");
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) {
|
jaxl/JAXL | a3b9490056cbf84a9b4624942d76d9c2f6aba8fa | Text of the LICENSE file corresponds to BSD-3-Clause | diff --git a/composer.json b/composer.json
index 2aeb5d9..31c2289 100644
--- a/composer.json
+++ b/composer.json
@@ -1,49 +1,49 @@
{
"name": "jaxl/jaxl",
"type": "library",
"description": "Jaxl - Async, Non-Blocking, Event based Networking Library in PHP.",
"keywords": ["xmpp", "jabber", "http", "asynchronous", "non blocking", "event loop", "php", "jaxl", "abhinavsingh"],
"homepage": "http://jaxl.readthedocs.org/en/latest/index.html",
- "license": "MIT",
+ "license": "BSD-3-Clause",
"support": {
"forum": "https://groups.google.com/forum/#!forum/jaxl",
"issues": "https://github.com/jaxl/JAXL/issues",
"source": "https://github.com/jaxl/JAXL"
},
"authors": [
{
"name": "Abhinavsingh",
"homepage": "https://abhinavsingh.com/"
}
],
"require": {
"php": ">=5.2.4",
"ext-curl": "*",
"ext-hash": "*",
"ext-json": "*",
"ext-libxml": "*",
"ext-openssl": "*",
"ext-pcre": "*",
"ext-sockets": "*"
},
"require-dev": {
"phpunit/phpunit": "^3.7.0",
"squizlabs/php_codesniffer": "*"
},
"suggest": {
"ext-pcntl": "Interrupt JAXL with signals"
},
"autoload": {
"classmap": [
"core",
"http",
"xep",
"xmpp",
"jaxl.php"
],
"exclude-from-classmap": [
"/tests/"
]
},
"bin": ["jaxlctl"]
}
|
jaxl/JAXL | 8c39de44440fde1e4d9b938037ba003e4f3bbc6c | Fix camel case names | diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php
index c520b0f..61ebb18 100644
--- a/examples/http_pre_bind.php
+++ b/examples/http_pre_bind.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
// http pre bind php script
$body = file_get_contents("php://input");
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (!isset($attrs['to']) &&
!isset($attrs['rid']) &&
!isset($attrs['wait']) &&
!isset($attrs['hold'])
) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
$to = (string)$attrs['to'];
$rid = (int)$attrs['rid'];
$wait = (int)$attrs['wait'];
$hold = (int)$attrs['hold'];
list($host, $port) = JAXLUtil::get_dns_srv($to);
$client = new JAXL(array(
'domain' => $to,
'host' => $host,
'port' => $port,
'bosh_url' => 'http://localhost:5280/http-bind',
'bosh_rid' => $rid,
'bosh_wait' => $wait,
'bosh_hold' => $hold,
'auth_type' => 'ANONYMOUS',
'log_level' => JAXLLogger::INFO
));
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
echo sprintf(
'<body xmlns="%s" sid="%s" rid="%s" jid="%s"/>',
- XEP_0206::NS_HTTP_BIND,
+ XEP0206::NS_HTTP_BIND,
$client->xeps['0206']->sid,
$client->xeps['0206']->rid,
$client->full_jid->to_string()
);
exit;
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
_info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php
index f279272..27b401f 100644
--- a/examples/muc_log_bot.php
+++ b/examples/muc_log_bot.php
@@ -1,147 +1,147 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 5) {
echo "Usage: $argv[0] host jid pass [email protected] nickname".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[2],
'pass' => $argv[3],
'host' => $argv[1],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0045', // MUC
'0203', // Delayed Delivery
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$_room_full_jid = $argv[4]."/".$argv[5];
$room_full_jid = new XMPPJid($_room_full_jid);
$client->add_cb('on_auth_success', function () {
global $client, $room_full_jid;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// join muc room
$client->xeps['0045']->join_room($room_full_jid);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_groupchat_message', function ($stanza) {
global $client;
$from = new XMPPJid($stanza->from);
- $delay = $stanza->exists('delay', XEP_0203::NS_DELAYED_DELIVERY);
+ $delay = $stanza->exists('delay', XEP0203::NS_DELAYED_DELIVERY);
if ($from->resource) {
echo sprintf(
"message stanza rcvd from %s saying... %s, %s".PHP_EOL,
$from->resource,
$stanza->body,
$delay ? "delay timestamp ".$delay->attrs['stamp'] : "timestamp ".gmdate("Y-m-dTH:i:sZ")
);
} else {
$subject = $stanza->exists('subject');
if ($subject) {
echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".
$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL;
}
}
});
$client->add_cb('on_presence_stanza', function ($stanza) {
global $client, $room_full_jid;
$from = new XMPPJid($stanza->from);
// self-stanza received, we now have complete room roster
if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) {
- if (($x = $stanza->exists('x', XEP_0045::NS_MUC.'#user')) !== false) {
+ if (($x = $stanza->exists('x', XEP0045::NS_MUC.'#user')) !== false) {
if (($status = $x->exists('status', null, array('code' => '110'))) !== false) {
$item = $x->exists('item');
_info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].
", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']);
} else {
_info("xmlns #user have no x child element");
}
} else {
_warning("=======> odd case 1");
}
} elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) {
// stanza from other users received
- if (($x = $stanza->exists('x', XEP_0045::NS_MUC.'#user')) !== false) {
+ if (($x = $stanza->exists('x', XEP0045::NS_MUC.'#user')) !== false) {
$item = $x->exists('item');
echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".
$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL;
} else {
_warning("=======> odd case 2");
}
} else {
_warning("=======> odd case 3");
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/examples/register_user.php b/examples/register_user.php
index 90f2653..fb6cddf 100644
--- a/examples/register_user.php
+++ b/examples/register_user.php
@@ -1,168 +1,168 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 2) {
echo "Usage: $argv[0] domain".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'log_level' => JAXLLogger::DEBUG
));
$client->require_xep(array(
'0077' // InBand Registration
));
//
// below are two states which become part of
// our client's xmpp_stream lifecycle
// consider as if these methods are directly
// inside xmpp_stream state machine
//
// Note: $stanza = $args[0] is an instance of
// JAXLXml in xmpp_stream state methods,
// it is yet not ready for easy access
// patterns available on XMPPStanza instances
//
$form = array();
function wait_for_register_response($event, $args)
{
global $client, $form;
if ($event == 'stanza_cb') {
$stanza = $args[0];
if ($stanza->name == 'iq') {
$form['type'] = $stanza->attrs['type'];
if ($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
} elseif ($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo sprintf(
"registration failed with error code: %s and type: %s".PHP_EOL,
$error->attrs['code'],
$error->attrs['type']
);
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
}
}
} else {
_notice("unhandled event $event rcvd");
}
}
function wait_for_register_form($event, $args)
{
global $client, $form;
$stanza = $args[0];
- $query = $stanza->exists('query', XEP_0077::NS_INBAND_REGISTER);
+ $query = $stanza->exists('query', XEP0077::NS_INBAND_REGISTER);
if ($query) {
$instructions = $query->exists('instructions');
if ($instructions) {
echo $instructions->text.PHP_EOL;
}
foreach ($query->childrens as $k => $child) {
if ($child->name != 'instructions') {
$form[$child->name] = readline($child->name.":");
}
}
$client->xeps['0077']->set_form($stanza->attrs['from'], $form);
return "wait_for_register_response";
} else {
$client->end_stream();
return "logged_out";
}
}
//
// add necessary event callbacks here
//
$client->add_cb('on_stream_features', function ($stanza) {
global $client, $argv;
$client->xeps['0077']->get_form($argv[1]);
return "wait_for_register_form";
});
$client->add_cb('on_disconnect', function () {
global $form;
_info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
});
//
// finally start configured xmpp stream
//
$client->start();
//
// if registration was successful
// try to connect with newly registered account
//
if ($form['type'] == 'result') {
_info("connecting newly registered user account");
$client = new JAXL(array(
'jid' => $form['username'].'@'.$argv[1],
'pass' => $form['password'],
'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
$client->set_status('Available');
});
$client->start();
}
echo "done".PHP_EOL;
diff --git a/examples/subscriber.php b/examples/subscriber.php
index 13d15ea..fec9268 100644
--- a/examples/subscriber.php
+++ b/examples/subscriber.php
@@ -1,97 +1,97 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require dirname(__FILE__) . '/_bootstrap.php';
if ($argc < 3) {
echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// subscribe
$client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node');
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_headline_message', function ($stanza) {
global $client;
- if (($event = $stanza->exists('event', XEP_0060::NS_PUBSUB.'#event'))) {
+ if (($event = $stanza->exists('event', XEP0060::NS_PUBSUB.'#event'))) {
_info("got pubsub event");
} else {
_warning("unknown headline message rcvd");
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done".PHP_EOL;
diff --git a/phpcs.xml b/phpcs.xml
index 966df62..8796a20 100644
--- a/phpcs.xml
+++ b/phpcs.xml
@@ -1,45 +1,40 @@
<?xml version="1.0"?>
<ruleset name="JAXL">
<description>The JAXL coding standard (based on PSR-2 excluding some rules).</description>
<file>core</file>
<file>examples</file>
<file>http</file>
<file>tests</file>
<file>xep</file>
<file>xmpp</file>
<file>jaxl.php</file>
<file>jaxlctl</file>
<arg value="p"/>
<arg name="encoding" value="utf-8"/>
<!-- Include the whole PSR-2 standard -->
<rule ref="PSR2"/>
<rule ref="Generic.Files.LineLength">
<properties>
<property name="lineLimit" value="120"/>
</properties>
</rule>
- <!-- TODO: Rename XEP_NNNN classes then remove this rule. -->
- <rule ref="Squiz.Classes.ValidClassName.NotCamelCaps">
- <severity>0</severity>
- </rule>
-
<!-- TODO: Move to PHP 5.3+ with namespaces then remove this rule. -->
<rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
<severity>0</severity>
</rule>
<!-- TODO: Register autoload (spl_autoload_register), remove include and require everywhere then remove this rule. -->
<rule ref="PSR1.Files.SideEffects.FoundWithSymbols">
<severity>0</severity>
</rule>
<!-- TODO: Rename all methods then remove this rule. -->
<rule ref="PSR1.Methods.CamelCapsMethodName.NotCamelCaps">
<severity>0</severity>
</rule>
</ruleset>
diff --git a/src/JAXL/jaxl.php b/src/JAXL/jaxl.php
index 83dbd82..e0b890e 100644
--- a/src/JAXL/jaxl.php
+++ b/src/JAXL/jaxl.php
@@ -1,858 +1,858 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : getcwd()."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
$this->cfg['multi_client'] = isset($this->cfg['multi_client']) ? $this->cfg['multi_client'] : false;
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
- * @return JAXLSocketClient|XEP_0206
+ * @return JAXLSocketClient|XEP0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
- $classname = 'XEP_'.$xep;
+ $classname = 'XEP'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
- $query = $stanza->exists('query', XEP_0030::NS_DISCO_INFO);
+ $query = $stanza->exists('query', XEP0030::NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
- $query = $stanza->exists('query', XEP_0030::NS_DISCO_ITEMS);
+ $query = $stanza->exists('query', XEP0030::NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
}
diff --git a/src/JAXL/xep/xep_0030.php b/src/JAXL/xep/xep_0030.php
index 0bc810b..69313f4 100644
--- a/src/JAXL/xep/xep_0030.php
+++ b/src/JAXL/xep/xep_0030.php
@@ -1,96 +1,96 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP_0030 extends XMPPXep
+class XEP0030 extends XMPPXep
{
const NS_DISCO_INFO = 'http://jabber.org/protocol/disco#info';
const NS_DISCO_ITEMS = 'http://jabber.org/protocol/disco#items';
//
// abstract method
//
public function init()
{
return array(
);
}
//
// api methods
//
public function get_info_pkt($entity_jid)
{
return $this->jaxl->get_iq_pkt(
array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid),
new JAXLXml('query', self::NS_DISCO_INFO)
);
}
public function get_info($entity_jid, $callback = null)
{
$pkt = $this->get_info_pkt($entity_jid);
if ($callback) {
$this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback);
}
$this->jaxl->send($pkt);
}
public function get_items_pkt($entity_jid)
{
return $this->jaxl->get_iq_pkt(
array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid),
new JAXLXml('query', self::NS_DISCO_ITEMS)
);
}
public function get_items($entity_jid, $callback = null)
{
$pkt = $this->get_items_pkt($entity_jid);
if ($callback) {
$this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback);
}
$this->jaxl->send($pkt);
}
//
// event callbacks
//
}
diff --git a/src/JAXL/xep/xep_0045.php b/src/JAXL/xep/xep_0045.php
index 532b798..303e274 100644
--- a/src/JAXL/xep/xep_0045.php
+++ b/src/JAXL/xep/xep_0045.php
@@ -1,121 +1,121 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP_0045 extends XMPPXep
+class XEP0045 extends XMPPXep
{
const NS_MUC = 'http://jabber.org/protocol/muc';
//
// abstract method
//
public function init()
{
return array();
}
public function send_groupchat($room_jid, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'groupchat',
'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid),
'from'=>$this->jaxl->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->jaxl->send($msg);
}
//
// api methods (occupant use case)
//
// room_full_jid simply means room jid with nick name as resource
public function get_join_room_pkt($room_full_jid, array $options)
{
$pkt = $this->jaxl->get_pres_pkt(
array(
'from'=>$this->jaxl->full_jid->to_string(),
'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid),
'id' => (isset($options['id'])) ? $options['id'] : uniqid()
)
);
$x = $pkt->c('x', self::NS_MUC);
if (isset($options['no_history'])) {
$x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0))->up();
}
if (isset($options['password'])) {
$x->c('password')->t($options['password'])->up();
}
return $x;
}
public function join_room($room_full_jid, array $options = array())
{
$pkt = $this->get_join_room_pkt($room_full_jid, $options);
$this->jaxl->send($pkt);
}
public function get_leave_room_pkt($room_full_jid)
{
return $this->jaxl->get_pres_pkt(array(
'type' => 'unavailable',
'from' => $this->jaxl->full_jid->to_string(),
'to' => ($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid
));
}
public function leave_room($room_full_jid)
{
$pkt = $this->get_leave_room_pkt($room_full_jid);
$this->jaxl->send($pkt);
}
//
// api methods (moderator use case)
//
//
// event callbacks
//
}
diff --git a/src/JAXL/xep/xep_0060.php b/src/JAXL/xep/xep_0060.php
index 8f7b7f1..55ff357 100644
--- a/src/JAXL/xep/xep_0060.php
+++ b/src/JAXL/xep/xep_0060.php
@@ -1,146 +1,146 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP_0060 extends XMPPXep
+class XEP0060 extends XMPPXep
{
const NS_PUBSUB = 'http://jabber.org/protocol/pubsub';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods (entity use case)
//
//
// api methods (subscriber use case)
//
public function get_subscribe_pkt($service, $node, $jid = null)
{
$child = new JAXLXml('pubsub', self::NS_PUBSUB);
$child->c(
'subscribe',
null,
array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string()))
);
return $this->get_iq_pkt($service, $child);
}
public function subscribe($service, $node, $jid = null)
{
$this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid));
}
public function unsubscribe()
{
}
public function get_subscription_options()
{
}
public function set_subscription_options()
{
}
public function get_node_items()
{
}
//
// api methods (publisher use case)
//
public function get_publish_item_pkt($service, $node, $item)
{
$child = new JAXLXml('pubsub', self::NS_PUBSUB);
$child->c('publish', null, array('node' => $node));
$child->cnode($item);
return $this->get_iq_pkt($service, $child);
}
public function publish_item($service, $node, $item)
{
$this->jaxl->send($this->get_publish_item_pkt($service, $node, $item));
}
public function delete_item()
{
}
//
// api methods (owner use case)
//
public function get_create_node_pkt($service, $node)
{
$child = new JAXLXml('pubsub', self::NS_PUBSUB);
$child->c('create', null, array('node' => $node));
return $this->get_iq_pkt($service, $child);
}
public function create_node($service, $node)
{
$this->jaxl->send($this->get_create_node_pkt($service, $node));
}
//
// event callbacks
//
//
// local methods
//
// this always add attrs
protected function get_iq_pkt($service, $child, $type = 'set')
{
return $this->jaxl->get_iq_pkt(
array('type' => $type, 'from' => $this->jaxl->full_jid->to_string(), 'to' => $service),
$child
);
}
}
diff --git a/src/JAXL/xep/xep_0077.php b/src/JAXL/xep/xep_0077.php
index 84050bd..2da005b 100644
--- a/src/JAXL/xep/xep_0077.php
+++ b/src/JAXL/xep/xep_0077.php
@@ -1,84 +1,84 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP_0077 extends XMPPXep
+class XEP0077 extends XMPPXep
{
const NS_FEATURE_REGISTER = 'http://jabber.org/features/iq-register';
const NS_INBAND_REGISTER = 'jabber:iq:register';
//
// abstract method
//
public function init()
{
return array(
);
}
//
// api methods
//
public function get_form_pkt($domain)
{
return $this->jaxl->get_iq_pkt(
array('to' => $domain, 'type' => 'get'),
new JAXLXml('query', self::NS_INBAND_REGISTER)
);
}
public function get_form($domain)
{
$this->jaxl->send($this->get_form_pkt($domain));
}
public function set_form($domain, array $form)
{
$query = new JAXLXml('query', self::NS_INBAND_REGISTER);
foreach ($form as $k => $v) {
$query->c($k, null, array(), $v)->up();
}
$pkt = $this->jaxl->get_iq_pkt(
array('to' => $domain, 'type' => 'set'),
$query
);
$this->jaxl->send($pkt);
}
}
diff --git a/src/JAXL/xep/xep_0114.php b/src/JAXL/xep/xep_0114.php
index 0211651..14c0db7 100644
--- a/src/JAXL/xep/xep_0114.php
+++ b/src/JAXL/xep/xep_0114.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP_0114 extends XMPPXep
+class XEP0114 extends XMPPXep
{
const NS_JABBER_COMPONENT_ACCEPT = 'jabber:component:accept';
//
// abstract method
//
public function init()
{
return array(
'on_connect' => 'start_stream',
'on_stream_start' => 'start_handshake',
'on_handshake_stanza' => 'logged_in',
'on_error_stanza' => 'logged_out'
);
}
//
// event callbacks
//
public function start_stream()
{
$xml = sprintf(
'<stream:stream xmlns:stream="%s" to="%s" xmlns="%s">',
XMPP::NS_XMPP,
$this->jaxl->jid->to_string(),
self::NS_JABBER_COMPONENT_ACCEPT
);
$this->jaxl->send_raw($xml);
}
public function start_handshake($stanza)
{
_debug("starting component handshake");
$id = $stanza->id;
$hash = strtolower(sha1($id.$this->jaxl->pass));
$stanza = new JAXLXml('handshake', null, $hash);
$this->jaxl->send($stanza);
}
public function logged_in($stanza)
{
_debug("component handshake complete");
$this->jaxl->handle_auth_success();
return array("logged_in", 1);
}
public function logged_out($stanza)
{
if ($stanza->name == "error" && $stanza->ns == XMPP::NS_XMPP) {
$reason = $stanza->childrens[0]->name;
$this->jaxl->handle_auth_failure($reason);
$this->jaxl->send_end_stream();
return array("logged_out", 0);
} else {
_debug("uncatched stanza received in logged_out");
}
}
}
diff --git a/src/JAXL/xep/xep_0115.php b/src/JAXL/xep/xep_0115.php
index b39336f..e7b081a 100644
--- a/src/JAXL/xep/xep_0115.php
+++ b/src/JAXL/xep/xep_0115.php
@@ -1,72 +1,72 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP_0115 extends XMPPXep
+class XEP0115 extends XMPPXep
{
const NS_CAPS = 'http://jabber.org/protocol/caps';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods
//
public function get_caps_pkt($cat, $type, $lang, $name, $node, $features)
{
asort($features);
$S = $cat.'/'.$type.'/'.$lang.'/'.$name.'<';
foreach ($features as $feature) {
$S .= $feature.'<';
}
$ver = base64_encode(sha1($S, true));
$stanza = new JAXLXml('c', self::NS_CAPS, array('hash' => 'sha1', 'node' => $node, 'ver' => $ver));
return $stanza;
}
//
// event callbacks
//
}
diff --git a/src/JAXL/xep/xep_0199.php b/src/JAXL/xep/xep_0199.php
index a9270d1..3fd3f13 100644
--- a/src/JAXL/xep/xep_0199.php
+++ b/src/JAXL/xep/xep_0199.php
@@ -1,60 +1,60 @@
<?php
-class XEP_0199 extends XMPPXep
+class XEP0199 extends XMPPXep
{
const NS_XMPP_PING = 'urn:xmpp:ping';
//
// abstract method
//
public function init()
{
return array(
'on_auth_success' => 'on_auth_success',
'on_get_iq' => 'on_xmpp_ping'
);
}
//
// api methods
//
public function get_ping_pkt()
{
$attrs = array(
'type' => 'get',
'from' => $this->jaxl->full_jid->to_string(),
'to' => $this->jaxl->full_jid->domain
);
return $this->jaxl->get_iq_pkt(
$attrs,
new JAXLXml('ping', self::NS_XMPP_PING)
);
}
public function ping()
{
$this->jaxl->send($this->get_ping_pkt());
}
//
// event callbacks
//
public function on_auth_success()
{
JAXLLoop::$clock->call_fun_periodic(30 * pow(10, 6), array(&$this, 'ping'));
}
public function on_xmpp_ping($stanza)
{
if ($stanza->exists('ping', self::NS_XMPP_PING)) {
$stanza->type = "result";
$stanza->to = $stanza->from;
$stanza->from = $this->jaxl->full_jid->to_string();
$this->jaxl->send($stanza);
}
}
}
diff --git a/src/JAXL/xep/xep_0203.php b/src/JAXL/xep/xep_0203.php
index 7aa6b89..265bb12 100644
--- a/src/JAXL/xep/xep_0203.php
+++ b/src/JAXL/xep/xep_0203.php
@@ -1,59 +1,59 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP_0203 extends XMPPXep
+class XEP0203 extends XMPPXep
{
const NS_DELAYED_DELIVERY = 'urn:xmpp:delay';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods
//
//
// event callbacks
//
}
diff --git a/src/JAXL/xep/xep_0206.php b/src/JAXL/xep/xep_0206.php
index 9d39656..12a8830 100644
--- a/src/JAXL/xep/xep_0206.php
+++ b/src/JAXL/xep/xep_0206.php
@@ -1,268 +1,268 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP_0206 extends XMPPXep
+class XEP0206 extends XMPPXep
{
const NS_HTTP_BIND = 'http://jabber.org/protocol/httpbind';
const NS_BOSH = 'urn:xmpp:xbosh';
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
//
// event callbacks
//
/**
* @param JAXLXml|XMPPStanza|string $body
*/
public function send($body)
{
if (is_object($body)) {
$body = $body->to_string();
} else {
if (substr($body, 0, 15) == '<stream:stream ') {
$this->restarted = true;
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
'xmlns:xmpp' => self::NS_BOSH
));
$body = $body->to_string();
} elseif (substr($body, 0, 16) == '</stream:stream>') {
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
$body = $body->to_string();
} else {
$body = $this->wrap($body);
}
}
_debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
_debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
_debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
_debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
_error("no ch found");
exit;
}
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.
self::NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
$this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
$this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
$this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
'xmlns:xmpp' => self::NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
if (isset($this->jaxl->cfg['jid'])) {
$attrs['from'] = $this->jaxl->cfg['jid'];
}
$body = new JAXLXml('body', self::NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
$body = new JAXLXml('body', self::NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
_debug("disconnecting");
}
}
diff --git a/src/JAXL/xep/xep_0249.php b/src/JAXL/xep/xep_0249.php
index 7e275c2..96bdad1 100644
--- a/src/JAXL/xep/xep_0249.php
+++ b/src/JAXL/xep/xep_0249.php
@@ -1,95 +1,95 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-class XEP_0249 extends XMPPXep
+class XEP0249 extends XMPPXep
{
const NS_DIRECT_MUC_INVITATION = 'jabber:x:conference';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods
//
public function get_invite_pkt(
$to_bare_jid,
$room_jid,
$password = null,
$reason = null,
$thread = null,
$continue = null
) {
$xattrs = array('jid' => $room_jid);
if ($password) {
$xattrs['password'] = $password;
}
if ($reason) {
$xattrs['reason'] = $reason;
}
if ($thread) {
$xattrs['thread'] = $thread;
}
if ($continue) {
$xattrs['continue'] = $continue;
}
return $this->jaxl->get_msg_pkt(
array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid),
null,
null,
null,
new JAXLXml('x', self::NS_DIRECT_MUC_INVITATION, $xattrs)
);
}
public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null)
{
$this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue));
}
//
// event callbacks
//
}
diff --git a/src/JAXL/xmpp/xmpp_stream.php b/src/JAXL/xmpp/xmpp_stream.php
index 330db59..29b0f5a 100644
--- a/src/JAXL/xmpp/xmpp_stream.php
+++ b/src/JAXL/xmpp/xmpp_stream.php
@@ -1,605 +1,605 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
- * @var JAXLSocketClient|XEP_0206
+ * @var JAXLSocketClient|XEP0206
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
- * @param JAXLSocketClient|XEP_0206 $transport
+ * @param JAXLSocketClient|XEP0206 $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
$jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//_debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
_error("got invalid return value from state handler '".$this->state."', sending end stream...");
$this->send_end_stream();
$this->state = "logged_out";
_notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers");
}
/**
* @param JAXLXml|XMPPStanza $stanza
*/
public function send($stanza)
{
$this->trans->send($stanza->to_string());
}
/**
* @param string $data
*/
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.XMPP::NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.XMPP::NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.XMPP::NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', XMPP::NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', XMPP::NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', XMPP::NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', XMPP::NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
_debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', XMPP::NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', XMPP::NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//_debug("stream started");
return "wait_for_stream_features";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', XMPP::NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', XMPP::NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', XMPP::NS_BIND) ? true : false;
$sess = $stanza->exists('session', XMPP::NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', XMPP::NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
_debug("no catch");
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == XMPP::NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'compressed' && $stanza->ns == XMPP::NS_COMPRESSION_PROTOCOL) {
diff --git a/tests/XMPPJidTest.php b/tests/XMPPJidTest.php
index 2c4bd5a..2b79c74 100644
--- a/tests/XMPPJidTest.php
+++ b/tests/XMPPJidTest.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* @author abhinavsingh
*
*/
class XMPPJidTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider jidPositiveProvider
*/
public function test_xmpp_jid_construct($jidText)
{
$jid = new XMPPJid($jidText);
$this->assertEquals($jidText, $jid->to_string());
}
public function jidPositiveProvider()
{
return array(
array('domain'),
array('domain.tld'),
array('1@domain'),
array('[email protected]'),
array('domain/res'),
array('domain.tld/res'),
array('1@domain/res'),
array('[email protected]/res'),
array('component.domain.tld'),
array('[email protected]/res'),
array('[email protected]/@res'),
array('[email protected]//res')
);
}
/**
* @dataProvider jidNegativeProvider
* @expectedException InvalidArgumentException
- * @requires function XEP_0029::validateJID
+ * @requires function XEP0029::validateJID
*/
public function testJidNegative($jidText)
{
$jid = new XMPPJid($jidText);
}
public function jidNegativeProvider()
{
return array(
array('"@domain'),
array('&@domain'),
array("'@domain"),
array('/@domain'),
array(':@domain'),
array('<@domain'),
array('>@domain'),
array('@@domain'),
array("\x7F" . '@domain'),
array("\xFF\xFE" . '@domain'),
array("\xFF\xFF" . '@domain')
);
}
}
|
jaxl/JAXL | d935bb1064bb7c6ad4eb88add6618b16f1b62a64 | Separate HTTPDispatchRule and HTTPDispatcher | diff --git a/src/JAXL/http/http_dispatch_rule.php b/src/JAXL/http/http_dispatch_rule.php
new file mode 100644
index 0000000..aa8f0d7
--- /dev/null
+++ b/src/JAXL/http/http_dispatch_rule.php
@@ -0,0 +1,84 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+//
+// (optionally) set an array of url dispatch rules
+// each dispatch rule is defined by an array of size 4 like:
+// array($callback, $pattern, $methods, $extra), where
+// $callback the method which will be called if this rule matches
+// $pattern regular expression to match request path
+// $methods list of allowed methods for this rule
+// pass boolean true to allow all http methods
+// if omitted or an empty array() is passed (which actually doesnt make sense)
+// by default 'GET' will be the method allowed on this rule
+// $extra reserved for future (you can totally omit this as of now)
+//
+class HTTPDispatchRule
+{
+
+ // match callback
+ public $cb = null;
+
+ // regexp to match on request path
+ public $pattern = null;
+
+ // methods to match upon
+ // add atleast 1 method for this rule to work
+ public $methods = null;
+
+ // other matching rules
+ public $extra = array();
+
+ public function __construct($cb, $pattern, array $methods = array('GET'), array $extra = array())
+ {
+ $this->cb = $cb;
+ $this->pattern = $pattern;
+ $this->methods = $methods;
+ $this->extra = $extra;
+ }
+
+ public function match($path, $method)
+ {
+ if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) {
+ if (in_array($method, $this->methods)) {
+ return $matches;
+ }
+ }
+ return false;
+ }
+}
diff --git a/src/JAXL/http/http_dispatcher.php b/src/JAXL/http/http_dispatcher.php
index 166b2f9..441a498 100644
--- a/src/JAXL/http/http_dispatcher.php
+++ b/src/JAXL/http/http_dispatcher.php
@@ -1,135 +1,88 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-//
-// (optionally) set an array of url dispatch rules
-// each dispatch rule is defined by an array of size 4 like:
-// array($callback, $pattern, $methods, $extra), where
-// $callback the method which will be called if this rule matches
-// $pattern regular expression to match request path
-// $methods list of allowed methods for this rule
-// pass boolean true to allow all http methods
-// if omitted or an empty array() is passed (which actually doesnt make sense)
-// by default 'GET' will be the method allowed on this rule
-// $extra reserved for future (you can totally omit this as of now)
-//
-class HTTPDispatchRule
-{
-
- // match callback
- public $cb = null;
-
- // regexp to match on request path
- public $pattern = null;
-
- // methods to match upon
- // add atleast 1 method for this rule to work
- public $methods = null;
-
- // other matching rules
- public $extra = array();
-
- public function __construct($cb, $pattern, array $methods = array('GET'), array $extra = array())
- {
- $this->cb = $cb;
- $this->pattern = $pattern;
- $this->methods = $methods;
- $this->extra = $extra;
- }
-
- public function match($path, $method)
- {
- if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) {
- if (in_array($method, $this->methods)) {
- return $matches;
- }
- }
- return false;
- }
-}
-
class HTTPDispatcher
{
protected $rules = array();
public function __construct()
{
$this->rules = array();
}
public function add_rule($rule)
{
$s = count($rule);
if ($s > 4) {
_debug("invalid rule");
return;
}
// fill up defaults
if ($s == 3) {
$rule[] = array();
} elseif ($s == 2) {
$rule[] = array('GET');
$rule[] = array();
} else {
_debug("invalid rule");
return;
}
$this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]);
}
public function dispatch($request)
{
foreach ($this->rules as $rule) {
//_debug("matching $request->path with pattern $rule->pattern");
if (($matches = $rule->match($request->path, $request->method)) !== false) {
_debug("matching rule found, dispatching");
$params = array($request);
// TODO: a bad way to restrict on 'pk', fix me for generalization
if (isset($matches['pk'])) {
$params[] = $matches['pk'];
}
call_user_func_array($rule->cb, $params);
return true;
}
}
return false;
}
}
|
jaxl/JAXL | e621c9bf602e6ca9dd5c1a06d4e71d50bf3928e7 | Separate JAXLCtl class and CLI logic | diff --git a/jaxlctl b/jaxlctl
index 9b2e37f..ee6e758 100755
--- a/jaxlctl
+++ b/jaxlctl
@@ -1,221 +1,78 @@
#!/usr/bin/env php
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
error_reporting(E_ALL | E_STRICT);
if (PHP_SAPI !== 'cli') {
echo 'Warning: script should be invoked via the CLI version of PHP, not the '.PHP_SAPI.' SAPI'.PHP_EOL;
}
if (!ini_get('date.timezone')) {
ini_set('date.timezone', 'UTC');
}
foreach (array(
// Run from ./JAXL-source/jaxlctl
dirname(__FILE__) . '/vendor/autoload.php',
// Run from /some-project/bin/jaxlctl
dirname(__FILE__) . '/../vendor/autoload.php',
// Run from /some-project/vendor/jaxl/jaxl/jaxlctl
dirname(__FILE__) . '/../../../vendor/autoload.php'
) as $file) {
if (file_exists($file)) {
require $file;
break;
}
}
unset($file);
$params = $argv;
$exe = array_shift($params);
$command = array_shift($params);
JAXLLogger::$level = JAXLLogger::INFO;
-// TODO: an abstract JAXLCtlCommand class
-// with seperate class per command
-// a mechanism to register new commands
-class JAXLCtl
-{
-
- protected $ipc = null;
-
- protected $buffer = '';
- protected $buffer_cb = null;
- protected $cli = null;
- public $dots = "....... ";
-
- protected $symbols = array();
-
- public function __construct($command, $params)
- {
- global $exe;
-
- if (method_exists($this, $command)) {
- $r = call_user_func_array(array(&$this, $command), $params);
- if (count($r) == 2) {
- list($buffer_cb, $quit_cb) = $r;
- $this->buffer_cb = $buffer_cb;
- $this->cli = new JAXLCli(array(&$this, 'onTerminalInput'), $quit_cb);
- $this->run();
- } else {
- _colorize("oops! internal command error", JAXLLogger::ERROR);
- exit;
- }
- } else {
- _colorize("error: invalid command '$command' received", JAXLLogger::ERROR);
- _colorize("type '$exe help' for list of available commands", JAXLLogger::NOTICE);
- exit;
- }
- }
-
- public function run()
- {
- JAXLCli::prompt();
- JAXLLoop::run();
- }
-
- public function onTerminalInput($raw)
- {
- $raw = trim($raw);
- $last = substr($raw, -1, 1);
-
- if ($last == ";") {
- // dispatch to buffer callback
- call_user_func($this->buffer_cb, $this->buffer.$raw);
- $this->buffer = '';
- } elseif ($last == '\\') {
- $this->buffer .= substr($raw, 0, -1);
- echo $this->dots;
- } else {
- // buffer command
- $this->buffer .= $raw."; ";
- echo $this->dots;
- }
- }
-
- public static function printHelp()
- {
- global $exe;
- _colorize("Usage: $exe command [options...]".PHP_EOL, JAXLLogger::INFO);
- _colorize("Commands:", JAXLLogger::NOTICE);
- _colorize(" help This help text", JAXLLogger::DEBUG);
- _colorize(" debug Attach a debug console to a running JAXL daemon", JAXLLogger::DEBUG);
- _colorize(" shell Open up Jaxl shell emulator", JAXLLogger::DEBUG);
- echo PHP_EOL;
- }
-
- protected function help()
- {
- JAXLCtl::printHelp();
- exit;
- }
-
- //
- // shell command
- //
-
- protected function shell()
- {
- return array(array(&$this, 'onShellInput'), array(&$this, 'onShellQuit'));
- }
-
- private function eval_($raw, $symbols)
- {
- extract($symbols);
-
- eval($raw);
- $g = get_defined_vars();
-
- unset($g['raw']);
- unset($g['symbols']);
- return $g;
- }
-
- public function onShellInput($raw)
- {
- $this->symbols = $this->eval_($raw, $this->symbols);
- JAXLCli::prompt();
- }
-
- public function onShellQuit()
- {
- exit;
- }
-
- //
- // debug command
- //
-
- protected function debug($sock_path)
- {
- $this->ipc = new JAXLSocketClient();
- $this->ipc->set_callback(array(&$this, 'onDebugResponse'));
- $this->ipc->connect('unix://'.$sock_path);
- return array(array(&$this, 'onDebugInput'), array(&$this, 'onDebugQuit'));
- }
-
- public function onDebugResponse($raw)
- {
- $ret = unserialize($raw);
- print_r($ret);
- echo PHP_EOL;
- JAXLCli::prompt();
- }
-
- public function onDebugInput($raw)
- {
- $this->ipc->send($this->buffer.$raw);
- }
-
- public function onDebugQuit()
- {
- $this->ipc->disconnect();
- exit;
- }
-}
-
// we atleast need a command argument
if ($argc < 2) {
JAXLCtl::printHelp();
exit;
}
$ctl = new JAXLCtl($command, $params);
echo "done".PHP_EOL;
diff --git a/src/JAXL/jaxlctl.php b/src/JAXL/jaxlctl.php
new file mode 100755
index 0000000..82e649d
--- /dev/null
+++ b/src/JAXL/jaxlctl.php
@@ -0,0 +1,180 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+// TODO: an abstract JAXLCtlCommand class
+// with seperate class per command
+// a mechanism to register new commands
+class JAXLCtl
+{
+
+ protected $ipc = null;
+
+ protected $buffer = '';
+ protected $buffer_cb = null;
+ protected $cli = null;
+ public $dots = "....... ";
+
+ protected $symbols = array();
+
+ public function __construct($command, $params)
+ {
+ global $exe;
+
+ if (method_exists($this, $command)) {
+ $r = call_user_func_array(array(&$this, $command), $params);
+ if (count($r) == 2) {
+ list($buffer_cb, $quit_cb) = $r;
+ $this->buffer_cb = $buffer_cb;
+ $this->cli = new JAXLCli(array(&$this, 'onTerminalInput'), $quit_cb);
+ $this->run();
+ } else {
+ _colorize("oops! internal command error", JAXLLogger::ERROR);
+ exit;
+ }
+ } else {
+ _colorize("error: invalid command '$command' received", JAXLLogger::ERROR);
+ _colorize("type '$exe help' for list of available commands", JAXLLogger::NOTICE);
+ exit;
+ }
+ }
+
+ public function run()
+ {
+ JAXLCli::prompt();
+ JAXLLoop::run();
+ }
+
+ public function onTerminalInput($raw)
+ {
+ $raw = trim($raw);
+ $last = substr($raw, -1, 1);
+
+ if ($last == ";") {
+ // dispatch to buffer callback
+ call_user_func($this->buffer_cb, $this->buffer.$raw);
+ $this->buffer = '';
+ } elseif ($last == '\\') {
+ $this->buffer .= substr($raw, 0, -1);
+ echo $this->dots;
+ } else {
+ // buffer command
+ $this->buffer .= $raw."; ";
+ echo $this->dots;
+ }
+ }
+
+ public static function printHelp()
+ {
+ global $exe;
+ _colorize("Usage: $exe command [options...]".PHP_EOL, JAXLLogger::INFO);
+ _colorize("Commands:", JAXLLogger::NOTICE);
+ _colorize(" help This help text", JAXLLogger::DEBUG);
+ _colorize(" debug Attach a debug console to a running JAXL daemon", JAXLLogger::DEBUG);
+ _colorize(" shell Open up Jaxl shell emulator", JAXLLogger::DEBUG);
+ echo PHP_EOL;
+ }
+
+ protected function help()
+ {
+ JAXLCtl::printHelp();
+ exit;
+ }
+
+ //
+ // shell command
+ //
+
+ protected function shell()
+ {
+ return array(array(&$this, 'onShellInput'), array(&$this, 'onShellQuit'));
+ }
+
+ private function eval_($raw, $symbols)
+ {
+ extract($symbols);
+
+ eval($raw);
+ $g = get_defined_vars();
+
+ unset($g['raw']);
+ unset($g['symbols']);
+ return $g;
+ }
+
+ public function onShellInput($raw)
+ {
+ $this->symbols = $this->eval_($raw, $this->symbols);
+ JAXLCli::prompt();
+ }
+
+ public function onShellQuit()
+ {
+ exit;
+ }
+
+ //
+ // debug command
+ //
+
+ protected function debug($sock_path)
+ {
+ $this->ipc = new JAXLSocketClient();
+ $this->ipc->set_callback(array(&$this, 'onDebugResponse'));
+ $this->ipc->connect('unix://'.$sock_path);
+ return array(array(&$this, 'onDebugInput'), array(&$this, 'onDebugQuit'));
+ }
+
+ public function onDebugResponse($raw)
+ {
+ $ret = unserialize($raw);
+ print_r($ret);
+ echo PHP_EOL;
+ JAXLCli::prompt();
+ }
+
+ public function onDebugInput($raw)
+ {
+ $this->ipc->send($this->buffer.$raw);
+ }
+
+ public function onDebugQuit()
+ {
+ $this->ipc->disconnect();
+ exit;
+ }
+}
|
jaxl/JAXL | b040350380eb8ba8755888f587b7392ff19c6d3e | Use getcwd() instead of global JAXL_CWD | diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php
index efbb78a..81641bb 100644
--- a/core/jaxl_pipe.php
+++ b/core/jaxl_pipe.php
@@ -1,133 +1,140 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* bidirectional communication pipes for processes
*
* This is how this will be (when complete):
* $pipe = new JAXLPipe() will return an array of size 2
* $pipe[0] represents the read end of the pipe
* $pipe[1] represents the write end of the pipe
*
* Proposed functionality might even change (currently consider this as experimental)
*
* @author abhinavsingh
*
*/
class JAXLPipe
{
protected $perm = 0600;
/** @var callable */
protected $recv_cb = null;
protected $fd = null;
/** @var JAXLSocketClient */
protected $client = null;
/** @var string */
public $name = null;
+ /** @var string */
+ private $pipes_folder = null;
+
/**
* @param string $name
* @param callable $read_cb TODO: Currently not used
*/
public function __construct($name, $read_cb = null)
{
- $pipes_folder = JAXL_CWD.'/.jaxl/pipes';
- if (!is_dir($pipes_folder)) {
- mkdir($pipes_folder);
+ // TODO: see JAXL->cfg['priv_dir']
+ $this->pipes_folder = getcwd().'/.jaxl/pipes';
+ if (!is_dir($this->pipes_folder)) {
+ mkdir($this->pipes_folder, 0777, true);
}
$this->ev = new JAXLEvent();
$this->name = $name;
// TODO: If someone's need the read callback and extends the JAXLPipe
// to obtain it, one can't because this property is private.
$this->read_cb = $read_cb;
$pipe_path = $this->get_pipe_file_path();
if (!file_exists($pipe_path)) {
posix_mkfifo($pipe_path, $this->perm);
$this->fd = fopen($pipe_path, 'r+');
if (!$this->fd) {
_error("unable to open pipe");
} else {
_debug("pipe opened using path $pipe_path");
_notice("Usage: $ echo 'Hello World!' > $pipe_path");
$this->client = new JAXLSocketClient();
$this->client->connect($this->fd);
$this->client->set_callback(array(&$this, 'on_data'));
}
} else {
_error("pipe with name $name already exists");
}
}
public function __destruct()
{
if (is_resource($this->fd)) {
fclose($this->fd);
}
if (file_exists($this->get_pipe_file_path())) {
unlink($this->get_pipe_file_path());
}
_debug("unlinking pipe file");
}
+ /**
+ * @return string
+ */
public function get_pipe_file_path()
{
- return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe';
+ return $this->pipes_folder.'/jaxl_'.$this->name.'.pipe';
}
/**
* @param callable $recv_cb
*/
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function on_data($data)
{
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $data);
}
}
}
diff --git a/docs/users/jaxl_instance.rst b/docs/users/jaxl_instance.rst
index 7e34f9d..ec370c9 100644
--- a/docs/users/jaxl_instance.rst
+++ b/docs/users/jaxl_instance.rst
@@ -1,159 +1,159 @@
.. _jaxl-instance:
JAXL Instance
=============
``JAXL`` instance configure/manage other :ref:`sub-packages <jaxl-instance>`.
It provides an event based callback methodology on various underlying object. Whenever required
``JAXL`` instance will itself perform the configured defaults.
Constructor options
-------------------
#. ``jid``
#. ``pass``
#. ``resource``
If not passed Jaxl will use a random resource value
#. ``auth_type``
DIGEST-MD5, PLAIN (default), CRAM-MD5, ANONYMOUS
#. ``host``
#. ``port``
#. ``bosh_url``
#. ``log_path``
#. ``log_level``
``ERROR``, ``WARNING``, ``NOTICE``, ``INFO`` (default), ``DEBUG``
#. ``force_tls``
#. ``stream_context``
#. ``priv_dir``
Jaxl creates 4 directories names ``log``, ``tmp``, ``run`` and ``sock`` inside a private directory
- which defaults to ``JAXL_CWD.'/.jaxl'``. If this option is passed, it will overwrite default private
+ which defaults to ``getcwd().'/.jaxl'``. If this option is passed, it will overwrite default private
directory.
.. note::
Jaxl currently doesn't check upon the permissions of passed ``priv_dir``. Make sure Jaxl library
have sufficient permissions to create above mentioned directories.
Available Event Callbacks
-------------------------
Following ``$ev`` are available on ``JAXL`` lifecycle for registering callbacks:
#. ``on_connect``
``JAXL`` instance has connected successfully
#. ``on_connect_error``
``JAXL`` instance failed to connect
#. ``on_stream_start``
``JAXL`` instance has successfully initiated XMPP stream with the jabber server
#. ``on_stream_features``
``JAXL`` instance has received supported stream features
#. ``on_auth_success``
authentication successful
#. ``on_auth_failure``
authentication failed
#. ``on_presence_stanza``
``JAXL`` instance has received a presence stanza
#. ``on_{$type}_message``
``JAXL`` instance has received a message stanza. ``$type`` can be ``chat``, ``groupchat``, ``headline``, ``normal``, ``error``
#. ``on_stanza_id_{$id}``
Useful when dealing with iq stanza. This event is fired when ``JAXL`` instance has received response to a particular
xmpp stanza id
#. ``on_{$name}_stanza``
Useful when dealing with custom xmpp stanza
#. ``on_disconnect``
``JAXL`` instance has disconnected from the jabber server
Available Methods
-----------------
Following methods are available on initialized ``JAXL`` instance object:
#. ``get_pid_file_path()``
returns path of ``JAXL`` instance pid file
#. ``get_sock_file_path()``
returns path to ``JAXL`` ipc unix socket domain
#. ``require_xep($xeps = array())``
autoload and initialize passed XEP's
#. ``add_cb($ev, $cb, $priority = 1)``
add a callback to function ``$cb`` on event ``$ev``, returns a reference of added callback
#. ``del_cb($ref)``
delete previously registered event callback
#. ``set_status($status, $show, $priority)``
send a presence status stanza
#. ``send_chat_msg($to, $body, $thread = null, $subject = null)``
send a message stanza of type chat
#. ``get_vcard($jid = null, $cb = null)``
fetch vcard for bare ``$jid``, passed ``$cb`` will be called with received vcard stanza
#. ``get_roster($cb = null)``
fetch roster list of connected jabber client, passed ``$cb`` will be called with received roster stanza
#. ``start($opts = array())``
start configured ``JAXL`` instance, optionally accepts two options specified below:
#. ``--with-debug-shell``
start ``JAXL`` instance and enter an interactive console
#. ``--with-unix-sock``
start ``JAXL`` instance with support for IPC and remote debugging
#. ``send($stanza)``
send an instance of JAXLXml packet over connected socket
#. ``send_raw($data)``
send raw payload over connected socket
#. ``get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)``
#. ``get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)``
#. ``get_iq_pkt($attrs, $payload)``
diff --git a/jaxl.php b/jaxl.php
index b192d06..83dbd82 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,681 +1,679 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
-define('JAXL_CWD', dirname(__FILE__));
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
-
- // create .jaxl directory in JAXL_CWD
- // for our /tmp, /run and /log folders
+
+ // Create .jaxl directory for our /tmp, /run and /log folders
// overwrite these using jaxl config array
- $this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
+ $this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : getcwd()."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
$this->cfg['multi_client'] = isset($this->cfg['multi_client']) ? $this->cfg['multi_client'] : false;
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLSocketClient|XEP_0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$classname = 'XEP_'.$xep;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
|
jaxl/JAXL | 59f937baaff6e7b811c1f383794fc6aedf1ace62 | Use autoload from composer | diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php
index 13b33ed..cb92da3 100644
--- a/core/jaxl_cli.php
+++ b/core/jaxl_cli.php
@@ -1,107 +1,105 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_loop.php';
-
class JAXLCli
{
public static $counter = 0;
private $in = null;
private $quit_cb = null;
private $recv_cb = null;
private $recv_chunk_size = 1024;
public function __construct($recv_cb = null, $quit_cb = null)
{
$this->recv_cb = $recv_cb;
$this->quit_cb = $quit_cb;
// catch read event on stdin
$this->in = fopen('php://stdin', 'r');
stream_set_blocking($this->in, false);
JAXLLoop::watch($this->in, array(
'read' => array(&$this, 'on_read_ready')
));
}
public function __destruct()
{
if (is_resource($this->in)) {
fclose($this->in);
}
}
public function stop()
{
JAXLLoop::unwatch($this->in, array(
'read' => true
));
}
public function on_read_ready($in)
{
$raw = @fread($in, $this->recv_chunk_size);
if (ord($raw) == 10) {
// enter key
JAXLCli::prompt(false);
return;
} elseif (trim($raw) == 'quit') {
$this->stop();
$this->in = null;
if ($this->quit_cb) {
call_user_func($this->quit_cb);
}
return;
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $raw);
}
}
public static function prompt($inc = true)
{
if ($inc) {
++self::$counter;
}
echo "jaxl ".self::$counter."> ";
}
}
diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php
index 5103ad4..1ac58d4 100644
--- a/core/jaxl_loop.php
+++ b/core/jaxl_loop.php
@@ -1,171 +1,168 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_logger.php';
-require_once JAXL_CWD.'/core/jaxl_clock.php';
-
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLLoop
{
/**
* @var JAXLClock
*/
public static $clock = null;
private static $is_running = false;
private static $active_read_fds = 0;
private static $active_write_fds = 0;
private static $read_fds = array();
private static $read_cbs = array();
private static $write_fds = array();
private static $write_cbs = array();
private static $secs = 0;
private static $usecs = 30000;
private function __construct()
{
}
private function __clone()
{
}
public static function watch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
self::$read_fds[$fdid] = $fd;
self::$read_cbs[$fdid] = $opts['read'];
++self::$active_read_fds;
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
self::$write_fds[$fdid] = $fd;
self::$write_cbs[$fdid] = $opts['write'];
++self::$active_write_fds;
}
_debug("Watch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function unwatch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
if (isset(self::$read_fds[$fdid])) {
unset(self::$read_fds[$fdid]);
unset(self::$read_cbs[$fdid]);
--self::$active_read_fds;
}
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
if (isset(self::$write_fds[$fdid])) {
unset(self::$write_fds[$fdid]);
unset(self::$write_cbs[$fdid]);
--self::$active_write_fds;
}
}
_debug("Unwatch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function run()
{
if (!self::$is_running) {
self::$is_running = true;
self::$clock = new JAXLClock();
while ((self::$active_read_fds + self::$active_write_fds) > 0) {
self::select();
}
_debug("no more active fd's to select");
self::$is_running = false;
}
}
public static function select()
{
$read = self::$read_fds;
$write = self::$write_fds;
$except = null;
$changed = @stream_select($read, $write, $except, self::$secs, self::$usecs);
if ($changed === false) {
_error("error in the event loop, shutting down...");
/*foreach (self::$read_fds as $fd) {
if (is_resource($fd)) {
print_r(stream_get_meta_data($fd));
}
}*/
exit;
} elseif ($changed > 0) {
// read callback
foreach ($read as $r) {
$fdid = array_search($r, self::$read_fds);
if (isset(self::$read_fds[$fdid])) {
call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]);
}
}
// write callback
foreach ($write as $w) {
$fdid = array_search($w, self::$write_fds);
if (isset(self::$write_fds[$fdid])) {
call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]);
}
}
self::$clock->tick();
} elseif ($changed === 0) {
//_debug("nothing changed while selecting for read");
self::$clock->tick((self::$secs * pow(10, 6)) + self::$usecs);
}
}
}
diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php
index 22b3c83..efbb78a 100644
--- a/core/jaxl_pipe.php
+++ b/core/jaxl_pipe.php
@@ -1,136 +1,133 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_event.php';
-require_once JAXL_CWD.'/core/jaxl_loop.php';
-
/**
* bidirectional communication pipes for processes
*
* This is how this will be (when complete):
* $pipe = new JAXLPipe() will return an array of size 2
* $pipe[0] represents the read end of the pipe
* $pipe[1] represents the write end of the pipe
*
* Proposed functionality might even change (currently consider this as experimental)
*
* @author abhinavsingh
*
*/
class JAXLPipe
{
protected $perm = 0600;
/** @var callable */
protected $recv_cb = null;
protected $fd = null;
/** @var JAXLSocketClient */
protected $client = null;
/** @var string */
public $name = null;
/**
* @param string $name
* @param callable $read_cb TODO: Currently not used
*/
public function __construct($name, $read_cb = null)
{
$pipes_folder = JAXL_CWD.'/.jaxl/pipes';
if (!is_dir($pipes_folder)) {
mkdir($pipes_folder);
}
$this->ev = new JAXLEvent();
$this->name = $name;
// TODO: If someone's need the read callback and extends the JAXLPipe
// to obtain it, one can't because this property is private.
$this->read_cb = $read_cb;
$pipe_path = $this->get_pipe_file_path();
if (!file_exists($pipe_path)) {
posix_mkfifo($pipe_path, $this->perm);
$this->fd = fopen($pipe_path, 'r+');
if (!$this->fd) {
_error("unable to open pipe");
} else {
_debug("pipe opened using path $pipe_path");
_notice("Usage: $ echo 'Hello World!' > $pipe_path");
$this->client = new JAXLSocketClient();
$this->client->connect($this->fd);
$this->client->set_callback(array(&$this, 'on_data'));
}
} else {
_error("pipe with name $name already exists");
}
}
public function __destruct()
{
if (is_resource($this->fd)) {
fclose($this->fd);
}
if (file_exists($this->get_pipe_file_path())) {
unlink($this->get_pipe_file_path());
}
_debug("unlinking pipe file");
}
public function get_pipe_file_path()
{
return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe';
}
/**
* @param callable $recv_cb
*/
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function on_data($data)
{
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $data);
}
}
}
diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php
index 8c74118..b63670e 100644
--- a/core/jaxl_sock5.php
+++ b/core/jaxl_sock5.php
@@ -1,142 +1,140 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_socket_client.php';
-
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class JAXLSock5
{
/** @var JAXLSocketClient */
private $client = null;
/** @var string */
protected $transport = null;
/** @var string */
protected $ip = null;
/** @var string|int */
protected $port = null;
/**
* @param string $transport
*/
public function __construct($transport = 'tcp')
{
$this->transport = $transport;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function __destruct()
{
}
/**
* @param string $ip
* @param int $port
* @return bool
*/
public function connect($ip, $port = 1080)
{
$this->ip = $ip;
$this->port = $port;
$sock_path = $this->sock_path();
if ($this->client->connect($sock_path)) {
_debug("established connection to $sock_path");
return true;
} else {
_error("unable to connect $sock_path");
return false;
}
}
//
// Three phases of SOCK5
//
// Negotiation pkt consists of 3 part:
// 0x05 => Sock protocol version
// 0x01 => Number of method identifier octet
//
// Following auth methods are defined:
// 0x00 => No authentication required
// 0x01 => GSSAPI
// 0x02 => USERNAME/PASSWORD
// 0x03 to 0x7F => IANA ASSIGNED
// 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS
// 0xFF => NO ACCEPTABLE METHODS
public function negotiate()
{
$pkt = pack("C3", 0x05, 0x01, 0x00);
$this->client->send($pkt);
// enter sub-negotiation state
}
public function relay_request()
{
// enter wait for reply state
}
public function send_data()
{
}
//
// Socket client callback
//
public function on_response($raw)
{
_debug($raw);
}
//
// Private
//
protected function sock_path()
{
return $this->transport.'://'.$this->ip.':'.$this->port;
}
}
diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php
index 7f8d4cb..f36bee9 100644
--- a/core/jaxl_socket_client.php
+++ b/core/jaxl_socket_client.php
@@ -1,265 +1,263 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_loop.php';
-
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLSocketClient
{
private $host = null;
private $port = null;
private $transport = null;
/** @var resource */
private $stream_context = null;
private $blocking = false;
public $fd = null;
public $errno = null;
public $errstr = null;
private $timeout = 10;
private $ibuffer = "";
private $obuffer = "";
private $compressed = false;
private $recv_bytes = 0;
private $send_bytes = 0;
/** @var callable */
private $recv_cb = null;
private $recv_chunk_size = 1024;
private $writing = false;
/**
* @param resource $stream_context Resource created with stream_context_create().
*/
public function __construct($stream_context = null)
{
$this->stream_context = $stream_context;
}
public function __destruct()
{
//_debug("cleaning up xmpp socket...");
$this->disconnect();
}
/**
* Emit on on_read_ready.
*
* @param callable $recv_cb
*/
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
/**
* @param string | resource $socket_path
*/
public function connect($socket_path)
{
if (gettype($socket_path) == "string") {
$path_parts = explode(":", $socket_path);
$this->transport = $path_parts[0];
$this->host = substr($path_parts[1], 2, strlen($path_parts[1]));
if (count($path_parts) == 3) {
$this->port = $path_parts[2];
}
_info("trying ".$socket_path);
if ($this->stream_context) {
$this->fd = @stream_socket_client(
$socket_path,
$this->errno,
$this->errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
$this->stream_context
);
} else {
$this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout);
}
} elseif (is_resource($socket_path)) {
$this->fd = &$socket_path;
} else {
// Some error occurred.
}
if ($this->fd) {
_debug("connected to ".$socket_path."");
stream_set_blocking($this->fd, $this->blocking);
// watch descriptor for read/write events
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_read_ready')
));
return true;
} else {
_error(sprintf(
"unable to connect %s with error no: %s, error str: %s",
is_null($socket_path) ? 'NULL' : $socket_path,
is_null($this->errno) ? 'NULL' : $this->errno,
is_null($this->errstr) ? 'NULL' : $this->errstr
));
$this->disconnect();
return false;
}
}
public function disconnect()
{
JAXLLoop::unwatch($this->fd, array(
'read' => true,
'write' => true
));
if (is_resource($this->fd)) {
fclose($this->fd);
}
$this->fd = null;
}
public function compress()
{
$this->compressed = true;
//stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ);
//stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE);
}
public function crypt()
{
// set blocking (since tls negotiation fails if stream is non-blocking)
stream_set_blocking($this->fd, true);
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
}
}
}
// switch back to non-blocking
stream_set_blocking($this->fd, false);
return $ret;
}
/**
* @param string $data
*/
public function send($data)
{
$this->obuffer .= $data;
// add watch for write events
if ($this->writing) {
return;
}
JAXLLoop::watch($this->fd, array(
'write' => array(&$this, 'on_write_ready')
));
$this->writing = true;
}
public function on_read_ready($fd)
{
//_debug("on read ready called");
$raw = @fread($fd, $this->recv_chunk_size);
$bytes = strlen($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($fd);
if ($meta['eof'] === true) {
_warning("socket eof, disconnecting");
JAXLLoop::unwatch($fd, array(
'read' => true
));
$this->disconnect();
return;
}
}
$this->recv_bytes += $bytes;
$total = $this->ibuffer.$raw;
$this->ibuffer = "";
_debug("read ".$bytes."/".$this->recv_bytes." of data");
if ($bytes > 0) {
_debug($raw);
}
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $raw);
}
}
public function on_write_ready($fd)
{
//_debug("on write ready called");
$total = strlen($this->obuffer);
$bytes = @fwrite($fd, $this->obuffer);
$this->send_bytes += $bytes;
_debug("sent ".$bytes."/".$this->send_bytes." of data");
_debug(substr($this->obuffer, 0, $bytes));
$this->obuffer = substr($this->obuffer, $bytes, $total-$bytes);
// unwatch for write if obuffer is empty
if (strlen($this->obuffer) === 0) {
JAXLLoop::unwatch($fd, array(
'write' => true
));
$this->writing = false;
}
//_debug("current obuffer size: ".strlen($this->obuffer)."");
}
}
diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php
index f5c70bd..c686f8b 100644
--- a/core/jaxl_socket_server.php
+++ b/core/jaxl_socket_server.php
@@ -1,278 +1,276 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_loop.php';
-
class JAXLSocketServer
{
public $fd = null;
private $clients = array();
private $recv_chunk_size = 1024;
private $send_chunk_size = 8092;
private $accept_cb = null;
private $request_cb = null;
private $blocking = false;
private $backlog = 200;
public function __construct($path, $accept_cb, $request_cb)
{
$this->accept_cb = $accept_cb;
$this->request_cb = $request_cb;
$ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog)));
$this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx);
if ($this->fd !== false) {
if (@stream_set_blocking($this->fd, $this->blocking)) {
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_server_accept_ready')
));
_info("socket ready to accept on path ".$path);
} else {
_error("unable to set non block flag");
}
} else {
_error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr);
}
}
public function __destruct()
{
_info("shutting down socket server");
}
public function read($client_id)
{
//_debug("reactivating read on client sock");
$this->add_read_cb($client_id);
}
/**
* @param int $client_id
* @param string $data
*/
public function send($client_id, $data)
{
$this->clients[$client_id]['obuffer'] .= $data;
$this->add_write_cb($client_id);
}
public function close($client_id)
{
$this->clients[$client_id]['close'] = true;
$this->add_write_cb($client_id);
}
public function on_server_accept_ready($server)
{
//_debug("got server accept");
$client = @stream_socket_accept($server, 0, $addr);
if (!$client) {
_error("unable to accept new client conn");
return;
}
if (@stream_set_blocking($client, $this->blocking)) {
$client_id = (int) $client;
$this->clients[$client_id] = array(
'fd' => $client,
'ibuffer' => '',
'obuffer' => '',
'addr' => trim($addr),
'close' => false,
'closed' => false,
'reading' => false,
'writing' => false
);
_debug("accepted connection from client#".$client_id.", addr:".$addr);
// if accept callback is registered
// callback and let user land take further control of what to do
if ($this->accept_cb) {
call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']);
} else {
// if no accept callback is registered
// close the accepted connection
if (is_resource($client)) {
fclose($client);
}
$this->clients[$client_id]['closed'] = true;
unset($this->clients[$client_id]);
}
} else {
_error("unable to set non block flag");
}
}
public function on_client_read_ready($client)
{
// deactive socket for read
$client_id = (int) $client;
//_debug("client#$client_id is read ready");
$this->del_read_cb($client_id);
$raw = fread($client, $this->recv_chunk_size);
$bytes = strlen($raw);
_debug("recv $bytes bytes from client#$client_id");
//_debug($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($client);
if ($meta['eof'] === true) {
_debug("socket eof client#".$client_id.", closing");
$this->del_read_cb($client_id);
if (is_resource($client)) {
fclose($client);
}
unset($this->clients[$client_id]);
return;
}
}
$total = $this->clients[$client_id]['ibuffer'] . $raw;
if ($this->request_cb) {
call_user_func($this->request_cb, $client_id, $total);
}
$this->clients[$client_id]['ibuffer'] = '';
}
public function on_client_write_ready($client)
{
$client_id = (int) $client;
_debug("client#$client_id is write ready");
try {
// send in chunks
$total = $this->clients[$client_id]['obuffer'];
$written = @fwrite($client, substr($total, 0, $this->send_chunk_size));
if ($written === false) {
// fwrite failed
_warning("====> fwrite failed");
$this->clients[$client_id]['obuffer'] = $total;
} elseif ($written == strlen($total) || $written == $this->send_chunk_size) {
// full chunk written
//_debug("full chunk written");
$this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size);
} else {
// partial chunk written
//_debug("partial chunk $written written");
$this->clients[$client_id]['obuffer'] = substr($total, $written);
}
// if no more stuff to write, remove write handler
if (strlen($this->clients[$client_id]['obuffer']) === 0) {
$this->del_write_cb($client_id);
// if scheduled for close and not closed do it and clean up
if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) {
if (is_resource($client)) {
fclose($client);
}
$this->clients[$client_id]['closed'] = true;
unset($this->clients[$client_id]);
_debug("closed client#".$client_id);
}
}
} catch (JAXLException $e) {
_debug("====> got fwrite exception");
}
}
//
// client sock event register utils
//
protected function add_read_cb($client_id)
{
if ($this->clients[$client_id]['reading']) {
return;
}
JAXLLoop::watch($this->clients[$client_id]['fd'], array(
'read' => array(&$this, 'on_client_read_ready')
));
$this->clients[$client_id]['reading'] = true;
}
protected function add_write_cb($client_id)
{
if ($this->clients[$client_id]['writing']) {
return;
}
JAXLLoop::watch($this->clients[$client_id]['fd'], array(
'write' => array(&$this, 'on_client_write_ready')
));
$this->clients[$client_id]['writing'] = true;
}
protected function del_read_cb($client_id)
{
if (!$this->clients[$client_id]['reading']) {
return;
}
JAXLLoop::unwatch($this->clients[$client_id]['fd'], array(
'read' => true
));
$this->clients[$client_id]['reading'] = false;
}
protected function del_write_cb($client_id)
{
if (!$this->clients[$client_id]['writing']) {
return;
}
JAXLLoop::unwatch($this->clients[$client_id]['fd'], array(
'write' => true
));
$this->clients[$client_id]['writing'] = false;
}
}
diff --git a/docs/users/http_examples.rst b/docs/users/http_examples.rst
index 6357e42..12286ee 100644
--- a/docs/users/http_examples.rst
+++ b/docs/users/http_examples.rst
@@ -1,102 +1,98 @@
HTTP Examples
=============
Writing HTTP Server
-------------------
Intialize an ``HTTPServer`` instance
.. code-block:: ruby
- require_once 'jaxl.php';
- require_once JAXL_CWD.'/http/http_server.php';
$http = new HTTPServer();
By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this.
Define a callback method that will accept all incoming ``HTTPRequest`` objects
.. code-block:: ruby
function on_request($request)
{
if ($request->method == 'GET') {
$body = json_encode($request);
$request->ok($body, array('Content-Type' => 'application:json'));
} else {
$request->not_found();
}
}
``on_request`` callback method will receive a ``HTTPRequest`` object instance.
For this example, we will simply echo back json encoded ``$request`` object for
every http GET request.
Start http server:
.. code-block:: ruby
$http->start('on_request');
We pass ``on_request`` method as first parameter to ``HTTPServer::start/1``.
If nothing is passed, requests will fail with a default 404 not found error message
Writing REST API Server
-----------------------
Intialize an ``HTTPServer`` instance
.. code-block:: ruby
- require_once 'jaxl.php';
- require_once JAXL_CWD.'/http/http_server.php';
$http = new HTTPServer();
By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this.
Define our REST resources callback methods:
.. code-block:: ruby
function index($request)
{
$request->send_response(
200, array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>'
);
$request->close();
}
function upload($request)
{
if ($request->method == 'GET') {
$request->send_response(
200, array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action=""><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>'
);
} elseif ($request->method == 'POST') {
if ($request->body === null && $request->expect) {
$request->recv_body();
} else {
// got upload body, save it
_debug("file upload complete, got ".strlen($request->body)." bytes of data");
$request->close();
}
}
}
Next we need to register dispatch rules for our callbacks above:
.. code-block:: ruby
$index = array('index', '^/$');
$upload = array('upload', '^/upload', array('GET', 'POST'));
$rules = array($index, $upload);
$http->dispatch($rules);
Start REST api server:
.. code-block:: ruby
$http->start();
Make an HTTP request
--------------------
diff --git a/docs/users/xmpp_examples.rst b/docs/users/xmpp_examples.rst
index e92d3c3..927a310 100644
--- a/docs/users/xmpp_examples.rst
+++ b/docs/users/xmpp_examples.rst
@@ -1,120 +1,117 @@
XMPP Examples
=============
Echo Bot Client
---------------
include ``jaxl.php`` and initialize a new ``JAXL`` instance:
.. code-block:: ruby
- require 'jaxl.php';
$client = new JAXL(array(
'jid' => '[email protected]',
'pass' => 'password'
));
We just initialized a new ``JAXL`` instance by passing our jabber client ``jid`` and ``pass``.
View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor.
Next we need to register callbacks on events of interest using ``JAXL::add_cb/2`` method as shown below:
.. code-block:: ruby
$client->add_cb('on_auth_success', function () {
global $client;
$client->set_status("available!"); // set your status
$client->get_vcard(); // fetch your vcard
$client->get_roster(); // fetch your roster list
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_disconnect', function () {
_debug("got on_disconnect cb");
});
We just registered callbacks on ``on_auth_success``, ``on_chat_message`` and ``on_disconnect`` events
that will occur inside our configured ``JAXL`` instance lifecycle.
We also passed a method that will be called (with parameters if any) when the event has been detected.
See list of :ref:`available event callbacks <jaxl-instance>` that we can hook to inside ``JAXL`` instance lifecycle.
Received ``$msg`` parameter with ``on_chat_message`` event callback above, will be an instance of ``XMPPMsg`` which
extends ``XMPPStanza`` class, that allows us easy to use access patterns to common XMPP stanza attributes like
``to``, ``from``, ``type``, ``id`` to name a few.
We were also able to access our xmpp client full jabber id by calling ``$client->full_jid``. This attribute of
``JAXL`` instance is available from ``on_auth_success`` event. ``full_jid`` attribute is an instance of ``XMPPJid``.
To send our echo back ``$msg`` packet we called ``JAXL::send/1`` which accepts a single parameter which MUST be
an instance of ``JAXLXml``. Since ``XMPPStanza`` is a wrapper upon ``JAXLXml`` we can very well pass our modified
``$msg`` object to the send method.
Read more about various :ref:`XML Objects <xml-objects>` and how they make writing XMPP applications fun and easy.
You can also :ref:`add custom access patterns <xml-objects>` upon received ``XMPPStanza`` objects. Since all access
patterns are evaluated upon first access and cached for later usage, adding hundreds of custom access patterns that
retrieves information from 100th child of received XML packet will not be an issue.
We will finally start our xmpp client by calling:
.. code-block:: ruby
$client->start();
See list of :ref:`available options <jaxl-instance>` that can be passed to the ``JAXL::start/2`` method.
These options are particularly useful for debugging and monitoring.
Echo Bot BOSH Client
--------------------
Everything goes same for a cli BOSH client. To run above echo bot client example as a bosh client simply
pass additional parameters to ``JAXL`` constructor:
.. code-block:: ruby
- require 'jaxl.php';
$client = new JAXL(array(
'jid' => '[email protected]',
'pass' => 'password',
'bosh_url' => 'http://localhost:5280/http-bind'
));
You can even pass custom values for ``hold``, ``wait`` and other attributes.
View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor.
Echo Bot External Component
---------------------------
Again almost everything goes same for an external component except a few custom ``JAXL`` constructor
parameter as shown below:
.. code-block:: ruby
- require_once 'jaxl.php';
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required) destination socket
'host' => $argv[3],
'port' => $argv[4]
));
We will also need to include ``XEP0114`` which implements Jabber Component XMPP Extension.
.. code-block:: ruby
// (required)
$comp->require_xep(array(
'0114' // jabber component protocol
));
``JAXL::require_xep/1`` accepts an array of XEP numbers passed as strings.
diff --git a/http/http_client.php b/http/http_client.php
index 33aacb2..b98623e 100644
--- a/http/http_client.php
+++ b/http/http_client.php
@@ -1,157 +1,155 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_socket_client.php';
-
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class HTTPClient
{
/** @var string */
private $url = null;
private $parts = array();
private $headers = array();
private $data = null;
public $method = null;
/** @var JAXLSocketClient */
private $client = null;
/**
* @param string $url
* @param array $headers TODO: Currently not used.
* @param unknown $data TODO: Currently not used.
*/
public function __construct($url, array $headers = array(), $data = null)
{
$this->url = $url;
$this->headers = $headers;
$this->data = $data;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function start($method = 'GET')
{
$this->method = $method;
$this->parts = parse_url($this->url);
$transport = $this->transport();
$ip = $this->ip();
$port = $this->port();
$socket_path = $transport.'://'.$ip.':'.$port;
if ($this->client->connect($socket_path)) {
_debug("connection to $this->url established");
// send request data
$this->send_request();
// start main loop
JAXLLoop::run();
} else {
_debug("unable to open $this->url");
}
}
public function on_response($raw)
{
_info("got http response");
}
protected function send_request()
{
$this->client->send($this->line().HTTPServer::HTTP_CRLF);
$this->client->send($this->ua().HTTPServer::HTTP_CRLF);
$this->client->send($this->host().HTTPServer::HTTP_CRLF);
$this->client->send(HTTPServer::HTTP_CRLF);
}
//
// private methods on uri parts
//
private function line()
{
return $this->method.' '.$this->uri().' HTTP/1.1';
}
private function ua()
{
return 'User-Agent: jaxl_http_client/3.x';
}
private function host()
{
return 'Host: '.$this->parts['host'].':'.$this->port();
}
private function transport()
{
return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl');
}
private function ip()
{
return gethostbyname($this->parts['host']);
}
private function port()
{
return isset($this->parts['port']) ? $this->parts['port'] : 80;
}
private function uri()
{
$uri = $this->parts['path'];
if (isset($this->parts['query'])) {
$uri .= '?'.$this->parts['query'];
}
if (isset($this->parts['fragment'])) {
$uri .= '#'.$this->parts['fragment'];
}
return $uri;
}
}
diff --git a/http/http_multipart.php b/http/http_multipart.php
index 52bcc0e..869ca96 100644
--- a/http/http_multipart.php
+++ b/http/http_multipart.php
@@ -1,171 +1,169 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_fsm.php';
-
class HTTPMultiPart extends JAXLFsm
{
public $boundary = null;
public $form_data = array();
public $index = -1;
public function handle_invalid_state($r)
{
_error("got invalid event $r");
}
public function __construct($boundary)
{
$this->boundary = $boundary;
parent::__construct('wait_for_boundary_start');
}
public function state()
{
return $this->state;
}
public function wait_for_boundary_start($event, $data)
{
if ($event == 'process') {
if ($data[0] == '--'.$this->boundary) {
$this->index += 1;
$this->form_data[$this->index] = array(
'meta' => array(),
'headers' => array(),
'body' => ''
);
return array('wait_for_content_disposition', true);
} else {
_warning("invalid boundary start $data[0] while expecting $this->boundary");
return array('wait_for_boundary_start', false);
}
} else {
_warning("invalid $event rcvd");
return array('wait_for_boundary_start', false);
}
}
public function wait_for_content_disposition($event, $data)
{
if ($event == 'process') {
$disposition = explode(":", $data[0]);
if (strtolower(trim($disposition[0])) == 'content-disposition') {
$this->form_data[$this->index]['headers'][$disposition[0]] = trim($disposition[1]);
$meta = explode(";", $disposition[1]);
if (trim(array_shift($meta)) == 'form-data') {
foreach ($meta as $k) {
list($k, $v) = explode("=", $k);
$this->form_data[$this->index]['meta'][$k] = $v;
}
return array('wait_for_content_type', true);
} else {
_warning("first part of meta is not form-data");
return array('wait_for_content_disposition', false);
}
} else {
_warning("not a valid content-disposition line");
return array('wait_for_content_disposition', false);
}
} else {
_warning("invalid $event rcvd");
return array('wait_for_content_disposition', false);
}
}
public function wait_for_content_type($event, $data)
{
if ($event == 'process') {
$type = explode(":", $data[0]);
if (strtolower(trim($type[0])) == 'content-type') {
$this->form_data[$this->index]['headers'][$type[0]] = trim($type[1]);
$this->form_data[$this->index]['meta']['type'] = $type[1];
return array('wait_for_content_body', true);
} else {
_debug("not a valid content-type line");
return array('wait_for_content_type', false);
}
} else {
_warning("invalid $event rcvd");
return array('wait_for_content_type', false);
}
}
public function wait_for_content_body($event, $data)
{
if ($event == 'process') {
if ($data[0] == '--'.$this->boundary) {
_debug("start of new multipart/form-data detected");
return array('wait_for_content_disposition', true);
} elseif ($data[0] == '--'.$this->boundary.'--') {
_debug("end of multipart form data detected");
return array('wait_for_empty_line', true);
} else {
$this->form_data[$this->index]['body'] .= $data[0];
return array('wait_for_content_body', true);
}
} else {
_warning("invalid $event rcvd");
return array('wait_for_content_body', false);
}
}
public function wait_for_empty_line($event, $data)
{
if ($event == 'process') {
if ($data[0] == '') {
return array('done', true);
} else {
_warning("invalid empty line $data[0] received");
return array('wait_for_empty_line', false);
}
} else {
_warning("got $event in done state with data $data[0]");
return array('wait_for_empty_line', false);
}
}
public function done($event, $data)
{
_warning("got unhandled event $event with data $data[0]");
return array('done', false);
}
}
diff --git a/http/http_request.php b/http/http_request.php
index 4d0e5a4..aaa719d 100644
--- a/http/http_request.php
+++ b/http/http_request.php
@@ -1,512 +1,509 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_fsm.php';
-require_once JAXL_CWD.'/http/http_multipart.php';
-
//
// These methods are available only once
// $request FSM has reached 'headers_received' state
//
// following shortcuts are available
// on received $request object:
//
// $request->{status_code_name}($headers, $body)
// $request->{status_code_name}($body, $headers)
//
// $request->{status_code_name}($headers)
// $request->{status_code_name}($body)
//
// following specific methods are also available:
//
// $request->send_line($code)
// $request->send_header($key, $value)
// $request->send_headers($headers)
// $request->send_message($string)
//
// all the above methods can also be directly performed using:
//
// $request->send_response($code, $headers = array(), $body = null)
//
// Note: All the send_* methods do not manage connection close/keep-alive logic,
// it is upto you to do that, by default connection will usually be dropped
// on client disconnect if not handled by you.
//
class HTTPRequest extends JAXLFsm
{
// peer identifier
public $sock = null;
public $ip = null;
public $port = null;
// request line
public $version = null;
public $method = null;
public $resource = null;
public $path = null;
public $query = array();
// headers and body
public $headers = array();
public $body = null;
public $recvd_body_len = 0;
// is true if 'Expect: 100-Continue'
// request header has been seen
public $expect = false;
// set if there is Content-Type: multipart/form-data; boundary=...
// header already seen
public $multipart = null;
// callback for send/read/close actions on accepted sock
private $send_cb = null;
private $read_cb = null;
private $close_cb = null;
private $shortcuts = array(
'ok' => 200, // 2xx
'redirect' => 302, 'not_modified' => 304, // 3xx
'not_found' => 404, 'bad_request' => 400, // 4xx
'internal_error' => 500, // 5xx
'recv_body' => true, 'close' => true // others
);
public function __construct($sock, $addr)
{
$this->sock = $sock;
$addr = explode(":", $addr);
$this->ip = $addr[0];
if (count($addr) == 2) {
$this->port = $addr[1];
}
parent::__construct("setup");
}
public function __destruct()
{
_debug("http request going down in ".$this->state." state");
}
public function state()
{
return $this->state;
}
//
// abstract method implementation
//
public function handle_invalid_state($r)
{
_debug("handle invalid state called with");
var_dump($r);
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case 'set_sock_cb':
$this->send_cb = $args[0];
$this->read_cb = $args[1];
$this->close_cb = $args[2];
return 'wait_for_request_line';
break;
default:
_warning("uncatched $event");
return 'setup';
}
}
public function wait_for_request_line($event, $args)
{
switch ($event) {
case 'line':
$this->line($args[0], $args[1], $args[2]);
return 'wait_for_headers';
break;
default:
_warning("uncatched $event");
return 'wait_for_request_line';
}
}
public function wait_for_headers($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'maybe_headers_received';
default:
_warning("uncatched $event");
return 'wait_for_headers';
}
}
public function maybe_headers_received($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'headers_received';
break;
case 'body':
return $this->wait_for_body($event, $args);
break;
default:
_warning("uncatched $event");
return 'maybe_headers_received';
}
}
public function wait_for_body($event, $args)
{
switch ($event) {
case 'body':
$content_length = $this->headers['Content-Length'];
$rcvd = $args[0];
$rcvd_len = strlen($rcvd);
$this->recvd_body_len += $rcvd_len;
if ($this->body === null) {
$this->body = $rcvd;
} else {
$this->body .= $rcvd;
}
if ($this->multipart) {
// boundary start, content_disposition, form data, boundary start, ....., boundary end
// these define various states of a multipart/form-data
$form_data = explode(HTTPServer::HTTP_CRLF, $rcvd);
foreach ($form_data as $data) {
//_debug("passing $data to multipart fsm");
if (!$this->multipart->process($data)) {
_debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
}
}
if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'set_header':
$content_length = $this->headers['Content-Length'];
$body = implode(":", $args);
$rcvd_len = strlen($body);
$this->recvd_body_len += $rcvd_len;
if (!$this->multipart->process($body)) {
_debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'empty_line':
$content_length = $this->headers['Content-Length'];
if (!$this->multipart->process('')) {
_debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
default:
_warning("uncatched $event");
return 'wait_for_body';
}
}
// headers and may be body received
public function headers_received($event, $args)
{
switch ($event) {
case 'empty_line':
return 'headers_received';
break;
default:
if (substr($event, 0, 5) == 'send_') {
$protected = '_'.$event;
if (method_exists($this, $protected)) {
call_user_func_array(array(&$this, $protected), $args);
return 'headers_received';
} else {
_debug("non-existant method $event called");
return 'headers_received';
}
} elseif (isset($this->shortcuts[$event])) {
return $this->handle_shortcut($event, $args);
} else {
_warning("uncatched $event ".$args[0]);
return 'headers_received';
}
}
}
public function closed($event, $args)
{
_warning("uncatched $event");
}
// sets input headers
// called internally for every header received
protected function set_header($k, $v)
{
$k = trim($k);
$v = ltrim($v);
// is expect header?
if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') {
$this->expect = true;
}
// is multipart form data?
if (strtolower($k) == 'content-type') {
$ctype = explode(';', $v);
if (count($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') {
$boundary = explode('=', trim($ctype[1]));
if (strtolower(trim($boundary[0])) == 'boundary') {
_debug("multipart with boundary $boundary[1] detected");
$this->multipart = new HTTPMultiPart(ltrim($boundary[1]));
}
}
}
$this->headers[trim($k)] = trim($v);
}
// shortcut handler
protected function handle_shortcut($event, $args)
{
_debug("executing shortcut '$event'");
switch ($event) {
// http status code shortcuts
case 'ok':
case 'redirect':
case 'not_modified':
case 'bad_request':
case 'not_found':
case 'internal_error':
list($headers, $body) = $this->parse_shortcut_args($args);
$code = $this->shortcuts[$event];
$this->send_response($code, $headers, $body);
$this->close();
return 'closed';
break;
// others
case 'recv_body':
// send expect header if required
if ($this->expect) {
$this->expect = false;
$this->send_line(100);
}
// read data
$this->read();
return 'wait_for_body';
break;
case 'close':
$this->close();
return 'closed';
break;
}
}
private function parse_shortcut_args($args)
{
if (count($args) == 0) {
$body = null;
$headers = array();
}
if (count($args) == 1) {
// http headers or body only received
if (is_array($args[0])) {
// http headers only
$headers = $args[0];
$body = null;
} else {
// body only
$body = $args[0];
$headers = array();
}
} elseif (count($args) == 2) {
// body and http headers both received
if (is_array($args[0])) {
// header first
$body = $args[1];
$headers = $args[0];
} else {
// body first
$body = $args[0];
$headers = $args[1];
}
}
return array($headers, $body);
}
//
// send methods
// available only on 'headers_received' state
//
protected function send_line($code)
{
$raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTPServer::HTTP_CRLF;
$this->send($raw);
}
protected function send_header($k, $v)
{
$raw = $k.': '.$v.HTTPServer::HTTP_CRLF;
$this->send($raw);
}
protected function send_headers($code, $headers)
{
foreach ($headers as $k => $v) {
$this->send_header($k, $v);
}
}
protected function send_body($body)
{
$this->send($body);
}
protected function send_response($code, array $headers = array(), $body = null)
{
// send out response line
$this->send_line($code);
// set content length of body exists and is not already set
if ($body && !isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($body);
}
// send out headers
$this->send_headers($code, $headers);
// send body
// prefixed with an empty line
_debug("sending out HTTP_CRLF prefixed body");
if ($body) {
$this->send_body(HTTPServer::HTTP_CRLF.$body);
}
}
//
// internal methods
//
// initializes status line elements
private function line($method, $resource, $version)
{
$this->method = $method;
$this->resource = $resource;
$resource = explode("?", $resource);
$this->path = $resource[0];
if (count($resource) == 2) {
$query = $resource[1];
$query = explode("&", $query);
foreach ($query as $q) {
$q = explode("=", $q);
if (count($q) == 1) {
$q[1] = "";
}
$this->query[$q[0]] = $q[1];
}
}
$this->version = $version;
}
private function send($raw)
{
call_user_func($this->send_cb, $this->sock, $raw);
}
private function read()
{
call_user_func($this->read_cb, $this->sock);
}
private function close()
{
call_user_func($this->close_cb, $this->sock);
}
}
diff --git a/http/http_server.php b/http/http_server.php
index f85a1d1..cecd782 100644
--- a/http/http_server.php
+++ b/http/http_server.php
@@ -1,203 +1,199 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_logger.php';
-require_once JAXL_CWD.'/http/http_dispatcher.php';
-require_once JAXL_CWD.'/http/http_request.php';
-
class HTTPServer
{
// Carriage return and line feed.
const HTTP_CRLF = "\r\n";
// 1xx informational
const HTTP_100 = 'Continue';
const HTTP_101 = 'Switching Protocols';
// 2xx success
const HTTP_200 = 'OK';
// 3xx redirection
const HTTP_301 = 'Moved Permanently';
const HTTP_304 = 'Not Modified';
// 4xx client error
const HTTP_400 = 'Bad Request';
const HTTP_403 = 'Forbidden';
const HTTP_404 = 'Not Found';
const HTTP_405 = 'Method Not Allowed';
const HTTP_499 = 'Client Closed Request'; // Nginx
// 5xx server error
const HTTP_500 = 'Internal Server Error';
const HTTP_503 = 'Service Unavailable';
/** @var JAXLSocketServer */
private $server = null;
/** @var callable */
public $cb = null;
private $dispatcher = null;
private $requests = array();
public function __construct($port = 9699, $address = "127.0.0.1")
{
$path = 'tcp://'.$address.':'.$port;
$this->server = new JAXLSocketServer(
$path,
array(&$this, 'on_accept'),
array(&$this, 'on_request')
);
$this->dispatcher = new HTTPDispatcher();
}
public function __destruct()
{
$this->server = null;
}
public function dispatch($rules)
{
foreach ($rules as $rule) {
$this->dispatcher->add_rule($rule);
}
}
/**
* @param callable $cb
*/
public function start($cb = null)
{
$this->cb = $cb;
JAXLLoop::run();
}
public function on_accept($sock, $addr)
{
_debug("on_accept for client#$sock, addr:$addr");
// initialize new request obj
$request = new HTTPRequest($sock, $addr);
// setup sock cb
$request->set_sock_cb(
array(&$this->server, 'send'),
array(&$this->server, 'read'),
array(&$this->server, 'close')
);
// cache request object
$this->requests[$sock] = &$request;
// reactive client for further read
$this->server->read($sock);
}
public function on_request($sock, $raw)
{
_debug("on_request for client#$sock");
$request = $this->requests[$sock];
// 'wait_for_body' state is reached when ever
// application calls recv_body() method
// on received $request object
if ($request->state() == 'wait_for_body') {
$request->body($raw);
} else {
// break on crlf
$lines = explode(HTTP_CRLF, $raw);
// parse request line
if ($request->state() == 'wait_for_request_line') {
list($method, $resource, $version) = explode(" ", $lines[0]);
$request->line($method, $resource, $version);
unset($lines[0]);
_info($request->ip." ".$request->method." ".$request->resource." ".$request->version);
}
// parse headers
foreach ($lines as $line) {
$line_parts = explode(":", $line);
if (count($line_parts) > 1) {
if (strlen($line_parts[0]) > 0) {
$k = $line_parts[0];
unset($line_parts[0]);
$v = implode(":", $line_parts);
$request->set_header($k, $v);
}
} elseif (strlen(trim($line_parts[0])) == 0) {
$request->empty_line();
} else {
// if exploded line array size is 1
// and there is something in $line_parts[0]
// must be request body
$request->body($line);
}
}
}
// if request has reached 'headers_received' state?
if ($request->state() == 'headers_received') {
// dispatch to any matching rule found
_debug("delegating to dispatcher for further routing");
$dispatched = $this->dispatcher->dispatch($request);
// if no dispatch rule matched call generic callback
if (!$dispatched && $this->cb) {
_debug("no dispatch rule matched, sending to generic callback");
call_user_func($this->cb, $request);
} elseif (!$dispatched) {
// elseif not dispatched and not generic callbacked
// send 404 not_found
// TODO: send 404 if no callback is registered for this request
_debug("dropping request since no matching dispatch rule or generic callback was specified");
$request->not_found('404 Not Found');
}
} else {
// if state is not 'headers_received'
// reactivate client socket for read event
$this->server->read($sock);
}
}
}
diff --git a/jaxl.php b/jaxl.php
index ec2e3da..b192d06 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,881 +1,860 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
-require_once JAXL_CWD.'/core/jaxl_exception.php';
-require_once JAXL_CWD.'/core/jaxl_cli.php';
-require_once JAXL_CWD.'/core/jaxl_loop.php';
-require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
-require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
-require_once JAXL_CWD.'/core/jaxl_event.php';
-require_once JAXL_CWD.'/core/jaxl_logger.php';
-require_once JAXL_CWD.'/core/jaxl_socket_server.php';
-
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
$this->cfg['multi_client'] = isset($this->cfg['multi_client']) ? $this->cfg['multi_client'] : false;
// lifecycle events callback
$this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLSocketClient|XEP_0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
- $filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
-
- // include xep
- require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
-
+
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', XEP_0030::NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', XEP_0030::NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
-
- /**
- * Used to define JAXL_CWD in tests.
- */
- public static function dummy()
- {
- // Do nothing.
- }
}
diff --git a/jaxlctl b/jaxlctl
index 890aaca..9b2e37f 100755
--- a/jaxlctl
+++ b/jaxlctl
@@ -1,200 +1,221 @@
#!/usr/bin/env php
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
error_reporting(E_ALL | E_STRICT);
-date_default_timezone_set('UTC');
+
+if (PHP_SAPI !== 'cli') {
+ echo 'Warning: script should be invoked via the CLI version of PHP, not the '.PHP_SAPI.' SAPI'.PHP_EOL;
+}
+
+if (!ini_get('date.timezone')) {
+ ini_set('date.timezone', 'UTC');
+}
+
+foreach (array(
+ // Run from ./JAXL-source/jaxlctl
+ dirname(__FILE__) . '/vendor/autoload.php',
+ // Run from /some-project/bin/jaxlctl
+ dirname(__FILE__) . '/../vendor/autoload.php',
+ // Run from /some-project/vendor/jaxl/jaxl/jaxlctl
+ dirname(__FILE__) . '/../../../vendor/autoload.php'
+) as $file) {
+ if (file_exists($file)) {
+ require $file;
+ break;
+ }
+}
+unset($file);
$params = $argv;
$exe = array_shift($params);
$command = array_shift($params);
-require_once 'jaxl.php';
JAXLLogger::$level = JAXLLogger::INFO;
// TODO: an abstract JAXLCtlCommand class
// with seperate class per command
// a mechanism to register new commands
class JAXLCtl
{
protected $ipc = null;
protected $buffer = '';
protected $buffer_cb = null;
protected $cli = null;
public $dots = "....... ";
protected $symbols = array();
public function __construct($command, $params)
{
global $exe;
if (method_exists($this, $command)) {
$r = call_user_func_array(array(&$this, $command), $params);
if (count($r) == 2) {
list($buffer_cb, $quit_cb) = $r;
$this->buffer_cb = $buffer_cb;
$this->cli = new JAXLCli(array(&$this, 'onTerminalInput'), $quit_cb);
$this->run();
} else {
_colorize("oops! internal command error", JAXLLogger::ERROR);
exit;
}
} else {
_colorize("error: invalid command '$command' received", JAXLLogger::ERROR);
_colorize("type '$exe help' for list of available commands", JAXLLogger::NOTICE);
exit;
}
}
public function run()
{
JAXLCli::prompt();
JAXLLoop::run();
}
public function onTerminalInput($raw)
{
$raw = trim($raw);
$last = substr($raw, -1, 1);
if ($last == ";") {
// dispatch to buffer callback
call_user_func($this->buffer_cb, $this->buffer.$raw);
$this->buffer = '';
} elseif ($last == '\\') {
$this->buffer .= substr($raw, 0, -1);
echo $this->dots;
} else {
// buffer command
$this->buffer .= $raw."; ";
echo $this->dots;
}
}
public static function printHelp()
{
global $exe;
_colorize("Usage: $exe command [options...]".PHP_EOL, JAXLLogger::INFO);
_colorize("Commands:", JAXLLogger::NOTICE);
_colorize(" help This help text", JAXLLogger::DEBUG);
_colorize(" debug Attach a debug console to a running JAXL daemon", JAXLLogger::DEBUG);
_colorize(" shell Open up Jaxl shell emulator", JAXLLogger::DEBUG);
echo PHP_EOL;
}
protected function help()
{
JAXLCtl::printHelp();
exit;
}
//
// shell command
//
protected function shell()
{
return array(array(&$this, 'onShellInput'), array(&$this, 'onShellQuit'));
}
private function eval_($raw, $symbols)
{
extract($symbols);
eval($raw);
$g = get_defined_vars();
unset($g['raw']);
unset($g['symbols']);
return $g;
}
public function onShellInput($raw)
{
$this->symbols = $this->eval_($raw, $this->symbols);
JAXLCli::prompt();
}
public function onShellQuit()
{
exit;
}
//
// debug command
//
protected function debug($sock_path)
{
$this->ipc = new JAXLSocketClient();
$this->ipc->set_callback(array(&$this, 'onDebugResponse'));
$this->ipc->connect('unix://'.$sock_path);
return array(array(&$this, 'onDebugInput'), array(&$this, 'onDebugQuit'));
}
public function onDebugResponse($raw)
{
$ret = unserialize($raw);
print_r($ret);
echo PHP_EOL;
JAXLCli::prompt();
}
public function onDebugInput($raw)
{
$this->ipc->send($this->buffer.$raw);
}
public function onDebugQuit()
{
$this->ipc->disconnect();
exit;
}
}
// we atleast need a command argument
if ($argc < 2) {
JAXLCtl::printHelp();
exit;
}
$ctl = new JAXLCtl($command, $params);
echo "done".PHP_EOL;
diff --git a/tests/JAXLEventTest.php b/tests/JAXLEventTest.php
index f8264db..e3ccd66 100644
--- a/tests/JAXLEventTest.php
+++ b/tests/JAXLEventTest.php
@@ -1,74 +1,72 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-JAXL::dummy();
-
/**
*
* @author abhinavsingh
*
*/
class JAXLEventTest extends PHPUnit_Framework_TestCase
{
public function test_jaxl_event()
{
$ev = new JAXLEvent();
$ref1 = $ev->add('on_connect', 'some_func', 0);
$ref2 = $ev->add('on_connect', 'some_func1', 0);
$ref3 = $ev->add('on_connect', 'some_func2', 1);
$ref4 = $ev->add('on_connect', 'some_func3', 4);
$ref5 = $ev->add('on_disconnect', 'some_func', 1);
$ref6 = $ev->add('on_disconnect', 'some_func1', 1);
//$ev->emit('on_connect', null);
$registry = $ev->getRegistry();
$this->assertEquals(2, count($registry));
$this->assertEquals(4, count($registry['on_connect']));
$this->assertEquals(2, count($registry['on_disconnect']));
$ev->del($ref2);
$ev->del($ref1);
$ev->del($ref6);
$ev->del($ref5);
$ev->del($ref4);
$ev->del($ref3);
}
}
diff --git a/tests/JAXLLoggerTest.php b/tests/JAXLLoggerTest.php
index 0b292ee..7f91670 100644
--- a/tests/JAXLLoggerTest.php
+++ b/tests/JAXLLoggerTest.php
@@ -1,44 +1,42 @@
<?php
-JAXL::dummy();
-
class JAXLLoggerTest extends PHPUnit_Framework_TestCase
{
/**
* @runInSeparateProcess<--fixme
*/
public function testColorize()
{
$msg = 'Test message';
// TODO: Fix JAXL to run with @runInSeparateProcess and remove following line.
$current = JAXLLogger::$colorize;
JAXLLogger::$colorize = false;
$this->assertEquals($msg, JAXLLogger::colorize($msg, JAXLLogger::ERROR));
JAXLLogger::$colorize = true;
$this->assertNotEquals($msg, JAXLLogger::colorize($msg, JAXLLogger::ERROR));
$color = 123;
JAXLLogger::setColors(array(
JAXLLogger::ERROR => $color
));
$this->assertEquals("\033[" . $color . "m" . $msg . "\033[0m", JAXLLogger::colorize($msg, JAXLLogger::ERROR));
// TODO: Fix JAXL to run with @runInSeparateProcess and remove following line.
JAXLLogger::$colorize = $current;
}
/**
* @requires PHP 5.4
* @requires function uopz_backup
*/
public function testLog()
{
$msg = 'Test message';
uopz_backup('error_log');
JAXLLogger::log($msg);
}
}
diff --git a/tests/JAXLSocketClientTest.php b/tests/JAXLSocketClientTest.php
index 17f1960..926ba22 100644
--- a/tests/JAXLSocketClientTest.php
+++ b/tests/JAXLSocketClientTest.php
@@ -1,59 +1,57 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-JAXL::dummy();
-
/**
*
* @author abhinavsingh
*
*/
class JAXLSocketClientTest extends PHPUnit_Framework_TestCase
{
public function test_jaxl_socket_client()
{
$sock = new JAXLSocketClient();
$sock->connect('tcp://127.0.0.1:5222');
$sock->send("<stream:stream>");
while ($sock->fd) {
$sock->recv();
}
}
}
diff --git a/tests/JAXLTest.php b/tests/JAXLTest.php
index 138382a..7057221 100644
--- a/tests/JAXLTest.php
+++ b/tests/JAXLTest.php
@@ -1,59 +1,57 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-JAXL::dummy();
-
/**
*
* @author abhinavsingh
*
*/
class JAXLTest extends PHPUnit_Framework_TestCase
{
public function testProtocolOption()
{
$config = array(
'host' => 'domain.tld',
'port' => 5223,
'protocol' => 'tcp'
);
$jaxl = new JAXL($config);
$this->assertEquals('tcp://domain.tld:5223', $jaxl->get_socket_path());
$this->assertInstanceOf('JAXLSocketClient', $jaxl->getTransport());
}
}
diff --git a/tests/JAXLXmlStreamTest.php b/tests/JAXLXmlStreamTest.php
index 80209a1..0a1a92b 100644
--- a/tests/JAXLXmlStreamTest.php
+++ b/tests/JAXLXmlStreamTest.php
@@ -1,77 +1,75 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-JAXL::dummy();
-
/**
*
* @author abhinavsingh
*
*/
class JAXLXmlStreamTest extends PHPUnit_Framework_TestCase
{
public function xml_start_cb($node)
{
$this->assertEquals('stream', $node->name);
$this->assertEquals(XMPP::NS_XMPP, $node->ns);
}
public function xml_end_cb($node)
{
$this->assertEquals('stream', $node->name);
}
public function xml_stanza_cb($node)
{
$this->assertEquals('features', $node->name);
$this->assertEquals(1, count($node->childrens));
}
public function test_xml_stream_callbacks()
{
$xml = new JAXLXmlStream();
$xml->set_callback(array(&$this, "xml_start_cb"), array(&$this, "xml_end_cb"), array(&$this, "xml_stanza_cb"));
$xml->parse('<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">');
$xml->parse('<features>');
$xml->parse('<mechanisms>');
$xml->parse('</mechanisms>');
$xml->parse('</features>');
$xml->parse('</stream:stream>');
}
}
diff --git a/tests/JAXLXmlTest.php b/tests/JAXLXmlTest.php
index 3bd5436..ffc9214 100644
--- a/tests/JAXLXmlTest.php
+++ b/tests/JAXLXmlTest.php
@@ -1,85 +1,83 @@
<?php
-JAXL::dummy();
-
class JAXLXmlTest extends PHPUnit_Framework_TestCase
{
public static $NS = 'SOME_NAMESPACE';
public static $attrs = array('attr1' => 'value1');
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function testJAXLXml_0()
{
$xml = new JAXLXml();
$this->assertEquals('<></>', $xml->to_string());
}
public function testJAXLXml_1_1()
{
$xml = new JAXLXml('');
$this->assertEquals('<></>', $xml->to_string());
}
public function testJAXLXml_1_2()
{
$xml = new JAXLXml('html');
$this->assertEquals('<html></html>', $xml->to_string());
}
public function testJAXLXml_2_1()
{
$xml = new JAXLXml('html', self::$NS);
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE"></html>',
$xml->to_string()
);
}
public function testJAXLXml_2_2()
{
$xml = new JAXLXml('html', self::$attrs);
$this->assertEquals(
'<html attr1="value1"></html>',
$xml->to_string()
);
}
public function testJAXLXml_3_1()
{
$xml = new JAXLXml('html', self::$attrs, 'Some text');
$this->assertEquals(
'<html attr1="value1">Some text</html>',
$xml->to_string()
);
}
public function testJAXLXml_3_2()
{
$xml = new JAXLXml('html', self::$NS, 'Some text');
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE">Some text</html>',
$xml->to_string()
);
}
public function testJAXLXml_3_3()
{
$xml = new JAXLXml('html', self::$NS, self::$attrs);
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE" attr1="value1"></html>',
$xml->to_string()
);
}
public function testJAXLXml_4()
{
$xml = new JAXLXml('html', self::$NS, self::$attrs, 'Some text');
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE" attr1="value1">Some text</html>',
$xml->to_string()
);
}
}
diff --git a/tests/XMPPJidTest.php b/tests/XMPPJidTest.php
index c30c75f..2c4bd5a 100644
--- a/tests/XMPPJidTest.php
+++ b/tests/XMPPJidTest.php
@@ -1,101 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-JAXL::dummy();
-
/**
*
* @author abhinavsingh
*
*/
class XMPPJidTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider jidPositiveProvider
*/
public function test_xmpp_jid_construct($jidText)
{
$jid = new XMPPJid($jidText);
$this->assertEquals($jidText, $jid->to_string());
}
public function jidPositiveProvider()
{
return array(
array('domain'),
array('domain.tld'),
array('1@domain'),
array('[email protected]'),
array('domain/res'),
array('domain.tld/res'),
array('1@domain/res'),
array('[email protected]/res'),
array('component.domain.tld'),
array('[email protected]/res'),
array('[email protected]/@res'),
array('[email protected]//res')
);
}
/**
* @dataProvider jidNegativeProvider
* @expectedException InvalidArgumentException
* @requires function XEP_0029::validateJID
*/
public function testJidNegative($jidText)
{
$jid = new XMPPJid($jidText);
}
public function jidNegativeProvider()
{
return array(
array('"@domain'),
array('&@domain'),
array("'@domain"),
array('/@domain'),
array(':@domain'),
array('<@domain'),
array('>@domain'),
array('@@domain'),
array("\x7F" . '@domain'),
array("\xFF\xFE" . '@domain'),
array("\xFF\xFF" . '@domain')
);
}
}
diff --git a/tests/XMPPMsgTest.php b/tests/XMPPMsgTest.php
index c421aab..4339488 100644
--- a/tests/XMPPMsgTest.php
+++ b/tests/XMPPMsgTest.php
@@ -1,89 +1,87 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-JAXL::dummy();
-
/**
*
* @author abhinavsingh
*
*/
class XMPPMsgTest extends PHPUnit_Framework_TestCase
{
public function test_xmpp_msg()
{
$msg = new XMPPMsg(array('to' => '[email protected]', 'from' => '[email protected]/~', 'type' => 'chat'), 'hi', 'thread1');
$this->assertEquals(
array(
'from' => '[email protected]/~',
'to' => '[email protected]',
'to_node' => '2',
'to_string' => '<message xmlns="jabber:client" to="[email protected]" from="[email protected]/~" type="chat">' .
'<body>hi</body><thread>thread1</thread></message>',
),
array(
'from' => $msg->from,
'to' => $msg->to,
'to_node' => $msg->to_node,
'to_string' => $msg->to_string(),
)
);
$msg->to = '[email protected]/sp';
$msg->body = 'hello world';
$msg->subject = 'some subject';
$this->assertEquals(
array(
'from' => '[email protected]/~',
'to' => '[email protected]/sp',
'to_node' => '4',
'to_string' => '<message xmlns="jabber:client" to="[email protected]/sp" from="[email protected]/~" type="chat">' .
'<body>hello world</body><thread>thread1</thread><subject>some subject</subject></message>',
),
array(
'from' => $msg->from,
'to' => $msg->to,
'to_node' => $msg->to_node,
'to_string' => $msg->to_string(),
)
);
}
}
diff --git a/tests/XMPPStanzaTest.php b/tests/XMPPStanzaTest.php
index 0244b5c..a50a14b 100644
--- a/tests/XMPPStanzaTest.php
+++ b/tests/XMPPStanzaTest.php
@@ -1,83 +1,81 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-JAXL::dummy();
-
/**
*
* @author abhinavsingh
*
*/
class XMPPStanzaTest extends PHPUnit_Framework_TestCase
{
public function test_xmpp_stanza_nested()
{
$xml = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]'));
$xml->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up()
->c('thread')->t('1234')->up()
->c('nested')
->c('nest')->t('nest1')->up()
->c('nest')->t('nest2')->up()
->c('nest')->t('nest3')->up()->up()
->c('c')->attrs(array('hash' => '84jsdmnskd'));
$stanza = new XMPPStanza($xml);
$this->assertEquals(
'<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested>' .
'<nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>',
$stanza->to_string()
);
}
public function test_xmpp_stanza_from_jaxl_xml()
{
// xml to stanza test
$xml = new JAXLXml('message', XMPP::NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q'));
$stanza = new XMPPStanza($xml);
$stanza->c('body')->t('hello world');
$this->assertEquals('XMPPStanza', get_class($stanza));
$this->assertEquals('JAXLXml', get_class($stanza->exists('body')));
$this->assertEquals('[email protected]', $stanza->to);
$this->assertEquals(
'<message xmlns="jabber:client" to="[email protected]" from="[email protected]/q">' .
'<body>hello world</body></message>',
$stanza->to_string()
);
}
}
diff --git a/tests/XMPPStreamTest.php b/tests/XMPPStreamTest.php
index 11f79c8..e6f6e79 100644
--- a/tests/XMPPStreamTest.php
+++ b/tests/XMPPStreamTest.php
@@ -1,61 +1,59 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-JAXL::dummy();
-
/**
*
* @author abhinavsingh
*
*/
class XMPPStreamTest extends PHPUnit_Framework_TestCase
{
public function test_xmpp_stream()
{
$this->markTestSkipped('Need help!');
$xmpp = new XMPPStream("test@localhost", "password");
$xmpp->connect();
$xmpp->start_stream();
while ($xmpp->sock->fd) {
$xmpp->sock->recv();
}
}
}
diff --git a/xep/xep_0030.php b/xep/xep_0030.php
index 3fb3d4b..0bc810b 100644
--- a/xep/xep_0030.php
+++ b/xep/xep_0030.php
@@ -1,98 +1,96 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0030 extends XMPPXep
{
const NS_DISCO_INFO = 'http://jabber.org/protocol/disco#info';
const NS_DISCO_ITEMS = 'http://jabber.org/protocol/disco#items';
//
// abstract method
//
public function init()
{
return array(
);
}
//
// api methods
//
public function get_info_pkt($entity_jid)
{
return $this->jaxl->get_iq_pkt(
array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid),
new JAXLXml('query', self::NS_DISCO_INFO)
);
}
public function get_info($entity_jid, $callback = null)
{
$pkt = $this->get_info_pkt($entity_jid);
if ($callback) {
$this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback);
}
$this->jaxl->send($pkt);
}
public function get_items_pkt($entity_jid)
{
return $this->jaxl->get_iq_pkt(
array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid),
new JAXLXml('query', self::NS_DISCO_ITEMS)
);
}
public function get_items($entity_jid, $callback = null)
{
$pkt = $this->get_items_pkt($entity_jid);
if ($callback) {
$this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback);
}
$this->jaxl->send($pkt);
}
//
// event callbacks
//
}
diff --git a/xep/xep_0045.php b/xep/xep_0045.php
index f8e871e..532b798 100644
--- a/xep/xep_0045.php
+++ b/xep/xep_0045.php
@@ -1,123 +1,121 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0045 extends XMPPXep
{
const NS_MUC = 'http://jabber.org/protocol/muc';
//
// abstract method
//
public function init()
{
return array();
}
public function send_groupchat($room_jid, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'groupchat',
'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid),
'from'=>$this->jaxl->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->jaxl->send($msg);
}
//
// api methods (occupant use case)
//
// room_full_jid simply means room jid with nick name as resource
public function get_join_room_pkt($room_full_jid, array $options)
{
$pkt = $this->jaxl->get_pres_pkt(
array(
'from'=>$this->jaxl->full_jid->to_string(),
'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid),
'id' => (isset($options['id'])) ? $options['id'] : uniqid()
)
);
$x = $pkt->c('x', self::NS_MUC);
if (isset($options['no_history'])) {
$x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0))->up();
}
if (isset($options['password'])) {
$x->c('password')->t($options['password'])->up();
}
return $x;
}
public function join_room($room_full_jid, array $options = array())
{
$pkt = $this->get_join_room_pkt($room_full_jid, $options);
$this->jaxl->send($pkt);
}
public function get_leave_room_pkt($room_full_jid)
{
return $this->jaxl->get_pres_pkt(array(
'type' => 'unavailable',
'from' => $this->jaxl->full_jid->to_string(),
'to' => ($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid
));
}
public function leave_room($room_full_jid)
{
$pkt = $this->get_leave_room_pkt($room_full_jid);
$this->jaxl->send($pkt);
}
//
// api methods (moderator use case)
//
//
// event callbacks
//
}
diff --git a/xep/xep_0060.php b/xep/xep_0060.php
index de054df..8f7b7f1 100644
--- a/xep/xep_0060.php
+++ b/xep/xep_0060.php
@@ -1,148 +1,146 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0060 extends XMPPXep
{
const NS_PUBSUB = 'http://jabber.org/protocol/pubsub';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods (entity use case)
//
//
// api methods (subscriber use case)
//
public function get_subscribe_pkt($service, $node, $jid = null)
{
$child = new JAXLXml('pubsub', self::NS_PUBSUB);
$child->c(
'subscribe',
null,
array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string()))
);
return $this->get_iq_pkt($service, $child);
}
public function subscribe($service, $node, $jid = null)
{
$this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid));
}
public function unsubscribe()
{
}
public function get_subscription_options()
{
}
public function set_subscription_options()
{
}
public function get_node_items()
{
}
//
// api methods (publisher use case)
//
public function get_publish_item_pkt($service, $node, $item)
{
$child = new JAXLXml('pubsub', self::NS_PUBSUB);
$child->c('publish', null, array('node' => $node));
$child->cnode($item);
return $this->get_iq_pkt($service, $child);
}
public function publish_item($service, $node, $item)
{
$this->jaxl->send($this->get_publish_item_pkt($service, $node, $item));
}
public function delete_item()
{
}
//
// api methods (owner use case)
//
public function get_create_node_pkt($service, $node)
{
$child = new JAXLXml('pubsub', self::NS_PUBSUB);
$child->c('create', null, array('node' => $node));
return $this->get_iq_pkt($service, $child);
}
public function create_node($service, $node)
{
$this->jaxl->send($this->get_create_node_pkt($service, $node));
}
//
// event callbacks
//
//
// local methods
//
// this always add attrs
protected function get_iq_pkt($service, $child, $type = 'set')
{
return $this->jaxl->get_iq_pkt(
array('type' => $type, 'from' => $this->jaxl->full_jid->to_string(), 'to' => $service),
$child
);
}
}
diff --git a/xep/xep_0077.php b/xep/xep_0077.php
index fff16f3..84050bd 100644
--- a/xep/xep_0077.php
+++ b/xep/xep_0077.php
@@ -1,86 +1,84 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0077 extends XMPPXep
{
const NS_FEATURE_REGISTER = 'http://jabber.org/features/iq-register';
const NS_INBAND_REGISTER = 'jabber:iq:register';
//
// abstract method
//
public function init()
{
return array(
);
}
//
// api methods
//
public function get_form_pkt($domain)
{
return $this->jaxl->get_iq_pkt(
array('to' => $domain, 'type' => 'get'),
new JAXLXml('query', self::NS_INBAND_REGISTER)
);
}
public function get_form($domain)
{
$this->jaxl->send($this->get_form_pkt($domain));
}
public function set_form($domain, array $form)
{
$query = new JAXLXml('query', self::NS_INBAND_REGISTER);
foreach ($form as $k => $v) {
$query->c($k, null, array(), $v)->up();
}
$pkt = $this->jaxl->get_iq_pkt(
array('to' => $domain, 'type' => 'set'),
$query
);
$this->jaxl->send($pkt);
}
}
diff --git a/xep/xep_0114.php b/xep/xep_0114.php
index 5f12eed..0211651 100644
--- a/xep/xep_0114.php
+++ b/xep/xep_0114.php
@@ -1,101 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0114 extends XMPPXep
{
const NS_JABBER_COMPONENT_ACCEPT = 'jabber:component:accept';
//
// abstract method
//
public function init()
{
return array(
'on_connect' => 'start_stream',
'on_stream_start' => 'start_handshake',
'on_handshake_stanza' => 'logged_in',
'on_error_stanza' => 'logged_out'
);
}
//
// event callbacks
//
public function start_stream()
{
$xml = sprintf(
'<stream:stream xmlns:stream="%s" to="%s" xmlns="%s">',
XMPP::NS_XMPP,
$this->jaxl->jid->to_string(),
self::NS_JABBER_COMPONENT_ACCEPT
);
$this->jaxl->send_raw($xml);
}
public function start_handshake($stanza)
{
_debug("starting component handshake");
$id = $stanza->id;
$hash = strtolower(sha1($id.$this->jaxl->pass));
$stanza = new JAXLXml('handshake', null, $hash);
$this->jaxl->send($stanza);
}
public function logged_in($stanza)
{
_debug("component handshake complete");
$this->jaxl->handle_auth_success();
return array("logged_in", 1);
}
public function logged_out($stanza)
{
if ($stanza->name == "error" && $stanza->ns == XMPP::NS_XMPP) {
$reason = $stanza->childrens[0]->name;
$this->jaxl->handle_auth_failure($reason);
$this->jaxl->send_end_stream();
return array("logged_out", 0);
} else {
_debug("uncatched stanza received in logged_out");
}
}
}
diff --git a/xep/xep_0115.php b/xep/xep_0115.php
index 8d4d630..b39336f 100644
--- a/xep/xep_0115.php
+++ b/xep/xep_0115.php
@@ -1,74 +1,72 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0115 extends XMPPXep
{
const NS_CAPS = 'http://jabber.org/protocol/caps';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods
//
public function get_caps_pkt($cat, $type, $lang, $name, $node, $features)
{
asort($features);
$S = $cat.'/'.$type.'/'.$lang.'/'.$name.'<';
foreach ($features as $feature) {
$S .= $feature.'<';
}
$ver = base64_encode(sha1($S, true));
$stanza = new JAXLXml('c', self::NS_CAPS, array('hash' => 'sha1', 'node' => $node, 'ver' => $ver));
return $stanza;
}
//
// event callbacks
//
}
diff --git a/xep/xep_0199.php b/xep/xep_0199.php
index 49678ea..a9270d1 100644
--- a/xep/xep_0199.php
+++ b/xep/xep_0199.php
@@ -1,62 +1,60 @@
<?php
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0199 extends XMPPXep
{
const NS_XMPP_PING = 'urn:xmpp:ping';
//
// abstract method
//
public function init()
{
return array(
'on_auth_success' => 'on_auth_success',
'on_get_iq' => 'on_xmpp_ping'
);
}
//
// api methods
//
public function get_ping_pkt()
{
$attrs = array(
'type' => 'get',
'from' => $this->jaxl->full_jid->to_string(),
'to' => $this->jaxl->full_jid->domain
);
return $this->jaxl->get_iq_pkt(
$attrs,
new JAXLXml('ping', self::NS_XMPP_PING)
);
}
public function ping()
{
$this->jaxl->send($this->get_ping_pkt());
}
//
// event callbacks
//
public function on_auth_success()
{
JAXLLoop::$clock->call_fun_periodic(30 * pow(10, 6), array(&$this, 'ping'));
}
public function on_xmpp_ping($stanza)
{
if ($stanza->exists('ping', self::NS_XMPP_PING)) {
$stanza->type = "result";
$stanza->to = $stanza->from;
$stanza->from = $this->jaxl->full_jid->to_string();
$this->jaxl->send($stanza);
}
}
}
diff --git a/xep/xep_0203.php b/xep/xep_0203.php
index ce31826..7aa6b89 100644
--- a/xep/xep_0203.php
+++ b/xep/xep_0203.php
@@ -1,61 +1,59 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0203 extends XMPPXep
{
const NS_DELAYED_DELIVERY = 'urn:xmpp:delay';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods
//
//
// event callbacks
//
}
diff --git a/xep/xep_0206.php b/xep/xep_0206.php
index d8ded76..9d39656 100644
--- a/xep/xep_0206.php
+++ b/xep/xep_0206.php
@@ -1,270 +1,268 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0206 extends XMPPXep
{
const NS_HTTP_BIND = 'http://jabber.org/protocol/httpbind';
const NS_BOSH = 'urn:xmpp:xbosh';
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
//
// event callbacks
//
/**
* @param JAXLXml|XMPPStanza|string $body
*/
public function send($body)
{
if (is_object($body)) {
$body = $body->to_string();
} else {
if (substr($body, 0, 15) == '<stream:stream ') {
$this->restarted = true;
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
'xmlns:xmpp' => self::NS_BOSH
));
$body = $body->to_string();
} elseif (substr($body, 0, 16) == '</stream:stream>') {
$body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
$body = $body->to_string();
} else {
$body = $this->wrap($body);
}
}
_debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
_debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
_debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
_debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
_error("no ch found");
exit;
}
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.
self::NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
$this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
$this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
$this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
'xmlns:xmpp' => self::NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
if (isset($this->jaxl->cfg['jid'])) {
$attrs['from'] = $this->jaxl->cfg['jid'];
}
$body = new JAXLXml('body', self::NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
$body = new JAXLXml('body', self::NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
_debug("disconnecting");
}
}
diff --git a/xep/xep_0249.php b/xep/xep_0249.php
index e776077..7e275c2 100644
--- a/xep/xep_0249.php
+++ b/xep/xep_0249.php
@@ -1,97 +1,95 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-
class XEP_0249 extends XMPPXep
{
const NS_DIRECT_MUC_INVITATION = 'jabber:x:conference';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods
//
public function get_invite_pkt(
$to_bare_jid,
$room_jid,
$password = null,
$reason = null,
$thread = null,
$continue = null
) {
$xattrs = array('jid' => $room_jid);
if ($password) {
$xattrs['password'] = $password;
}
if ($reason) {
$xattrs['reason'] = $reason;
}
if ($thread) {
$xattrs['thread'] = $thread;
}
if ($continue) {
$xattrs['continue'] = $continue;
}
return $this->jaxl->get_msg_pkt(
array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid),
null,
null,
null,
new JAXLXml('x', self::NS_DIRECT_MUC_INVITATION, $xattrs)
);
}
public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null)
{
$this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue));
}
//
// event callbacks
//
}
diff --git a/xmpp/xmpp_iq.php b/xmpp/xmpp_iq.php
index 14f041c..046eba8 100644
--- a/xmpp/xmpp_iq.php
+++ b/xmpp/xmpp_iq.php
@@ -1,48 +1,46 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_stanza.php';
-
class XMPPIq extends XMPPStanza
{
public function __construct($attrs)
{
parent::__construct('iq', $attrs);
}
}
diff --git a/xmpp/xmpp_msg.php b/xmpp/xmpp_msg.php
index c3e0de3..79167ca 100644
--- a/xmpp/xmpp_msg.php
+++ b/xmpp/xmpp_msg.php
@@ -1,58 +1,56 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_stanza.php';
-
class XMPPMsg extends XMPPStanza
{
public function __construct($attrs, $body = null, $thread = null, $subject = null)
{
parent::__construct('message', $attrs);
if ($body) {
$this->c('body')->t($body)->up();
}
if ($thread) {
$this->c('thread')->t($thread)->up();
}
if ($subject) {
$this->c('subject')->t($subject)->up();
}
}
}
diff --git a/xmpp/xmpp_pres.php b/xmpp/xmpp_pres.php
index ba2cd45..5ab4a83 100644
--- a/xmpp/xmpp_pres.php
+++ b/xmpp/xmpp_pres.php
@@ -1,58 +1,56 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_stanza.php';
-
class XMPPPres extends XMPPStanza
{
public function __construct($attrs, $status = null, $show = null, $priority = null)
{
parent::__construct('presence', $attrs);
if ($status) {
$this->c('status')->t($status)->up();
}
if ($show) {
$this->c('show')->t($show)->up();
}
if ($priority) {
$this->c('priority')->t($priority)->up();
}
}
}
diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php
index 1df8c0b..79e48e5 100644
--- a/xmpp/xmpp_stanza.php
+++ b/xmpp/xmpp_stanza.php
@@ -1,198 +1,194 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp.php';
-require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
-require_once JAXL_CWD.'/core/jaxl_xml.php';
-
/**
* Generic xmpp stanza object which provide convinient access pattern over xml objects
* Also to be able to convert an existing xml object into stanza object (to get access patterns going)
* this class doesn't extend xml, but infact works on a reference of xml object
* If not provided during constructor, new xml object is created and saved as reference
*
* @author abhinavsingh
*
*/
class XMPPStanza
{
/**
* @var JAXLXml
*/
private $xml;
/**
* @param JAXLXml|string $name
* @param array $attrs
* @param string $ns
*/
public function __construct($name, array $attrs = array(), $ns = XMPP::NS_JABBER_CLIENT)
{
if ($name instanceof JAXLXml) {
$this->xml = $name;
} else {
$this->xml = new JAXLXml($name, $ns, $attrs);
}
}
public function __call($method, $args)
{
return call_user_func_array(array($this->xml, $method), $args);
}
public function __get($prop)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
return isset($this->xml->attrs[$prop]) ? $this->xml->attrs[$prop] : null;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val) {
return null;
}
$val = new XMPPJid($val);
return $val->$key;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val = $this->xml->exists($prop);
if (!$val) {
return null;
}
return $val->text;
break;
default:
return null;
break;
}
}
public function __set($prop, $val)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop = $val;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
$this->xml->attrs[$prop] = $val;
return true;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val1 = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val1) {
$val1 = '';
}
$val1 = new XMPPJid($val1);
$val1->$key = $val;
$this->xml->attrs[$attr] = $val1->to_string();
return true;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val1 = $this->xml->exists($prop);
if (!$val1) {
$this->xml->c($prop)->t($val)->up();
} else {
$this->xml->update($prop, $val1->ns, $val1->attrs, $val);
}
return true;
break;
default:
return null;
break;
}
}
}
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php
index 8898bce..330db59 100644
--- a/xmpp/xmpp_stream.php
+++ b/xmpp/xmpp_stream.php
@@ -1,562 +1,550 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/core/jaxl_fsm.php';
-require_once JAXL_CWD.'/core/jaxl_xml.php';
-require_once JAXL_CWD.'/core/jaxl_xml_stream.php';
-require_once JAXL_CWD.'/core/jaxl_util.php';
-require_once JAXL_CWD.'/core/jaxl_socket_client.php';
-
-require_once JAXL_CWD.'/xmpp/xmpp.php';
-require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
-require_once JAXL_CWD.'/xmpp/xmpp_msg.php';
-require_once JAXL_CWD.'/xmpp/xmpp_pres.php';
-require_once JAXL_CWD.'/xmpp/xmpp_iq.php';
-
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
* @var JAXLSocketClient|XEP_0206
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
* @param JAXLSocketClient|XEP_0206 $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
$jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//_debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
_error("got invalid return value from state handler '".$this->state."', sending end stream...");
$this->send_end_stream();
$this->state = "logged_out";
_notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers");
}
/**
* @param JAXLXml|XMPPStanza $stanza
*/
public function send($stanza)
{
$this->trans->send($stanza->to_string());
}
/**
* @param string $data
*/
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.XMPP::NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.XMPP::NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.XMPP::NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', XMPP::NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', XMPP::NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', XMPP::NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', XMPP::NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
_debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', XMPP::NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', XMPP::NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//_debug("stream started");
return "wait_for_stream_features";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', XMPP::NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', XMPP::NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', XMPP::NS_BIND) ? true : false;
$sess = $stanza->exists('session', XMPP::NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', XMPP::NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
|
jaxl/JAXL | d585a910fed006aeef184730ccd7b8f2837175de | Set OS specific \r\n and \n | diff --git a/http/http_client.php b/http/http_client.php
index 5a376bd..33aacb2 100644
--- a/http/http_client.php
+++ b/http/http_client.php
@@ -1,157 +1,157 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class HTTPClient
{
/** @var string */
private $url = null;
private $parts = array();
private $headers = array();
private $data = null;
public $method = null;
/** @var JAXLSocketClient */
private $client = null;
/**
* @param string $url
* @param array $headers TODO: Currently not used.
* @param unknown $data TODO: Currently not used.
*/
public function __construct($url, array $headers = array(), $data = null)
{
$this->url = $url;
$this->headers = $headers;
$this->data = $data;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function start($method = 'GET')
{
$this->method = $method;
$this->parts = parse_url($this->url);
$transport = $this->transport();
$ip = $this->ip();
$port = $this->port();
$socket_path = $transport.'://'.$ip.':'.$port;
if ($this->client->connect($socket_path)) {
_debug("connection to $this->url established");
// send request data
$this->send_request();
// start main loop
JAXLLoop::run();
} else {
_debug("unable to open $this->url");
}
}
public function on_response($raw)
{
_info("got http response");
}
protected function send_request()
{
- $this->client->send($this->line()."\r\n");
- $this->client->send($this->ua()."\r\n");
- $this->client->send($this->host()."\r\n");
- $this->client->send("\r\n");
+ $this->client->send($this->line().HTTPServer::HTTP_CRLF);
+ $this->client->send($this->ua().HTTPServer::HTTP_CRLF);
+ $this->client->send($this->host().HTTPServer::HTTP_CRLF);
+ $this->client->send(HTTPServer::HTTP_CRLF);
}
//
// private methods on uri parts
//
private function line()
{
return $this->method.' '.$this->uri().' HTTP/1.1';
}
private function ua()
{
return 'User-Agent: jaxl_http_client/3.x';
}
private function host()
{
return 'Host: '.$this->parts['host'].':'.$this->port();
}
private function transport()
{
return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl');
}
private function ip()
{
return gethostbyname($this->parts['host']);
}
private function port()
{
return isset($this->parts['port']) ? $this->parts['port'] : 80;
}
private function uri()
{
$uri = $this->parts['path'];
if (isset($this->parts['query'])) {
$uri .= '?'.$this->parts['query'];
}
if (isset($this->parts['fragment'])) {
$uri .= '#'.$this->parts['fragment'];
}
return $uri;
}
}
diff --git a/http/http_request.php b/http/http_request.php
index e54d0d5..4d0e5a4 100644
--- a/http/http_request.php
+++ b/http/http_request.php
@@ -1,512 +1,512 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/http/http_multipart.php';
//
// These methods are available only once
// $request FSM has reached 'headers_received' state
//
// following shortcuts are available
// on received $request object:
//
// $request->{status_code_name}($headers, $body)
// $request->{status_code_name}($body, $headers)
//
// $request->{status_code_name}($headers)
// $request->{status_code_name}($body)
//
// following specific methods are also available:
//
// $request->send_line($code)
// $request->send_header($key, $value)
// $request->send_headers($headers)
// $request->send_message($string)
//
// all the above methods can also be directly performed using:
//
// $request->send_response($code, $headers = array(), $body = null)
//
// Note: All the send_* methods do not manage connection close/keep-alive logic,
// it is upto you to do that, by default connection will usually be dropped
// on client disconnect if not handled by you.
//
class HTTPRequest extends JAXLFsm
{
// peer identifier
public $sock = null;
public $ip = null;
public $port = null;
// request line
public $version = null;
public $method = null;
public $resource = null;
public $path = null;
public $query = array();
// headers and body
public $headers = array();
public $body = null;
public $recvd_body_len = 0;
// is true if 'Expect: 100-Continue'
// request header has been seen
public $expect = false;
// set if there is Content-Type: multipart/form-data; boundary=...
// header already seen
public $multipart = null;
// callback for send/read/close actions on accepted sock
private $send_cb = null;
private $read_cb = null;
private $close_cb = null;
private $shortcuts = array(
'ok' => 200, // 2xx
'redirect' => 302, 'not_modified' => 304, // 3xx
'not_found' => 404, 'bad_request' => 400, // 4xx
'internal_error' => 500, // 5xx
'recv_body' => true, 'close' => true // others
);
public function __construct($sock, $addr)
{
$this->sock = $sock;
$addr = explode(":", $addr);
$this->ip = $addr[0];
if (count($addr) == 2) {
$this->port = $addr[1];
}
parent::__construct("setup");
}
public function __destruct()
{
_debug("http request going down in ".$this->state." state");
}
public function state()
{
return $this->state;
}
//
// abstract method implementation
//
public function handle_invalid_state($r)
{
_debug("handle invalid state called with");
var_dump($r);
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case 'set_sock_cb':
$this->send_cb = $args[0];
$this->read_cb = $args[1];
$this->close_cb = $args[2];
return 'wait_for_request_line';
break;
default:
_warning("uncatched $event");
return 'setup';
}
}
public function wait_for_request_line($event, $args)
{
switch ($event) {
case 'line':
$this->line($args[0], $args[1], $args[2]);
return 'wait_for_headers';
break;
default:
_warning("uncatched $event");
return 'wait_for_request_line';
}
}
public function wait_for_headers($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'maybe_headers_received';
default:
_warning("uncatched $event");
return 'wait_for_headers';
}
}
public function maybe_headers_received($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'headers_received';
break;
case 'body':
return $this->wait_for_body($event, $args);
break;
default:
_warning("uncatched $event");
return 'maybe_headers_received';
}
}
public function wait_for_body($event, $args)
{
switch ($event) {
case 'body':
$content_length = $this->headers['Content-Length'];
$rcvd = $args[0];
$rcvd_len = strlen($rcvd);
$this->recvd_body_len += $rcvd_len;
if ($this->body === null) {
$this->body = $rcvd;
} else {
$this->body .= $rcvd;
}
if ($this->multipart) {
// boundary start, content_disposition, form data, boundary start, ....., boundary end
// these define various states of a multipart/form-data
- $form_data = explode("\r\n", $rcvd);
+ $form_data = explode(HTTPServer::HTTP_CRLF, $rcvd);
foreach ($form_data as $data) {
//_debug("passing $data to multipart fsm");
if (!$this->multipart->process($data)) {
_debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
}
}
if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'set_header':
$content_length = $this->headers['Content-Length'];
$body = implode(":", $args);
$rcvd_len = strlen($body);
$this->recvd_body_len += $rcvd_len;
if (!$this->multipart->process($body)) {
_debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'empty_line':
$content_length = $this->headers['Content-Length'];
if (!$this->multipart->process('')) {
_debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
default:
_warning("uncatched $event");
return 'wait_for_body';
}
}
// headers and may be body received
public function headers_received($event, $args)
{
switch ($event) {
case 'empty_line':
return 'headers_received';
break;
default:
if (substr($event, 0, 5) == 'send_') {
$protected = '_'.$event;
if (method_exists($this, $protected)) {
call_user_func_array(array(&$this, $protected), $args);
return 'headers_received';
} else {
_debug("non-existant method $event called");
return 'headers_received';
}
} elseif (isset($this->shortcuts[$event])) {
return $this->handle_shortcut($event, $args);
} else {
_warning("uncatched $event ".$args[0]);
return 'headers_received';
}
}
}
public function closed($event, $args)
{
_warning("uncatched $event");
}
// sets input headers
// called internally for every header received
protected function set_header($k, $v)
{
$k = trim($k);
$v = ltrim($v);
// is expect header?
if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') {
$this->expect = true;
}
// is multipart form data?
if (strtolower($k) == 'content-type') {
$ctype = explode(';', $v);
if (count($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') {
$boundary = explode('=', trim($ctype[1]));
if (strtolower(trim($boundary[0])) == 'boundary') {
_debug("multipart with boundary $boundary[1] detected");
$this->multipart = new HTTPMultiPart(ltrim($boundary[1]));
}
}
}
$this->headers[trim($k)] = trim($v);
}
// shortcut handler
protected function handle_shortcut($event, $args)
{
_debug("executing shortcut '$event'");
switch ($event) {
// http status code shortcuts
case 'ok':
case 'redirect':
case 'not_modified':
case 'bad_request':
case 'not_found':
case 'internal_error':
list($headers, $body) = $this->parse_shortcut_args($args);
$code = $this->shortcuts[$event];
$this->send_response($code, $headers, $body);
$this->close();
return 'closed';
break;
// others
case 'recv_body':
// send expect header if required
if ($this->expect) {
$this->expect = false;
$this->send_line(100);
}
// read data
$this->read();
return 'wait_for_body';
break;
case 'close':
$this->close();
return 'closed';
break;
}
}
private function parse_shortcut_args($args)
{
if (count($args) == 0) {
$body = null;
$headers = array();
}
if (count($args) == 1) {
// http headers or body only received
if (is_array($args[0])) {
// http headers only
$headers = $args[0];
$body = null;
} else {
// body only
$body = $args[0];
$headers = array();
}
} elseif (count($args) == 2) {
// body and http headers both received
if (is_array($args[0])) {
// header first
$body = $args[1];
$headers = $args[0];
} else {
// body first
$body = $args[0];
$headers = $args[1];
}
}
return array($headers, $body);
}
//
// send methods
// available only on 'headers_received' state
//
protected function send_line($code)
{
$raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTPServer::HTTP_CRLF;
$this->send($raw);
}
protected function send_header($k, $v)
{
$raw = $k.': '.$v.HTTPServer::HTTP_CRLF;
$this->send($raw);
}
protected function send_headers($code, $headers)
{
foreach ($headers as $k => $v) {
$this->send_header($k, $v);
}
}
protected function send_body($body)
{
$this->send($body);
}
protected function send_response($code, array $headers = array(), $body = null)
{
// send out response line
$this->send_line($code);
// set content length of body exists and is not already set
if ($body && !isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($body);
}
// send out headers
$this->send_headers($code, $headers);
// send body
// prefixed with an empty line
_debug("sending out HTTP_CRLF prefixed body");
if ($body) {
$this->send_body(HTTPServer::HTTP_CRLF.$body);
}
}
//
// internal methods
//
// initializes status line elements
private function line($method, $resource, $version)
{
$this->method = $method;
$this->resource = $resource;
$resource = explode("?", $resource);
$this->path = $resource[0];
if (count($resource) == 2) {
$query = $resource[1];
$query = explode("&", $query);
foreach ($query as $q) {
$q = explode("=", $q);
if (count($q) == 1) {
$q[1] = "";
}
$this->query[$q[0]] = $q[1];
}
}
$this->version = $version;
}
private function send($raw)
{
call_user_func($this->send_cb, $this->sock, $raw);
}
private function read()
{
call_user_func($this->read_cb, $this->sock);
}
private function close()
{
call_user_func($this->close_cb, $this->sock);
}
}
diff --git a/jaxlctl b/jaxlctl
index 5269121..890aaca 100755
--- a/jaxlctl
+++ b/jaxlctl
@@ -1,200 +1,200 @@
#!/usr/bin/env php
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
error_reporting(E_ALL | E_STRICT);
date_default_timezone_set('UTC');
$params = $argv;
$exe = array_shift($params);
$command = array_shift($params);
require_once 'jaxl.php';
JAXLLogger::$level = JAXLLogger::INFO;
// TODO: an abstract JAXLCtlCommand class
// with seperate class per command
// a mechanism to register new commands
class JAXLCtl
{
protected $ipc = null;
protected $buffer = '';
protected $buffer_cb = null;
protected $cli = null;
public $dots = "....... ";
protected $symbols = array();
public function __construct($command, $params)
{
global $exe;
if (method_exists($this, $command)) {
$r = call_user_func_array(array(&$this, $command), $params);
if (count($r) == 2) {
list($buffer_cb, $quit_cb) = $r;
$this->buffer_cb = $buffer_cb;
$this->cli = new JAXLCli(array(&$this, 'onTerminalInput'), $quit_cb);
$this->run();
} else {
_colorize("oops! internal command error", JAXLLogger::ERROR);
exit;
}
} else {
_colorize("error: invalid command '$command' received", JAXLLogger::ERROR);
_colorize("type '$exe help' for list of available commands", JAXLLogger::NOTICE);
exit;
}
}
public function run()
{
JAXLCli::prompt();
JAXLLoop::run();
}
public function onTerminalInput($raw)
{
$raw = trim($raw);
$last = substr($raw, -1, 1);
if ($last == ";") {
// dispatch to buffer callback
call_user_func($this->buffer_cb, $this->buffer.$raw);
$this->buffer = '';
} elseif ($last == '\\') {
$this->buffer .= substr($raw, 0, -1);
echo $this->dots;
} else {
// buffer command
$this->buffer .= $raw."; ";
echo $this->dots;
}
}
public static function printHelp()
{
global $exe;
- _colorize("Usage: $exe command [options...]\n", JAXLLogger::INFO);
+ _colorize("Usage: $exe command [options...]".PHP_EOL, JAXLLogger::INFO);
_colorize("Commands:", JAXLLogger::NOTICE);
_colorize(" help This help text", JAXLLogger::DEBUG);
_colorize(" debug Attach a debug console to a running JAXL daemon", JAXLLogger::DEBUG);
_colorize(" shell Open up Jaxl shell emulator", JAXLLogger::DEBUG);
- echo "\n";
+ echo PHP_EOL;
}
protected function help()
{
JAXLCtl::printHelp();
exit;
}
//
// shell command
//
protected function shell()
{
return array(array(&$this, 'onShellInput'), array(&$this, 'onShellQuit'));
}
private function eval_($raw, $symbols)
{
extract($symbols);
eval($raw);
$g = get_defined_vars();
unset($g['raw']);
unset($g['symbols']);
return $g;
}
public function onShellInput($raw)
{
$this->symbols = $this->eval_($raw, $this->symbols);
JAXLCli::prompt();
}
public function onShellQuit()
{
exit;
}
//
// debug command
//
protected function debug($sock_path)
{
$this->ipc = new JAXLSocketClient();
$this->ipc->set_callback(array(&$this, 'onDebugResponse'));
$this->ipc->connect('unix://'.$sock_path);
return array(array(&$this, 'onDebugInput'), array(&$this, 'onDebugQuit'));
}
public function onDebugResponse($raw)
{
$ret = unserialize($raw);
print_r($ret);
- echo "\n";
+ echo PHP_EOL;
JAXLCli::prompt();
}
public function onDebugInput($raw)
{
$this->ipc->send($this->buffer.$raw);
}
public function onDebugQuit()
{
$this->ipc->disconnect();
exit;
}
}
// we atleast need a command argument
if ($argc < 2) {
JAXLCtl::printHelp();
exit;
}
$ctl = new JAXLCtl($command, $params);
-echo "done\n";
+echo "done".PHP_EOL;
|
jaxl/JAXL | 1df9620ecb7a7726b8603375dc767741c124f06c | Use autoload from composer | diff --git a/examples/_bootstrap.php b/examples/_bootstrap.php
new file mode 100644
index 0000000..ebf2855
--- /dev/null
+++ b/examples/_bootstrap.php
@@ -0,0 +1,26 @@
+<?php
+/**
+ * Bootstrap for examples.
+ */
+
+error_reporting(E_ALL | E_STRICT);
+
+if (PHP_SAPI !== 'cli') {
+ echo 'Warning: script should be invoked via the CLI version of PHP, not the '.PHP_SAPI.' SAPI'.PHP_EOL;
+}
+
+if (!ini_get('date.timezone')) {
+ ini_set('date.timezone', 'UTC');
+}
+
+foreach (array(
+ dirname(__FILE__) . '/../../autoload.php',
+ dirname(__FILE__) . '/../vendor/autoload.php',
+ dirname(__FILE__) . '/vendor/autoload.php'
+) as $file) {
+ if (file_exists($file)) {
+ require $file;
+ break;
+ }
+}
+unset($file);
diff --git a/examples/curl.php b/examples/curl.php
index 6937297..acbb96b 100644
--- a/examples/curl.php
+++ b/examples/curl.php
@@ -1,49 +1,49 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if ($argc < 2) {
- echo "Usage: $argv[0] url\n";
+ echo "Usage: $argv[0] url".PHP_EOL;
exit;
}
-require_once 'jaxl.php';
JAXLLogger::$level = JAXLLogger::DEBUG;
-require_once JAXL_CWD.'/http/http_client.php';
$request = new HTTPClient($argv[1]);
$request->start();
diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php
index 552321c..0b99c3c 100644
--- a/examples/echo_bosh_bot.php
+++ b/examples/echo_bosh_bot.php
@@ -1,106 +1,107 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if ($argc < 3) {
- echo "Usage: $argv[0] jid pass\n";
+ echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
-require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'bosh_url' => 'http://localhost:5280/http-bind',
// (optional) srv lookup is done if not provided
// for bosh client 'host' value is used for 'route' attribute
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
// for bosh client 'port' value is used for 'route' attribute
//'port' => 5222,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXLLogger::INFO
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/echo_bot.php b/examples/echo_bot.php
index b4d1dc0..b3b2d86 100644
--- a/examples/echo_bot.php
+++ b/examples/echo_bot.php
@@ -1,147 +1,148 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
// Run as:
// php examples/echo_bot.php root@localhost password
// php examples/echo_bot.php root@localhost password DIGEST-MD5
// php examples/echo_bot.php localhost "" ANONYMOUS
if ($argc < 3) {
- echo "Usage: $argv[0] jid pass auth_type\n";
+ echo "Usage: $argv[0] jid pass auth_type".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
-require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (optional) srv lookup is done if not provided
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
//'port' => 5222,
// (optional) defaults to false
//'force_tls' => true,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXLLogger::INFO
));
//
// required XEP's
//
$client->require_xep(array(
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
});
// by default JAXL instance catches incoming roster list results and updates
// roster list is parsed/cached and an event 'on_roster_update' is emitted
$client->add_cb('on_roster_update', function () {
//global $client;
//print_r($client->roster);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
_info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_presence_stanza', function ($stanza) {
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
_info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start(array(
'--with-debug-shell' => true,
'--with-unix-sock' => true
));
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php
index aa64145..bcb106e 100644
--- a/examples/echo_component_bot.php
+++ b/examples/echo_component_bot.php
@@ -1,98 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if ($argc != 5) {
- echo "Usage: $argv[0] jid pass host port\n";
+ echo "Usage: $argv[0] jid pass host port".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
-require_once 'jaxl.php';
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'host' => $argv[3],
'port' => $argv[4],
'log_level' => JAXLLogger::INFO
));
//
// XEP's required (required)
//
$comp->require_xep(array(
'0114' // jabber component protocol
));
//
// add necessary event callbacks here
//
$comp->add_cb('on_auth_success', function () {
_info("got on_auth_success cb");
});
$comp->add_cb('on_auth_failure', function ($reason) {
global $comp;
$comp->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$comp->add_cb('on_chat_message', function ($stanza) {
global $comp;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $comp->jid->to_string();
$comp->send($stanza);
});
$comp->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$comp->start();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/echo_http_server.php b/examples/echo_http_server.php
index 2eb0e0c..e91de77 100644
--- a/examples/echo_http_server.php
+++ b/examples/echo_http_server.php
@@ -1,59 +1,59 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-// include and configure logger
-require_once 'jaxl.php';
+require dirname(__FILE__) . '/_bootstrap.php';
+
+// configure logger
JAXLLogger::$level = JAXLLogger::INFO;
// print usage notice and parse addr/port parameters if passed
_colorize("Usage: $argv[0] port (default: 9699)", JAXLLogger::NOTICE);
$port = ($argc == 2 ? $argv[1] : 9699);
// initialize http server
-require_once JAXL_CWD.'/http/http_server.php';
$http = new HTTPServer($port);
// catch all incoming requests here
function on_request($request)
{
$body = json_encode($request);
$request->ok($body, array('Content-Type' => 'application/json'));
}
// start http server
$http->start('on_request');
diff --git a/examples/echo_unix_sock_server.php b/examples/echo_unix_sock_server.php
index 1e2c6a9..ed9a38a 100644
--- a/examples/echo_unix_sock_server.php
+++ b/examples/echo_unix_sock_server.php
@@ -1,62 +1,63 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if ($argc < 2) {
- echo "Usage: $argv[0] /path/to/server.sock\n";
+ echo "Usage: $argv[0] /path/to/server.sock".PHP_EOL;
exit;
}
-require_once 'jaxl.php';
JAXLLogger::$level = JAXLLogger::INFO;
$server = null;
function on_request($client, $raw)
{
global $server;
$server->send($client, $raw);
_info("got client callback ".$raw);
}
if (file_exists($argv[1])) {
unlink($argv[1]);
}
$server = new JAXLSocketServer('unix://'.$argv[1], null, 'on_request');
JAXLLoop::run();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/http_bind.php b/examples/http_bind.php
index de1ce9e..a050e09 100644
--- a/examples/http_bind.php
+++ b/examples/http_bind.php
@@ -1,64 +1,65 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if (!isset($_GET['jid']) || !isset($_GET['pass'])) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
-require_once '../jaxl.php';
$client = new JAXL(array(
'jid' => $_GET['jid'],
'pass' => $_GET['pass'],
'bosh_url' => 'http://localhost:5280/http-bind',
'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
});
//
// finally start configured xmpp stream
//
$client->start();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php
index 1c46787..c520b0f 100644
--- a/examples/http_pre_bind.php
+++ b/examples/http_pre_bind.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
// http pre bind php script
$body = file_get_contents("php://input");
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (!isset($attrs['to']) &&
!isset($attrs['rid']) &&
!isset($attrs['wait']) &&
!isset($attrs['hold'])
) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
-require_once '../jaxl.php';
-
$to = (string)$attrs['to'];
$rid = (int)$attrs['rid'];
$wait = (int)$attrs['wait'];
$hold = (int)$attrs['hold'];
list($host, $port) = JAXLUtil::get_dns_srv($to);
$client = new JAXL(array(
'domain' => $to,
'host' => $host,
'port' => $port,
'bosh_url' => 'http://localhost:5280/http-bind',
'bosh_rid' => $rid,
'bosh_wait' => $wait,
'bosh_hold' => $hold,
'auth_type' => 'ANONYMOUS',
'log_level' => JAXLLogger::INFO
));
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
echo sprintf(
'<body xmlns="%s" sid="%s" rid="%s" jid="%s"/>',
XEP_0206::NS_HTTP_BIND,
$client->xeps['0206']->sid,
$client->xeps['0206']->rid,
$client->full_jid->to_string()
);
exit;
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
_info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
});
//
// finally start configured xmpp stream
//
$client->start();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php
index 784f499..824ea87 100644
--- a/examples/http_rest_server.php
+++ b/examples/http_rest_server.php
@@ -1,127 +1,127 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-// include and configure logger
-require_once 'jaxl.php';
+require dirname(__FILE__) . '/_bootstrap.php';
+
+// configure logger
JAXLLogger::$level = JAXLLogger::INFO;
// print usage notice and parse addr/port parameters if passed
_colorize("Usage: $argv[0] port (default: 9699)", JAXLLogger::NOTICE);
$port = ($argc == 2 ? $argv[1] : 9699);
// initialize http server
-require_once JAXL_CWD.'/http/http_server.php';
$http = new HTTPServer($port);
// callback method for dispatch rule (see below)
function index($request)
{
$request->send_response(
200,
array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>'
);
$request->close();
}
// callback method for dispatch rule (see below)
function upload($request)
{
if ($request->method == 'GET') {
$request->ok(
array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" ' .
'action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" ' .
'value="upload"/></form></body></html>'
);
} elseif ($request->method == 'POST') {
if ($request->body === null && $request->expect) {
$request->recv_body();
} else {
// got upload body, save it
_info("file upload complete, got ".strlen($request->body)." bytes of data");
$upload_data = $request->multipart->form_data[0]['body'];
$request->ok(
$upload_data,
array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])
);
}
}
}
// add dispatch rules with callback method as first argument
$index = array('index', '^/$');
$upload = array('upload', '^/upload', array('GET', 'POST'));
// some REST CRUD style callback methods
// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules
function create_event($request)
{
_info("got event create request");
$request->close();
}
function read_event($request, $pk)
{
_info("got event read request for $pk");
$request->close();
}
function update_event($request, $pk)
{
_info("got event update request for $pk");
$request->close();
}
function delete_event($request, $pk)
{
_info("got event delete request for $pk");
$request->close();
}
$event_create = array('create_event', '^/event/create/$', array('PUT'));
$event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD'));
$event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST'));
$event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE'));
// prepare rule set
$rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete);
$http->dispatch($rules);
// start http server
$http->start();
diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php
index f007233..f279272 100644
--- a/examples/muc_log_bot.php
+++ b/examples/muc_log_bot.php
@@ -1,146 +1,147 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if ($argc < 5) {
- echo "Usage: $argv[0] host jid pass [email protected] nickname\n";
+ echo "Usage: $argv[0] host jid pass [email protected] nickname".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
-require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[2],
'pass' => $argv[3],
'host' => $argv[1],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0045', // MUC
'0203', // Delayed Delivery
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$_room_full_jid = $argv[4]."/".$argv[5];
$room_full_jid = new XMPPJid($_room_full_jid);
$client->add_cb('on_auth_success', function () {
global $client, $room_full_jid;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// join muc room
$client->xeps['0045']->join_room($room_full_jid);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_groupchat_message', function ($stanza) {
global $client;
$from = new XMPPJid($stanza->from);
$delay = $stanza->exists('delay', XEP_0203::NS_DELAYED_DELIVERY);
if ($from->resource) {
echo sprintf(
"message stanza rcvd from %s saying... %s, %s".PHP_EOL,
$from->resource,
$stanza->body,
$delay ? "delay timestamp ".$delay->attrs['stamp'] : "timestamp ".gmdate("Y-m-dTH:i:sZ")
);
} else {
$subject = $stanza->exists('subject');
if ($subject) {
echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".
$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL;
}
}
});
$client->add_cb('on_presence_stanza', function ($stanza) {
global $client, $room_full_jid;
$from = new XMPPJid($stanza->from);
// self-stanza received, we now have complete room roster
if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) {
if (($x = $stanza->exists('x', XEP_0045::NS_MUC.'#user')) !== false) {
if (($status = $x->exists('status', null, array('code' => '110'))) !== false) {
$item = $x->exists('item');
_info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].
", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']);
} else {
_info("xmlns #user have no x child element");
}
} else {
_warning("=======> odd case 1");
}
} elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) {
// stanza from other users received
if (($x = $stanza->exists('x', XEP_0045::NS_MUC.'#user')) !== false) {
$item = $x->exists('item');
echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".
$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL;
} else {
_warning("=======> odd case 2");
}
} else {
_warning("=======> odd case 3");
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/multi_client.php b/examples/multi_client.php
index 14b8e9d..a07c5dc 100644
--- a/examples/multi_client.php
+++ b/examples/multi_client.php
@@ -1,130 +1,129 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
// input multiple account credentials
$accounts = array();
$add_new = true;
while ($add_new) {
$jid = readline('Enter Jabber Id: ');
$pass = readline('Enter Password: ');
$accounts[] = array($jid, $pass);
$next = readline('Add another account (y/n): ');
$add_new = $next == 'y' ? true : false;
}
-// setup jaxl
-require_once 'jaxl.php';
-
//
// common callbacks
//
function on_auth_success($client)
{
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
}
function on_auth_failure($client, $reason)
{
_info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
}
function on_chat_message($client, $stanza)
{
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
}
function on_presence_stanza($client, $stanza)
{
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
_info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
}
function on_disconnect($client)
{
_info("got on_disconnect cb");
}
//
// bootstrap all account instances
//
foreach ($accounts as $account) {
$client = new JAXL(array(
'jid' => $account[0],
'pass' => $account[1],
'log_level' => JAXLLogger::DEBUG,
// Enable multi client support.
// This will force 1st parameter of callbacks as connected client instance.
'multi_client' => true
));
$client->add_cb('on_auth_success', 'on_auth_success');
$client->add_cb('on_auth_failure', 'on_auth_failure');
$client->add_cb('on_chat_message', 'on_chat_message');
$client->add_cb('on_presence_stanza', 'on_presence_stanza');
$client->add_cb('on_disconnect', 'on_disconnect');
$client->connect($client->get_socket_path());
$client->start_stream();
}
// start core loop
JAXLLoop::run();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/pipes.php b/examples/pipes.php
index 697251f..37f720e 100644
--- a/examples/pipes.php
+++ b/examples/pipes.php
@@ -1,57 +1,55 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-// include and configure logger
-require_once 'jaxl.php';
-JAXLLogger::$level = JAXLLogger::INFO;
+require dirname(__FILE__) . '/_bootstrap.php';
-// include jaxl pipes
-require_once JAXL_CWD.'/core/jaxl_pipe.php';
+// configure logger
+JAXLLogger::$level = JAXLLogger::INFO;
// initialize
$pipe_name = getmypid();
$pipe = new JAXLPipe($pipe_name);
// add read event callback
$pipe->set_callback(function ($data) {
global $pipe;
_info("read ".trim($data)." from pipe");
});
JAXLLoop::run();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/publisher.php b/examples/publisher.php
index d66a78e..3ee089f 100644
--- a/examples/publisher.php
+++ b/examples/publisher.php
@@ -1,101 +1,102 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if ($argc < 3) {
- echo "Usage: $argv[0] jid pass\n";
+ echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
-require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// publish
$item = new JAXLXml('item', null, array('id' => time()));
$item->c('entry', 'http://www.w3.org/2005/Atom');
$item->c('title')->t('Soliloquy')->up();
$item->c('summary')->t('To be, or not to be: that is the question')->up();
$item->c(
'link',
null,
array('rel' => 'alternate', 'type' => 'text/html', 'href' => 'http://denmark.lit/2003/12/13/atom03')
)->up();
$item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up();
$item->c('published')->t('2003-12-13T18:30:02Z')->up();
$item->c('updated')->t('2003-12-13T18:30:02Z')->up();
$client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/register_user.php b/examples/register_user.php
index c31ef1f..90f2653 100644
--- a/examples/register_user.php
+++ b/examples/register_user.php
@@ -1,167 +1,168 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if ($argc < 2) {
- echo "Usage: $argv[0] domain\n";
+ echo "Usage: $argv[0] domain".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
-require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'log_level' => JAXLLogger::DEBUG
));
$client->require_xep(array(
'0077' // InBand Registration
));
//
// below are two states which become part of
// our client's xmpp_stream lifecycle
// consider as if these methods are directly
// inside xmpp_stream state machine
//
// Note: $stanza = $args[0] is an instance of
// JAXLXml in xmpp_stream state methods,
// it is yet not ready for easy access
// patterns available on XMPPStanza instances
//
$form = array();
function wait_for_register_response($event, $args)
{
global $client, $form;
if ($event == 'stanza_cb') {
$stanza = $args[0];
if ($stanza->name == 'iq') {
$form['type'] = $stanza->attrs['type'];
if ($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
} elseif ($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo sprintf(
"registration failed with error code: %s and type: %s".PHP_EOL,
$error->attrs['code'],
$error->attrs['type']
);
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
}
}
} else {
_notice("unhandled event $event rcvd");
}
}
function wait_for_register_form($event, $args)
{
global $client, $form;
$stanza = $args[0];
$query = $stanza->exists('query', XEP_0077::NS_INBAND_REGISTER);
if ($query) {
$instructions = $query->exists('instructions');
if ($instructions) {
echo $instructions->text.PHP_EOL;
}
foreach ($query->childrens as $k => $child) {
if ($child->name != 'instructions') {
$form[$child->name] = readline($child->name.":");
}
}
$client->xeps['0077']->set_form($stanza->attrs['from'], $form);
return "wait_for_register_response";
} else {
$client->end_stream();
return "logged_out";
}
}
//
// add necessary event callbacks here
//
$client->add_cb('on_stream_features', function ($stanza) {
global $client, $argv;
$client->xeps['0077']->get_form($argv[1]);
return "wait_for_register_form";
});
$client->add_cb('on_disconnect', function () {
global $form;
_info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
});
//
// finally start configured xmpp stream
//
$client->start();
//
// if registration was successful
// try to connect with newly registered account
//
if ($form['type'] == 'result') {
_info("connecting newly registered user account");
$client = new JAXL(array(
'jid' => $form['username'].'@'.$argv[1],
'pass' => $form['password'],
'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
$client->set_status('Available');
});
$client->start();
}
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/subscriber.php b/examples/subscriber.php
index 252792a..13d15ea 100644
--- a/examples/subscriber.php
+++ b/examples/subscriber.php
@@ -1,96 +1,97 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if ($argc < 3) {
- echo "Usage: $argv[0] jid pass\n";
+ echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
-require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// subscribe
$client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node');
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_headline_message', function ($stanza) {
global $client;
if (($event = $stanza->exists('event', XEP_0060::NS_PUBSUB.'#event'))) {
_info("got pubsub event");
} else {
_warning("unknown headline message rcvd");
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
-echo "done\n";
+echo "done".PHP_EOL;
diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php
index a470a67..d3924e6 100644
--- a/examples/xmpp_rest.php
+++ b/examples/xmpp_rest.php
@@ -1,75 +1,75 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
// View explanation for this example here:
// https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ
if ($argc < 3) {
- echo "Usage: $argv[0] jid pass\n";
+ echo "Usage: $argv[0] jid pass".PHP_EOL;
exit;
}
// initialize xmpp client
-require_once 'jaxl.php';
$xmpp = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
// register callbacks on required xmpp events
$xmpp->add_cb('on_auth_success', function () {
global $xmpp;
_info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string());
});
// initialize http server
-require_once JAXL_CWD.'/http/http_server.php';
$http = new HTTPServer();
// add generic callback
// you can also dispatch REST style callback
// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules
$http->cb = function ($request) {
// For demo purposes we simply return xmpp client full jid
global $xmpp;
$request->ok($xmpp->full_jid->to_string());
};
// This will start main JAXLLoop,
// hence we don't need to call $http->start() explicitly
$xmpp->start();
diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php
index 85c0387..8fe2c91 100644
--- a/examples/xoauth2_gtalk_client.php
+++ b/examples/xoauth2_gtalk_client.php
@@ -1,97 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
+require dirname(__FILE__) . '/_bootstrap.php';
+
if ($argc != 3) {
- echo "Usage: $argv[0] jid access_token\n";
+ echo "Usage: $argv[0] jid access_token".PHP_EOL;
exit;
}
//
// initialize JAXL object with initial config
//
-require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// force tls
'force_tls' => true,
// (required) perform X-OAUTH2
'auth_type' => 'X-OAUTH2',
// (optional)
//'resource' => 'resource',
'log_level' => JAXLLogger::DEBUG
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
-echo "done\n";
+echo "done".PHP_EOL;
|
jaxl/JAXL | c236559c5ae24c9cebf3a74e89326d0fca25dc50 | Fix test and don't polute autoload with tests | diff --git a/composer.json b/composer.json
index 64b0eb1..2aeb5d9 100644
--- a/composer.json
+++ b/composer.json
@@ -1,46 +1,49 @@
{
"name": "jaxl/jaxl",
"type": "library",
"description": "Jaxl - Async, Non-Blocking, Event based Networking Library in PHP.",
"keywords": ["xmpp", "jabber", "http", "asynchronous", "non blocking", "event loop", "php", "jaxl", "abhinavsingh"],
"homepage": "http://jaxl.readthedocs.org/en/latest/index.html",
"license": "MIT",
"support": {
"forum": "https://groups.google.com/forum/#!forum/jaxl",
"issues": "https://github.com/jaxl/JAXL/issues",
"source": "https://github.com/jaxl/JAXL"
},
"authors": [
{
"name": "Abhinavsingh",
"homepage": "https://abhinavsingh.com/"
}
],
"require": {
"php": ">=5.2.4",
"ext-curl": "*",
"ext-hash": "*",
"ext-json": "*",
"ext-libxml": "*",
"ext-openssl": "*",
"ext-pcre": "*",
"ext-sockets": "*"
},
"require-dev": {
"phpunit/phpunit": "^3.7.0",
"squizlabs/php_codesniffer": "*"
},
"suggest": {
"ext-pcntl": "Interrupt JAXL with signals"
},
"autoload": {
"classmap": [
"core",
"http",
"xep",
"xmpp",
"jaxl.php"
+ ],
+ "exclude-from-classmap": [
+ "/tests/"
]
},
"bin": ["jaxlctl"]
}
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index a2b44df..4ef33a8 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,18 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
- convertNoticesToExceptions="false"
- convertWarningsToExceptions="false"
+ convertNoticesToExceptions="true"
+ convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
>
<testsuites>
<testsuite name="JAXL">
<directory suffix=".php">tests/</directory>
</testsuite>
</testsuites>
</phpunit>
diff --git a/tests/test_jaxl_xml.php b/tests/test_jaxl_xml.php
index 6bcb581..a8e69b1 100644
--- a/tests/test_jaxl_xml.php
+++ b/tests/test_jaxl_xml.php
@@ -1,81 +1,84 @@
<?php
JAXL::dummy();
/**
*
* @author abhinavsingh
*
*/
class JAXLXmlTest extends PHPUnit_Framework_TestCase
{
public static $NS = 'SOME_NAMESPACE';
public static $attrs = array('attr1' => 'value1');
+ /**
+ * @expectedException PHPUnit_Framework_Error_Notice
+ */
public function testJAXLXml_0()
{
$xml = new JAXLXml();
$this->assertEquals('<></>', $xml->to_string());
}
public function testJAXLXml_1()
{
$xml = new JAXLXml('html');
$this->assertEquals('<html></html>', $xml->to_string());
}
public function testJAXLXml_2_1()
{
$xml = new JAXLXml('html', self::$NS);
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE"></html>',
$xml->to_string()
);
}
public function testJAXLXml_2_2()
{
$xml = new JAXLXml('html', self::$attrs);
$this->assertEquals(
'<html attr1="value1"></html>',
$xml->to_string()
);
}
public function testJAXLXml_3_1()
{
$xml = new JAXLXml('html', self::$attrs, 'Some text');
$this->assertEquals(
'<html attr1="value1">Some text</html>',
$xml->to_string()
);
}
public function testJAXLXml_3_2()
{
$xml = new JAXLXml('html', self::$NS, 'Some text');
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE">Some text</html>',
$xml->to_string()
);
}
public function testJAXLXml_3_3()
{
$xml = new JAXLXml('html', self::$NS, self::$attrs);
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE" attr1="value1"></html>',
$xml->to_string()
);
}
public function testJAXLXml_4()
{
$xml = new JAXLXml('html', self::$NS, self::$attrs, 'Some text');
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE" attr1="value1">Some text</html>',
$xml->to_string()
);
}
}
|
jaxl/JAXL | f650509a616c82cddcff270fbfe252ccb1402042 | Facebook chat is deprecated. Refs #41 | diff --git a/docs/users/jaxl_instance.rst b/docs/users/jaxl_instance.rst
index 501db1e..e27883e 100644
--- a/docs/users/jaxl_instance.rst
+++ b/docs/users/jaxl_instance.rst
@@ -1,166 +1,158 @@
.. _jaxl-instance:
JAXL Instance
=============
``JAXL`` instance configure/manage other :ref:`sub-packages <jaxl-instance>`.
It provides an event based callback methodology on various underlying object. Whenever required
``JAXL`` instance will itself perform the configured defaults.
Constructor options
-------------------
#. ``jid``
#. ``pass``
#. ``resource``
If not passed Jaxl will use a random resource value
#. ``auth_type``
- DIGEST-MD5, PLAIN (default), CRAM-MD5, ANONYMOUS, X-FACEBOOK-PLATFORM
+ DIGEST-MD5, PLAIN (default), CRAM-MD5, ANONYMOUS
#. ``host``
#. ``port``
#. ``bosh_url``
#. ``log_path``
#. ``log_level``
``JAXL_ERROR``, ``JAXL_WARNING``, ``JAXL_NOTICE``, ``JAXL_INFO`` (default), ``JAXL_DEBUG``
- #. ``fb_access_token``
-
- required when using X-FACEBOOK-PLATFORM auth mechanism
-
- #. ``fb_app_key``
-
- required when using X-FACEBOOK-PLATFORM auth mechanism
-
#. ``force_tls``
#. ``stream_context``
#. ``priv_dir``
Jaxl creates 4 directories names ``log``, ``tmp``, ``run`` and ``sock`` inside a private directory
which defaults to ``JAXL_CWD.'/.jaxl'``. If this option is passed, it will overwrite default private
directory.
.. note::
Jaxl currently doesn't check upon the permissions of passed ``priv_dir``. Make sure Jaxl library
have sufficient permissions to create above mentioned directories.
Available Event Callbacks
-------------------------
Following ``$ev`` are available on ``JAXL`` lifecycle for registering callbacks:
#. ``on_connect``
``JAXL`` instance has connected successfully
#. ``on_connect_error``
``JAXL`` instance failed to connect
#. ``on_stream_start``
``JAXL`` instance has successfully initiated XMPP stream with the jabber server
#. ``on_stream_features``
``JAXL`` instance has received supported stream features
#. ``on_auth_success``
authentication successful
#. ``on_auth_failure``
authentication failed
#. ``on_presence_stanza``
``JAXL`` instance has received a presence stanza
#. ``on_{$type}_message``
``JAXL`` instance has received a message stanza. ``$type`` can be ``chat``, ``groupchat``, ``headline``, ``normal``, ``error``
#. ``on_stanza_id_{$id}``
Useful when dealing with iq stanza. This event is fired when ``JAXL`` instance has received response to a particular
xmpp stanza id
#. ``on_{$name}_stanza``
Useful when dealing with custom xmpp stanza
#. ``on_disconnect``
``JAXL`` instance has disconnected from the jabber server
Available Methods
-----------------
Following methods are available on initialized ``JAXL`` instance object:
#. ``get_pid_file_path()``
returns path of ``JAXL`` instance pid file
#. ``get_sock_file_path()``
returns path to ``JAXL`` ipc unix socket domain
#. ``require_xep($xeps = array())``
autoload and initialize passed XEP's
#. ``add_cb($ev, $cb, $priority = 1)``
add a callback to function ``$cb`` on event ``$ev``, returns a reference of added callback
#. ``del_cb($ref)``
delete previously registered event callback
#. ``set_status($status, $show, $priority)``
send a presence status stanza
#. ``send_chat_msg($to, $body, $thread = null, $subject = null)``
send a message stanza of type chat
#. ``get_vcard($jid = null, $cb = null)``
fetch vcard for bare ``$jid``, passed ``$cb`` will be called with received vcard stanza
#. ``get_roster($cb = null)``
fetch roster list of connected jabber client, passed ``$cb`` will be called with received roster stanza
#. ``start($opts = array())``
start configured ``JAXL`` instance, optionally accepts two options specified below:
#. ``--with-debug-shell``
start ``JAXL`` instance and enter an interactive console
#. ``--with-unix-sock``
start ``JAXL`` instance with support for IPC and remote debugging
#. ``send($stanza)``
send an instance of JAXLXml packet over connected socket
#. ``send_raw($data)``
send raw payload over connected socket
#. ``get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)``
#. ``get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)``
#. ``get_iq_pkt($attrs, $payload)``
\ No newline at end of file
diff --git a/examples/xfacebook_platform_client.php b/examples/xfacebook_platform_client.php
deleted file mode 100644
index 7e3bc9f..0000000
--- a/examples/xfacebook_platform_client.php
+++ /dev/null
@@ -1,106 +0,0 @@
-<?php
-/**
- * Jaxl (Jabber XMPP Library)
- *
- * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * * Neither the name of Abhinav Singh nor the names of his
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
- * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-if ($argc != 4) {
- echo "Usage: $argv[0] fb_user_id_or_username fb_app_key fb_access_token\n";
- exit;
-}
-
-//
-// initialize JAXL object with initial config
-//
-require_once 'jaxl.php';
-$client = new JAXL(array(
- // (required) credentials
- 'jid' => $argv[1].'@chat.facebook.com',
- 'fb_app_key' => $argv[2],
- 'fb_access_token' => $argv[3],
-
- // force tls (facebook require this now)
- 'force_tls' => true,
- // (required) force facebook oauth
- 'auth_type' => 'X-FACEBOOK-PLATFORM',
-
- // (optional)
- //'resource' => 'resource',
-
- 'log_level' => JAXL_INFO
-));
-
-//
-// add necessary event callbacks here
-//
-
-function on_auth_success_callback()
-{
- global $client;
- _info("got on_auth_success cb, jid ".$client->full_jid->to_string());
- $client->set_status("available!", "dnd", 10);
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
-
-function on_auth_failure_callback($reason)
-{
- global $client;
- $client->send_end_stream();
- _info("got on_auth_failure cb with reason $reason");
-}
-$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
-
-function on_chat_message_callback($stanza)
-{
- global $client;
-
- // echo back incoming message stanza
- $stanza->to = $stanza->from;
- $stanza->from = $client->full_jid->to_string();
- $client->send($stanza);
-}
-$client->add_cb('on_chat_message', 'on_chat_message_callback');
-
-function on_disconnect_callback()
-{
- _info("got on_disconnect cb");
-}
-$client->add_cb('on_disconnect', 'on_disconnect_callback');
-
-//
-// finally start configured xmpp stream
-//
-$client->start();
-echo "done\n";
diff --git a/jaxl.php b/jaxl.php
index 57ab060..7531ef3 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -70,868 +70,803 @@ class JAXL extends XMPPStream
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
-
- protected function send_fb_challenge_response($challenge)
- {
- $this->send($this->get_fb_challenge_response_pkt($challenge));
- }
-
- // refer https://developers.facebook.com/docs/chat/#jabber
- public function get_fb_challenge_response_pkt($challenge)
- {
- $stanza = new JAXLXml('response', NS_SASL);
-
- $challenge = base64_decode($challenge);
- $challenge = urldecode($challenge);
- parse_str($challenge, $challenge_arr);
-
- $response = http_build_query(array(
- 'method' => $challenge_arr['method'],
- 'nonce' => $challenge_arr['nonce'],
- 'access_token' => $this->cfg['fb_access_token'],
- 'api_key' => $this->cfg['fb_app_key'],
- 'call_id' => 0,
- 'v' => '1.0'
- ));
-
- $stanza->t(base64_encode($response));
- return $stanza;
- }
-
- public function wait_for_fb_sasl_response($event, $args)
- {
- switch ($event) {
- case "stanza_cb":
- $stanza = $args[0];
-
- if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
- $challenge = $stanza->text;
- $this->send_fb_challenge_response($challenge);
- return "wait_for_sasl_response";
- } else {
- _debug("got unhandled sasl response, should never happen here");
- exit;
- }
- break;
- default:
- _debug("not catched $event, should never happen here");
- exit;
- break;
- }
- }
-
+
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
- // if pref auth doesn't exists, choose one from available mechanisms
-
- foreach ($mechs as $mech => $any) {
- // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
- if ($mech == 'X-FACEBOOK-PLATFORM') {
- if (isset($this->cfg['fb_access_token'])) {
- break;
- }
- } else {
- // else try first of the available methods
-
- break;
- }
- }
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
-
- if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
- return "wait_for_fb_sasl_response";
- } elseif ($pref_auth == 'CRAM-MD5') {
+
+ if ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
|
jaxl/JAXL | f6e3a3b6ad213917272e85c24b3d4083efa0b413 | Move JAXL_MULTI_CLIENT to "multi_client" config parameter | diff --git a/core/jaxl_event.php b/core/jaxl_event.php
index fa81072..96ba88c 100644
--- a/core/jaxl_event.php
+++ b/core/jaxl_event.php
@@ -1,164 +1,167 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Following kind of events are possible:
* 1) hook i.e. if a callback for such an event is registered, calling function
* is responsible for the workflow from their on
* 2) filter i.e. calling function will manipulate passed arguments
* and modified arguments will be passed to next chain of filter
*
* As a rule of thumb, only 1 hook can be registered for an event, while more
* than 1 filter is allowed for an event hook and filter both cannot be applied
* on an event.
*
* @author abhinavsingh
*
*/
class JAXLEvent
{
protected $common = array();
protected $reg = array();
- public function __construct($common)
+ /**
+ * @param array $common
+ */
+ public function __construct(array $common = array())
{
$this->common = $common;
}
public function __destruct()
{
}
/**
* Add callback on a event.
*
* Callback'd method must return `true` to be persistent, otherwise
* if returned `null` or `false`, callback will be removed automatically.
*
* @param string $ev
* @param callable $cb
* @param int $priority
* @return string Reference to be used while deleting callback.
*/
public function add($ev, $cb, $priority)
{
if (!isset($this->reg[$ev])) {
$this->reg[$ev] = array();
}
$ref = count($this->reg[$ev]);
$this->reg[$ev][] = array($priority, $cb);
return $ev."-".$ref;
}
/**
* Emit event to notify registered callbacks.
*
* TODO: Is a pqueue required here for performance enhancement in case we
* have too many cbs on a specific event?
*
* @param string $ev
* @param array $data
* @return array
*/
public function emit($ev, array $data = array())
{
$data = array_merge($this->common, $data);
$cbs = array();
if (!isset($this->reg[$ev])) {
return $data;
}
foreach ($this->reg[$ev] as $cb) {
if (!isset($cbs[$cb[0]])) {
$cbs[$cb[0]] = array();
}
$cbs[$cb[0]][] = $cb[1];
}
foreach ($cbs as $pri => $cb) {
foreach ($cb as $c) {
$ret = call_user_func_array($c, $data);
// This line is for fixing situation where callback function doesn't return an array type.
// In such cases next call of call_user_func_array will report error since $data is not
// an array type as expected.
// Things will change in future, atleast put the callback inside a try/catch block.
// Here we only check if there was a return, if yes we update $data with return value.
// This is bad design, need more thoughts, should work as of now.
if ($ret) {
$data = $ret;
}
}
}
unset($cbs);
return $data;
}
/**
* Remove previous registered callback.
*
* @param string $ref
*/
public function del($ref)
{
$ref = explode("-", $ref);
unset($this->reg[$ref[0]][$ref[1]]);
}
/**
* @param string $ev
* @return bool
*/
public function exists($ev)
{
$ret = isset($this->reg[$ev]);
//_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists"));
return $ret;
}
/**
* @return array List of registered events.
*/
public function getRegistry()
{
return $this->reg;
}
}
diff --git a/examples/multi_client.php b/examples/multi_client.php
index 4d0bdd3..14b8e9d 100644
--- a/examples/multi_client.php
+++ b/examples/multi_client.php
@@ -1,132 +1,130 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-// enable multi client support
-// this will force 1st parameter of callbacks
-// as connected client instance
-define('JAXL_MULTI_CLIENT', true);
-
// input multiple account credentials
$accounts = array();
$add_new = true;
while ($add_new) {
$jid = readline('Enter Jabber Id: ');
$pass = readline('Enter Password: ');
$accounts[] = array($jid, $pass);
$next = readline('Add another account (y/n): ');
$add_new = $next == 'y' ? true : false;
}
// setup jaxl
require_once 'jaxl.php';
//
// common callbacks
//
function on_auth_success($client)
{
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
}
function on_auth_failure($client, $reason)
{
_info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
}
function on_chat_message($client, $stanza)
{
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
}
function on_presence_stanza($client, $stanza)
{
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
_info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
}
function on_disconnect($client)
{
_info("got on_disconnect cb");
}
//
// bootstrap all account instances
//
foreach ($accounts as $account) {
$client = new JAXL(array(
'jid' => $account[0],
'pass' => $account[1],
- 'log_level' => JAXLLogger::DEBUG
+ 'log_level' => JAXLLogger::DEBUG,
+ // Enable multi client support.
+ // This will force 1st parameter of callbacks as connected client instance.
+ 'multi_client' => true
));
$client->add_cb('on_auth_success', 'on_auth_success');
$client->add_cb('on_auth_failure', 'on_auth_failure');
$client->add_cb('on_chat_message', 'on_chat_message');
$client->add_cb('on_presence_stanza', 'on_presence_stanza');
$client->add_cb('on_disconnect', 'on_disconnect');
$client->connect($client->get_socket_path());
$client->start_stream();
}
// start core loop
JAXLLoop::run();
echo "done\n";
diff --git a/jaxl.php b/jaxl.php
index 413766c..2e0e387 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,747 +1,748 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
-
+
+ $this->cfg['multi_client'] = isset($this->cfg['multi_client']) ? $this->cfg['multi_client'] : false;
// lifecycle events callback
- $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
-
+ $this->ev = new JAXLEvent($this->cfg['multi_client'] ? array(&$this) : array());
+
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLSocketClient|XEP_0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', XMPP::NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
diff --git a/tests/JAXLEventTest.php b/tests/JAXLEventTest.php
index a8a0ac6..f8264db 100644
--- a/tests/JAXLEventTest.php
+++ b/tests/JAXLEventTest.php
@@ -1,74 +1,74 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
JAXL::dummy();
/**
*
* @author abhinavsingh
*
*/
class JAXLEventTest extends PHPUnit_Framework_TestCase
{
public function test_jaxl_event()
{
- $ev = new JAXLEvent(array());
+ $ev = new JAXLEvent();
$ref1 = $ev->add('on_connect', 'some_func', 0);
$ref2 = $ev->add('on_connect', 'some_func1', 0);
$ref3 = $ev->add('on_connect', 'some_func2', 1);
$ref4 = $ev->add('on_connect', 'some_func3', 4);
$ref5 = $ev->add('on_disconnect', 'some_func', 1);
$ref6 = $ev->add('on_disconnect', 'some_func1', 1);
//$ev->emit('on_connect', null);
$registry = $ev->getRegistry();
$this->assertEquals(2, count($registry));
$this->assertEquals(4, count($registry['on_connect']));
$this->assertEquals(2, count($registry['on_disconnect']));
$ev->del($ref2);
$ev->del($ref1);
$ev->del($ref6);
$ev->del($ref5);
$ev->del($ref4);
$ev->del($ref3);
}
}
|
jaxl/JAXL | b47a997eafb7bf46e25eb81cd67a3f7e78309185 | Move NS_* from xmpp_nss.php to XMPP constants | diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php
index d4dc97e..f0df146 100644
--- a/core/jaxl_xml_stream.php
+++ b/core/jaxl_xml_stream.php
@@ -1,199 +1,198 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLXmlStream
{
private $delimiter = '\\';
private $ns;
private $parser;
private $stanza;
private $depth = -1;
private $start_cb;
private $stanza_cb;
private $end_cb;
public function __construct()
{
$this->init_parser();
}
private function init_parser()
{
$this->depth = -1;
$this->parser = xml_parser_create_ns("UTF-8", $this->delimiter);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
xml_set_character_data_handler($this->parser, array(&$this, "handle_character"));
xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag"));
}
public function __destruct()
{
//_debug("cleaning up xml parser...");
@xml_parser_free($this->parser);
}
public function reset_parser()
{
$this->parse_final(null);
@xml_parser_free($this->parser);
$this->parser = null;
$this->init_parser();
}
public function set_callback($start_cb, $end_cb, $stanza_cb)
{
$this->start_cb = $start_cb;
$this->end_cb = $end_cb;
$this->stanza_cb = $stanza_cb;
}
public function parse($str)
{
xml_parse($this->parser, $str, false);
}
public function parse_final($str)
{
xml_parse($this->parser, $str, true);
}
protected function handle_start_tag($parser, $name, array $attrs)
{
$name = $this->explode($name);
//echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL;
// replace ns with prefix
foreach ($attrs as $key => $v) {
$k = $this->explode($key);
// no ns specified
if ($k[0] == null) {
$attrs[$k[1]] = $v;
- } elseif ($k[0] == NS_XML) {
+ } elseif ($k[0] == XMPP::NS_XML) {
// xml ns
-
unset($attrs[$key]);
$attrs['xml:'.$k[1]] = $v;
} else {
_error("==================> unhandled ns prefix on attribute");
// remove attribute else will cause error with bad stanza format
// report to developer if above error message is ever encountered
unset($attrs[$key]);
}
}
if ($this->depth <= 0) {
$this->depth = 0;
$this->ns = $name[1];
if ($this->start_cb) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
call_user_func($this->start_cb, $stanza);
}
} else {
if (!$this->stanza) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
$this->stanza = &$stanza;
} else {
$this->stanza->c($name[1], $name[0], $attrs);
}
}
++$this->depth;
}
protected function handle_end_tag($parser, $name)
{
$name = explode($this->delimiter, $name);
$name = count($name) == 1 ? array('', $name[0]) : $name;
//echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL;
if ($this->depth == 1) {
if ($this->end_cb) {
$stanza = new JAXLXml($name[1], $this->ns);
call_user_func($this->end_cb, $stanza);
}
} elseif ($this->depth > 1) {
if ($this->stanza) {
$this->stanza->up();
}
if ($this->depth == 2) {
if ($this->stanza_cb) {
call_user_func($this->stanza_cb, $this->stanza);
$this->stanza = null;
}
}
}
--$this->depth;
}
protected function handle_character($parser, $data)
{
//echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL;
if ($this->stanza) {
$this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), true);
}
}
private function implode($data)
{
return implode($this->delimiter, $data);
}
private function explode($data)
{
$data = explode($this->delimiter, $data);
$data = count($data) == 1 ? array(null, $data[0]) : $data;
return $data;
}
}
diff --git a/jaxl.php b/jaxl.php
index 04c171c..413766c 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -83,863 +83,863 @@ class JAXL extends XMPPStream
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLSocketClient|XEP_0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
-
+
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
- $stanza = new JAXLXml('response', NS_SASL);
+ $stanza = new JAXLXml('response', XMPP::NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
-
+
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
-
+
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
- if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
+ if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
- if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
+ if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = base64_decode($stanza->text);
- $resp = new JAXLXml('response', NS_SASL);
+ $resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
- if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
+ if ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
- $resp = new JAXLXml('response', NS_SASL);
+ $resp = new JAXLXml('response', XMPP::NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
if (isset($this->cfg['fb_access_token'])) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', XEP_0030::NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', XEP_0030::NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
diff --git a/tests/JAXLXmlStreamTest.php b/tests/JAXLXmlStreamTest.php
index 1252843..80209a1 100644
--- a/tests/JAXLXmlStreamTest.php
+++ b/tests/JAXLXmlStreamTest.php
@@ -1,77 +1,77 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
JAXL::dummy();
/**
*
* @author abhinavsingh
*
*/
class JAXLXmlStreamTest extends PHPUnit_Framework_TestCase
{
public function xml_start_cb($node)
{
$this->assertEquals('stream', $node->name);
- $this->assertEquals(NS_XMPP, $node->ns);
+ $this->assertEquals(XMPP::NS_XMPP, $node->ns);
}
public function xml_end_cb($node)
{
$this->assertEquals('stream', $node->name);
}
public function xml_stanza_cb($node)
{
$this->assertEquals('features', $node->name);
$this->assertEquals(1, count($node->childrens));
}
public function test_xml_stream_callbacks()
{
$xml = new JAXLXmlStream();
$xml->set_callback(array(&$this, "xml_start_cb"), array(&$this, "xml_end_cb"), array(&$this, "xml_stanza_cb"));
$xml->parse('<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">');
$xml->parse('<features>');
$xml->parse('<mechanisms>');
$xml->parse('</mechanisms>');
$xml->parse('</features>');
$xml->parse('</stream:stream>');
}
}
diff --git a/tests/XMPPStanzaTest.php b/tests/XMPPStanzaTest.php
index 138f4f5..0244b5c 100644
--- a/tests/XMPPStanzaTest.php
+++ b/tests/XMPPStanzaTest.php
@@ -1,83 +1,83 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
JAXL::dummy();
/**
*
* @author abhinavsingh
*
*/
class XMPPStanzaTest extends PHPUnit_Framework_TestCase
{
public function test_xmpp_stanza_nested()
{
$xml = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]'));
$xml->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up()
->c('thread')->t('1234')->up()
->c('nested')
->c('nest')->t('nest1')->up()
->c('nest')->t('nest2')->up()
->c('nest')->t('nest3')->up()->up()
->c('c')->attrs(array('hash' => '84jsdmnskd'));
$stanza = new XMPPStanza($xml);
$this->assertEquals(
'<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested>' .
'<nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>',
$stanza->to_string()
);
}
public function test_xmpp_stanza_from_jaxl_xml()
{
// xml to stanza test
- $xml = new JAXLXml('message', NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q'));
+ $xml = new JAXLXml('message', XMPP::NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q'));
$stanza = new XMPPStanza($xml);
$stanza->c('body')->t('hello world');
$this->assertEquals('XMPPStanza', get_class($stanza));
$this->assertEquals('JAXLXml', get_class($stanza->exists('body')));
$this->assertEquals('[email protected]', $stanza->to);
$this->assertEquals(
'<message xmlns="jabber:client" to="[email protected]" from="[email protected]/q">' .
'<body>hello world</body></message>',
$stanza->to_string()
);
}
}
diff --git a/xep/xep_0114.php b/xep/xep_0114.php
index 531f722..5f12eed 100644
--- a/xep/xep_0114.php
+++ b/xep/xep_0114.php
@@ -1,101 +1,101 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
class XEP_0114 extends XMPPXep
{
const NS_JABBER_COMPONENT_ACCEPT = 'jabber:component:accept';
//
// abstract method
//
public function init()
{
return array(
'on_connect' => 'start_stream',
'on_stream_start' => 'start_handshake',
'on_handshake_stanza' => 'logged_in',
'on_error_stanza' => 'logged_out'
);
}
//
// event callbacks
//
public function start_stream()
{
$xml = sprintf(
'<stream:stream xmlns:stream="%s" to="%s" xmlns="%s">',
- NS_XMPP,
+ XMPP::NS_XMPP,
$this->jaxl->jid->to_string(),
self::NS_JABBER_COMPONENT_ACCEPT
);
$this->jaxl->send_raw($xml);
}
public function start_handshake($stanza)
{
_debug("starting component handshake");
$id = $stanza->id;
$hash = strtolower(sha1($id.$this->jaxl->pass));
$stanza = new JAXLXml('handshake', null, $hash);
$this->jaxl->send($stanza);
}
public function logged_in($stanza)
{
_debug("component handshake complete");
$this->jaxl->handle_auth_success();
return array("logged_in", 1);
}
public function logged_out($stanza)
{
- if ($stanza->name == "error" && $stanza->ns == NS_XMPP) {
+ if ($stanza->name == "error" && $stanza->ns == XMPP::NS_XMPP) {
$reason = $stanza->childrens[0]->name;
$this->jaxl->handle_auth_failure($reason);
$this->jaxl->send_end_stream();
return array("logged_out", 0);
} else {
_debug("uncatched stanza received in logged_out");
}
}
}
diff --git a/xmpp/xmpp_nss.php b/xmpp/xmpp.php
similarity index 62%
rename from xmpp/xmpp_nss.php
rename to xmpp/xmpp.php
index 233db6c..cf56824 100644
--- a/xmpp/xmpp_nss.php
+++ b/xmpp/xmpp.php
@@ -1,60 +1,64 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-// XML
-define('NS_XML_PFX', "xml");
-define('NS_XML', 'http://www.w3.org/XML/1998/namespace');
+class XMPP
+{
-// XMPP Core (RFC 3920)
-define('NS_XMPP_PFX', "stream");
-define('NS_XMPP', 'http://etherx.jabber.org/streams');
-define('NS_STREAM_ERRORS', 'urn:ietf:params:xml:ns:xmpp-streams');
-define('NS_TLS', 'urn:ietf:params:xml:ns:xmpp-tls');
-define('NS_SASL', 'urn:ietf:params:xml:ns:xmpp-sasl');
-define('NS_BIND', 'urn:ietf:params:xml:ns:xmpp-bind');
-define('NS_STANZA_ERRORS', 'urn:ietf:params:xml:ns:xmpp-stanzas');
+ // XML
+ const NS_XML_PFX = 'xml';
+ const NS_XML = 'http://www.w3.org/XML/1998/namespace';
-// XMPP-IM (RFC 3921)
-define('NS_JABBER_CLIENT', 'jabber:client');
-define('NS_JABBER_SERVER', 'jabber:server');
-define('NS_SESSION', 'urn:ietf:params:xml:ns:xmpp-session');
-define('NS_ROSTER', 'jabber:iq:roster');
+ // XMPP Core (RFC 3920)
+ const NS_XMPP_PFX = 'stream';
+ const NS_XMPP = 'http://etherx.jabber.org/streams';
+ const NS_STREAM_ERRORS = 'urn:ietf:params:xml:ns:xmpp-streams';
+ const NS_TLS = 'urn:ietf:params:xml:ns:xmpp-tls';
+ const NS_SASL = 'urn:ietf:params:xml:ns:xmpp-sasl';
+ const NS_BIND = 'urn:ietf:params:xml:ns:xmpp-bind';
+ const NS_STANZA_ERRORS = 'urn:ietf:params:xml:ns:xmpp-stanzas';
-// Stream Compression (XEP-0138)
-define('NS_COMPRESSION_FEATURE', 'http://jabber.org/features/compress');
-define('NS_COMPRESSION_PROTOCOL', 'http://jabber.org/protocol/compress');
+ // XMPP-IM (RFC 3921)
+ const NS_JABBER_CLIENT = 'jabber:client';
+ const NS_JABBER_SERVER = 'jabber:server';
+ const NS_SESSION = 'urn:ietf:params:xml:ns:xmpp-session';
+ const NS_ROSTER = 'jabber:iq:roster';
+
+ // Stream Compression (XEP-0138)
+ const NS_COMPRESSION_FEATURE = 'http://jabber.org/features/compress';
+ const NS_COMPRESSION_PROTOCOL = 'http://jabber.org/protocol/compress';
+}
diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php
index b07e831..1df8c0b 100644
--- a/xmpp/xmpp_stanza.php
+++ b/xmpp/xmpp_stanza.php
@@ -1,198 +1,198 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
+require_once JAXL_CWD.'/xmpp/xmpp.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
/**
* Generic xmpp stanza object which provide convinient access pattern over xml objects
* Also to be able to convert an existing xml object into stanza object (to get access patterns going)
* this class doesn't extend xml, but infact works on a reference of xml object
* If not provided during constructor, new xml object is created and saved as reference
*
* @author abhinavsingh
*
*/
class XMPPStanza
{
/**
* @var JAXLXml
*/
private $xml;
/**
* @param JAXLXml|string $name
* @param array $attrs
* @param string $ns
*/
- public function __construct($name, array $attrs = array(), $ns = NS_JABBER_CLIENT)
+ public function __construct($name, array $attrs = array(), $ns = XMPP::NS_JABBER_CLIENT)
{
if ($name instanceof JAXLXml) {
$this->xml = $name;
} else {
$this->xml = new JAXLXml($name, $ns, $attrs);
}
}
public function __call($method, $args)
{
return call_user_func_array(array($this->xml, $method), $args);
}
public function __get($prop)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
return isset($this->xml->attrs[$prop]) ? $this->xml->attrs[$prop] : null;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val) {
return null;
}
$val = new XMPPJid($val);
return $val->$key;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val = $this->xml->exists($prop);
if (!$val) {
return null;
}
return $val->text;
break;
default:
return null;
break;
}
}
public function __set($prop, $val)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop = $val;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
$this->xml->attrs[$prop] = $val;
return true;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val1 = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val1) {
$val1 = '';
}
$val1 = new XMPPJid($val1);
$val1->$key = $val;
$this->xml->attrs[$attr] = $val1->to_string();
return true;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val1 = $this->xml->exists($prop);
if (!$val1) {
$this->xml->c($prop)->t($val)->up();
} else {
$this->xml->update($prop, $val1->ns, $val1->attrs, $val);
}
return true;
break;
default:
return null;
break;
}
}
}
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php
index 99794b5..8898bce 100644
--- a/xmpp/xmpp_stream.php
+++ b/xmpp/xmpp_stream.php
@@ -1,769 +1,769 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
require_once JAXL_CWD.'/core/jaxl_xml_stream.php';
require_once JAXL_CWD.'/core/jaxl_util.php';
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
-require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
+require_once JAXL_CWD.'/xmpp/xmpp.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/xmpp/xmpp_msg.php';
require_once JAXL_CWD.'/xmpp/xmpp_pres.php';
require_once JAXL_CWD.'/xmpp/xmpp_iq.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
* @var JAXLSocketClient|XEP_0206
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
* @param JAXLSocketClient|XEP_0206 $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
$jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//_debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
_error("got invalid return value from state handler '".$this->state."', sending end stream...");
$this->send_end_stream();
$this->state = "logged_out";
_notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers");
}
/**
* @param JAXLXml|XMPPStanza $stanza
*/
public function send($stanza)
{
$this->trans->send($stanza->to_string());
}
/**
* @param string $data
*/
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
- $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" ';
+ $xml = '<stream:stream xmlns:stream="'.XMPP::NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
- $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">';
+ $xml .= 'xmlns="'.XMPP::NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.XMPP::NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
- $stanza = new JAXLXml('starttls', NS_TLS);
+ $stanza = new JAXLXml('starttls', XMPP::NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
- $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL);
+ $stanza = new JAXLXml('compress', XMPP::NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
- $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism));
+ $stanza = new JAXLXml('auth', XMPP::NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
- $stanza = new JAXLXml('response', NS_SASL);
+ $stanza = new JAXLXml('response', XMPP::NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
_debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
- $stanza = new JAXLXml('bind', NS_BIND);
+ $stanza = new JAXLXml('bind', XMPP::NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
- $stanza = new JAXLXml('session', NS_SESSION);
+ $stanza = new JAXLXml('session', XMPP::NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//_debug("stream started");
return "wait_for_stream_features";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
- $starttls = $stanza->exists('starttls', NS_TLS);
+ $starttls = $stanza->exists('starttls', XMPP::NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
- $mechs = $stanza->exists('mechanisms', NS_SASL);
+ $mechs = $stanza->exists('mechanisms', XMPP::NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
- $bind = $stanza->exists('bind', NS_BIND) ? true : false;
- $sess = $stanza->exists('session', NS_SESSION) ? true : false;
- $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false;
+ $bind = $stanza->exists('bind', XMPP::NS_BIND) ? true : false;
+ $sess = $stanza->exists('session', XMPP::NS_SESSION) ? true : false;
+ $comp = $stanza->exists('compression', XMPP::NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
_debug("no catch");
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
- if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) {
+ if ($stanza->name == 'proceed' && $stanza->ns == XMPP::NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
- if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) {
+ if ($stanza->name == 'compressed' && $stanza->ns == XMPP::NS_COMPRESSION_PROTOCOL) {
$this->xml->reset_parser();
$this->trans->compress();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_compression_result", 0);
break;
}
}
public function wait_for_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
- if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) {
+ if ($stanza->name == 'failure' && $stanza->ns == XMPP::NS_SASL) {
$reason = $stanza->childrens[0]->name;
//_debug("sasl failed with reason ".$reason."");
$this->handle_auth_failure($reason);
return "logged_out";
- } elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
+ } elseif ($stanza->name == 'challenge' && $stanza->ns == XMPP::NS_SASL) {
$challenge = $stanza->text;
$this->send_challenge_response($challenge);
return "wait_for_sasl_response";
- } elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) {
+ } elseif ($stanza->name == 'success' && $stanza->ns == XMPP::NS_SASL) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
_debug("got unhandled sasl response");
}
return "wait_for_sasl_response";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_sasl_response", 0);
break;
}
}
public function wait_for_bind_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// TODO: chk on id
if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result'
- && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) {
+ && ($jid = $stanza->exists('bind', XMPP::NS_BIND)->exists('jid'))) {
$this->full_jid = new XMPPJid($jid->text);
$this->send_session_pkt();
return "wait_for_session_response";
} else {
// FIXME:
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_bind_response", 0);
break;
}
}
public function wait_for_session_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$this->handle_auth_success();
return "logged_in";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_session_response", 0);
break;
}
}
public function logged_in($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// call abstract
if ($stanza->name == 'message') {
$this->handle_message($stanza);
} elseif ($stanza->name == 'presence') {
$this->handle_presence($stanza);
} elseif ($stanza->name == 'iq') {
$this->handle_iq($stanza);
} else {
$this->handle_other($event, $args);
}
return "logged_in";
break;
case "end_cb":
$this->send_end_stream();
return "logged_out";
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_in", 0);
break;
}
}
public function logged_out($event, $args)
{
switch ($event) {
case "end_cb":
$this->trans->disconnect();
return "disconnected";
break;
case "end_stream":
return "disconnected";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
case "connect":
return $this->do_connect($args);
break;
default:
// exit for any other event in logged_out state
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_out", 0);
break;
}
}
}
|
jaxl/JAXL | 66940066fbe4da82481e684717ddcc801927e164 | Move NS_* to XEPs constants | diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php
index a1bc945..1c46787 100644
--- a/examples/http_pre_bind.php
+++ b/examples/http_pre_bind.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// http pre bind php script
$body = file_get_contents("php://input");
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (!isset($attrs['to']) &&
!isset($attrs['rid']) &&
!isset($attrs['wait']) &&
!isset($attrs['hold'])
) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
require_once '../jaxl.php';
$to = (string)$attrs['to'];
$rid = (int)$attrs['rid'];
$wait = (int)$attrs['wait'];
$hold = (int)$attrs['hold'];
list($host, $port) = JAXLUtil::get_dns_srv($to);
$client = new JAXL(array(
'domain' => $to,
'host' => $host,
'port' => $port,
'bosh_url' => 'http://localhost:5280/http-bind',
'bosh_rid' => $rid,
'bosh_wait' => $wait,
'bosh_hold' => $hold,
'auth_type' => 'ANONYMOUS',
'log_level' => JAXLLogger::INFO
));
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
echo sprintf(
'<body xmlns="%s" sid="%s" rid="%s" jid="%s"/>',
- NS_HTTP_BIND,
+ XEP_0206::NS_HTTP_BIND,
$client->xeps['0206']->sid,
$client->xeps['0206']->rid,
$client->full_jid->to_string()
);
exit;
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
_info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php
index 00a33fd..f007233 100644
--- a/examples/muc_log_bot.php
+++ b/examples/muc_log_bot.php
@@ -1,146 +1,146 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 5) {
echo "Usage: $argv[0] host jid pass [email protected] nickname\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[2],
'pass' => $argv[3],
'host' => $argv[1],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0045', // MUC
'0203', // Delayed Delivery
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$_room_full_jid = $argv[4]."/".$argv[5];
$room_full_jid = new XMPPJid($_room_full_jid);
$client->add_cb('on_auth_success', function () {
global $client, $room_full_jid;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// join muc room
$client->xeps['0045']->join_room($room_full_jid);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_groupchat_message', function ($stanza) {
global $client;
$from = new XMPPJid($stanza->from);
- $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY);
+ $delay = $stanza->exists('delay', XEP_0203::NS_DELAYED_DELIVERY);
if ($from->resource) {
echo sprintf(
"message stanza rcvd from %s saying... %s, %s".PHP_EOL,
$from->resource,
$stanza->body,
$delay ? "delay timestamp ".$delay->attrs['stamp'] : "timestamp ".gmdate("Y-m-dTH:i:sZ")
);
} else {
$subject = $stanza->exists('subject');
if ($subject) {
echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".
$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL;
}
}
});
$client->add_cb('on_presence_stanza', function ($stanza) {
global $client, $room_full_jid;
$from = new XMPPJid($stanza->from);
// self-stanza received, we now have complete room roster
if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) {
- if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) {
+ if (($x = $stanza->exists('x', XEP_0045::NS_MUC.'#user')) !== false) {
if (($status = $x->exists('status', null, array('code' => '110'))) !== false) {
$item = $x->exists('item');
_info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].
", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']);
} else {
_info("xmlns #user have no x child element");
}
} else {
_warning("=======> odd case 1");
}
} elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) {
// stanza from other users received
- if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) {
+ if (($x = $stanza->exists('x', XEP_0045::NS_MUC.'#user')) !== false) {
$item = $x->exists('item');
echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".
$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL;
} else {
_warning("=======> odd case 2");
}
} else {
_warning("=======> odd case 3");
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/register_user.php b/examples/register_user.php
index 1e17b45..c31ef1f 100644
--- a/examples/register_user.php
+++ b/examples/register_user.php
@@ -1,167 +1,167 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 2) {
echo "Usage: $argv[0] domain\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'log_level' => JAXLLogger::DEBUG
));
$client->require_xep(array(
'0077' // InBand Registration
));
//
// below are two states which become part of
// our client's xmpp_stream lifecycle
// consider as if these methods are directly
// inside xmpp_stream state machine
//
// Note: $stanza = $args[0] is an instance of
// JAXLXml in xmpp_stream state methods,
// it is yet not ready for easy access
// patterns available on XMPPStanza instances
//
$form = array();
function wait_for_register_response($event, $args)
{
global $client, $form;
if ($event == 'stanza_cb') {
$stanza = $args[0];
if ($stanza->name == 'iq') {
$form['type'] = $stanza->attrs['type'];
if ($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
} elseif ($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo sprintf(
"registration failed with error code: %s and type: %s".PHP_EOL,
$error->attrs['code'],
$error->attrs['type']
);
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
}
}
} else {
_notice("unhandled event $event rcvd");
}
}
function wait_for_register_form($event, $args)
{
global $client, $form;
$stanza = $args[0];
- $query = $stanza->exists('query', NS_INBAND_REGISTER);
+ $query = $stanza->exists('query', XEP_0077::NS_INBAND_REGISTER);
if ($query) {
$instructions = $query->exists('instructions');
if ($instructions) {
echo $instructions->text.PHP_EOL;
}
foreach ($query->childrens as $k => $child) {
if ($child->name != 'instructions') {
$form[$child->name] = readline($child->name.":");
}
}
$client->xeps['0077']->set_form($stanza->attrs['from'], $form);
return "wait_for_register_response";
} else {
$client->end_stream();
return "logged_out";
}
}
//
// add necessary event callbacks here
//
$client->add_cb('on_stream_features', function ($stanza) {
global $client, $argv;
$client->xeps['0077']->get_form($argv[1]);
return "wait_for_register_form";
});
$client->add_cb('on_disconnect', function () {
global $form;
_info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
});
//
// finally start configured xmpp stream
//
$client->start();
//
// if registration was successful
// try to connect with newly registered account
//
if ($form['type'] == 'result') {
_info("connecting newly registered user account");
$client = new JAXL(array(
'jid' => $form['username'].'@'.$argv[1],
'pass' => $form['password'],
'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
$client->set_status('Available');
});
$client->start();
}
echo "done\n";
diff --git a/examples/subscriber.php b/examples/subscriber.php
index f5b54d7..252792a 100644
--- a/examples/subscriber.php
+++ b/examples/subscriber.php
@@ -1,96 +1,96 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// subscribe
$client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node');
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_headline_message', function ($stanza) {
global $client;
- if (($event = $stanza->exists('event', NS_PUBSUB.'#event'))) {
+ if (($event = $stanza->exists('event', XEP_0060::NS_PUBSUB.'#event'))) {
_info("got pubsub event");
} else {
_warning("unknown headline message rcvd");
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/jaxl.php b/jaxl.php
index 62fbbb0..04c171c 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -395,551 +395,551 @@ class JAXL extends XMPPStream
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
if (isset($this->cfg['fb_access_token'])) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
-
+
public function handle_domain_info($stanza)
{
- $query = $stanza->exists('query', NS_DISCO_INFO);
+ $query = $stanza->exists('query', XEP_0030::NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
-
+
public function handle_domain_items($stanza)
{
- $query = $stanza->exists('query', NS_DISCO_ITEMS);
+ $query = $stanza->exists('query', XEP_0030::NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
diff --git a/xep/xep_0030.php b/xep/xep_0030.php
index 6e45d3f..3fb3d4b 100644
--- a/xep/xep_0030.php
+++ b/xep/xep_0030.php
@@ -1,99 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_DISCO_INFO', 'http://jabber.org/protocol/disco#info');
-define('NS_DISCO_ITEMS', 'http://jabber.org/protocol/disco#items');
-
class XEP_0030 extends XMPPXep
{
+ const NS_DISCO_INFO = 'http://jabber.org/protocol/disco#info';
+ const NS_DISCO_ITEMS = 'http://jabber.org/protocol/disco#items';
//
// abstract method
//
public function init()
{
return array(
);
}
//
// api methods
//
public function get_info_pkt($entity_jid)
{
return $this->jaxl->get_iq_pkt(
array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid),
- new JAXLXml('query', NS_DISCO_INFO)
+ new JAXLXml('query', self::NS_DISCO_INFO)
);
}
public function get_info($entity_jid, $callback = null)
{
$pkt = $this->get_info_pkt($entity_jid);
if ($callback) {
$this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback);
}
$this->jaxl->send($pkt);
}
public function get_items_pkt($entity_jid)
{
return $this->jaxl->get_iq_pkt(
array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid),
- new JAXLXml('query', NS_DISCO_ITEMS)
+ new JAXLXml('query', self::NS_DISCO_ITEMS)
);
}
public function get_items($entity_jid, $callback = null)
{
$pkt = $this->get_items_pkt($entity_jid);
if ($callback) {
$this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback);
}
$this->jaxl->send($pkt);
}
//
// event callbacks
//
}
diff --git a/xep/xep_0045.php b/xep/xep_0045.php
index 08b8115..f8e871e 100644
--- a/xep/xep_0045.php
+++ b/xep/xep_0045.php
@@ -1,124 +1,123 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_MUC', 'http://jabber.org/protocol/muc');
-
class XEP_0045 extends XMPPXep
{
+ const NS_MUC = 'http://jabber.org/protocol/muc';
//
// abstract method
//
public function init()
{
return array();
}
public function send_groupchat($room_jid, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'groupchat',
'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid),
'from'=>$this->jaxl->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->jaxl->send($msg);
}
//
// api methods (occupant use case)
//
// room_full_jid simply means room jid with nick name as resource
public function get_join_room_pkt($room_full_jid, array $options)
{
$pkt = $this->jaxl->get_pres_pkt(
array(
'from'=>$this->jaxl->full_jid->to_string(),
'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid),
'id' => (isset($options['id'])) ? $options['id'] : uniqid()
)
);
- $x = $pkt->c('x', NS_MUC);
+ $x = $pkt->c('x', self::NS_MUC);
if (isset($options['no_history'])) {
$x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0))->up();
}
if (isset($options['password'])) {
$x->c('password')->t($options['password'])->up();
}
return $x;
}
public function join_room($room_full_jid, array $options = array())
{
$pkt = $this->get_join_room_pkt($room_full_jid, $options);
$this->jaxl->send($pkt);
}
public function get_leave_room_pkt($room_full_jid)
{
return $this->jaxl->get_pres_pkt(array(
'type' => 'unavailable',
'from' => $this->jaxl->full_jid->to_string(),
'to' => ($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid
));
}
public function leave_room($room_full_jid)
{
$pkt = $this->get_leave_room_pkt($room_full_jid);
$this->jaxl->send($pkt);
}
//
// api methods (moderator use case)
//
//
// event callbacks
//
}
diff --git a/xep/xep_0060.php b/xep/xep_0060.php
index 331be35..de054df 100644
--- a/xep/xep_0060.php
+++ b/xep/xep_0060.php
@@ -1,149 +1,148 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_PUBSUB', 'http://jabber.org/protocol/pubsub');
-
class XEP_0060 extends XMPPXep
{
+ const NS_PUBSUB = 'http://jabber.org/protocol/pubsub';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods (entity use case)
//
//
// api methods (subscriber use case)
//
public function get_subscribe_pkt($service, $node, $jid = null)
{
- $child = new JAXLXml('pubsub', NS_PUBSUB);
+ $child = new JAXLXml('pubsub', self::NS_PUBSUB);
$child->c(
'subscribe',
null,
array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string()))
);
return $this->get_iq_pkt($service, $child);
}
public function subscribe($service, $node, $jid = null)
{
$this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid));
}
public function unsubscribe()
{
}
public function get_subscription_options()
{
}
public function set_subscription_options()
{
}
public function get_node_items()
{
}
//
// api methods (publisher use case)
//
public function get_publish_item_pkt($service, $node, $item)
{
- $child = new JAXLXml('pubsub', NS_PUBSUB);
+ $child = new JAXLXml('pubsub', self::NS_PUBSUB);
$child->c('publish', null, array('node' => $node));
$child->cnode($item);
return $this->get_iq_pkt($service, $child);
}
public function publish_item($service, $node, $item)
{
$this->jaxl->send($this->get_publish_item_pkt($service, $node, $item));
}
public function delete_item()
{
}
//
// api methods (owner use case)
//
public function get_create_node_pkt($service, $node)
{
- $child = new JAXLXml('pubsub', NS_PUBSUB);
+ $child = new JAXLXml('pubsub', self::NS_PUBSUB);
$child->c('create', null, array('node' => $node));
return $this->get_iq_pkt($service, $child);
}
public function create_node($service, $node)
{
$this->jaxl->send($this->get_create_node_pkt($service, $node));
}
//
// event callbacks
//
//
// local methods
//
// this always add attrs
protected function get_iq_pkt($service, $child, $type = 'set')
{
return $this->jaxl->get_iq_pkt(
array('type' => $type, 'from' => $this->jaxl->full_jid->to_string(), 'to' => $service),
$child
);
}
}
diff --git a/xep/xep_0077.php b/xep/xep_0077.php
index 66b5f24..fff16f3 100644
--- a/xep/xep_0077.php
+++ b/xep/xep_0077.php
@@ -1,87 +1,86 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_FEATURE_REGISTER', 'http://jabber.org/features/iq-register');
-define('NS_INBAND_REGISTER', 'jabber:iq:register');
-
class XEP_0077 extends XMPPXep
{
+ const NS_FEATURE_REGISTER = 'http://jabber.org/features/iq-register';
+ const NS_INBAND_REGISTER = 'jabber:iq:register';
//
// abstract method
//
public function init()
{
return array(
);
}
//
// api methods
//
public function get_form_pkt($domain)
{
return $this->jaxl->get_iq_pkt(
array('to' => $domain, 'type' => 'get'),
- new JAXLXml('query', NS_INBAND_REGISTER)
+ new JAXLXml('query', self::NS_INBAND_REGISTER)
);
}
public function get_form($domain)
{
$this->jaxl->send($this->get_form_pkt($domain));
}
public function set_form($domain, array $form)
{
- $query = new JAXLXml('query', NS_INBAND_REGISTER);
+ $query = new JAXLXml('query', self::NS_INBAND_REGISTER);
foreach ($form as $k => $v) {
$query->c($k, null, array(), $v)->up();
}
$pkt = $this->jaxl->get_iq_pkt(
array('to' => $domain, 'type' => 'set'),
$query
);
$this->jaxl->send($pkt);
}
}
diff --git a/xep/xep_0114.php b/xep/xep_0114.php
index 6e9896a..531f722 100644
--- a/xep/xep_0114.php
+++ b/xep/xep_0114.php
@@ -1,102 +1,101 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_JABBER_COMPONENT_ACCEPT', 'jabber:component:accept');
-
class XEP_0114 extends XMPPXep
{
+ const NS_JABBER_COMPONENT_ACCEPT = 'jabber:component:accept';
//
// abstract method
//
public function init()
{
return array(
'on_connect' => 'start_stream',
'on_stream_start' => 'start_handshake',
'on_handshake_stanza' => 'logged_in',
'on_error_stanza' => 'logged_out'
);
}
//
// event callbacks
//
public function start_stream()
{
$xml = sprintf(
'<stream:stream xmlns:stream="%s" to="%s" xmlns="%s">',
NS_XMPP,
$this->jaxl->jid->to_string(),
- NS_JABBER_COMPONENT_ACCEPT
+ self::NS_JABBER_COMPONENT_ACCEPT
);
$this->jaxl->send_raw($xml);
}
public function start_handshake($stanza)
{
_debug("starting component handshake");
$id = $stanza->id;
$hash = strtolower(sha1($id.$this->jaxl->pass));
$stanza = new JAXLXml('handshake', null, $hash);
$this->jaxl->send($stanza);
}
public function logged_in($stanza)
{
_debug("component handshake complete");
$this->jaxl->handle_auth_success();
return array("logged_in", 1);
}
public function logged_out($stanza)
{
if ($stanza->name == "error" && $stanza->ns == NS_XMPP) {
$reason = $stanza->childrens[0]->name;
$this->jaxl->handle_auth_failure($reason);
$this->jaxl->send_end_stream();
return array("logged_out", 0);
} else {
_debug("uncatched stanza received in logged_out");
}
}
}
diff --git a/xep/xep_0115.php b/xep/xep_0115.php
index d90fdca..8d4d630 100644
--- a/xep/xep_0115.php
+++ b/xep/xep_0115.php
@@ -1,75 +1,74 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_CAPS', 'http://jabber.org/protocol/caps');
-
class XEP_0115 extends XMPPXep
{
+ const NS_CAPS = 'http://jabber.org/protocol/caps';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods
//
public function get_caps_pkt($cat, $type, $lang, $name, $node, $features)
{
asort($features);
$S = $cat.'/'.$type.'/'.$lang.'/'.$name.'<';
foreach ($features as $feature) {
$S .= $feature.'<';
}
$ver = base64_encode(sha1($S, true));
- $stanza = new JAXLXml('c', NS_CAPS, array('hash' => 'sha1', 'node' => $node, 'ver' => $ver));
+ $stanza = new JAXLXml('c', self::NS_CAPS, array('hash' => 'sha1', 'node' => $node, 'ver' => $ver));
return $stanza;
}
//
// event callbacks
//
}
diff --git a/xep/xep_0199.php b/xep/xep_0199.php
index 0ed6e19..49678ea 100644
--- a/xep/xep_0199.php
+++ b/xep/xep_0199.php
@@ -1,63 +1,62 @@
<?php
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_XMPP_PING', 'urn:xmpp:ping');
-
class XEP_0199 extends XMPPXep
{
+ const NS_XMPP_PING = 'urn:xmpp:ping';
//
// abstract method
//
public function init()
{
return array(
'on_auth_success' => 'on_auth_success',
'on_get_iq' => 'on_xmpp_ping'
);
}
//
// api methods
//
public function get_ping_pkt()
{
$attrs = array(
'type' => 'get',
'from' => $this->jaxl->full_jid->to_string(),
'to' => $this->jaxl->full_jid->domain
);
return $this->jaxl->get_iq_pkt(
$attrs,
- new JAXLXml('ping', NS_XMPP_PING)
+ new JAXLXml('ping', self::NS_XMPP_PING)
);
}
public function ping()
{
$this->jaxl->send($this->get_ping_pkt());
}
//
// event callbacks
//
public function on_auth_success()
{
JAXLLoop::$clock->call_fun_periodic(30 * pow(10, 6), array(&$this, 'ping'));
}
public function on_xmpp_ping($stanza)
{
- if ($stanza->exists('ping', NS_XMPP_PING)) {
+ if ($stanza->exists('ping', self::NS_XMPP_PING)) {
$stanza->type = "result";
$stanza->to = $stanza->from;
$stanza->from = $this->jaxl->full_jid->to_string();
$this->jaxl->send($stanza);
}
}
}
diff --git a/xep/xep_0203.php b/xep/xep_0203.php
index 7fc2847..ce31826 100644
--- a/xep/xep_0203.php
+++ b/xep/xep_0203.php
@@ -1,62 +1,61 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_DELAYED_DELIVERY', 'urn:xmpp:delay');
-
class XEP_0203 extends XMPPXep
{
+ const NS_DELAYED_DELIVERY = 'urn:xmpp:delay';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods
//
//
// event callbacks
//
}
diff --git a/xep/xep_0206.php b/xep/xep_0206.php
index 7fa3f09..d8ded76 100644
--- a/xep/xep_0206.php
+++ b/xep/xep_0206.php
@@ -1,270 +1,270 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind');
-define('NS_BOSH', 'urn:xmpp:xbosh');
-
class XEP_0206 extends XMPPXep
{
-
+ const NS_HTTP_BIND = 'http://jabber.org/protocol/httpbind';
+ const NS_BOSH = 'urn:xmpp:xbosh';
+
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
//
// event callbacks
//
/**
* @param JAXLXml|XMPPStanza|string $body
*/
public function send($body)
{
if (is_object($body)) {
$body = $body->to_string();
} else {
if (substr($body, 0, 15) == '<stream:stream ') {
$this->restarted = true;
- $body = new JAXLXml('body', NS_HTTP_BIND, array(
+ $body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
- 'xmlns:xmpp' => NS_BOSH
+ 'xmlns:xmpp' => self::NS_BOSH
));
$body = $body->to_string();
} elseif (substr($body, 0, 16) == '</stream:stream>') {
- $body = new JAXLXml('body', NS_HTTP_BIND, array(
+ $body = new JAXLXml('body', self::NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
$body = $body->to_string();
} else {
$body = $this->wrap($body);
}
}
_debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
_debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
_debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
_debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
_error("no ch found");
exit;
}
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
- return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>';
+ return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.
+ self::NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
$this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
$this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
$this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
- 'xmlns:xmpp' => NS_BOSH,
+ 'xmlns:xmpp' => self::NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
if (isset($this->jaxl->cfg['jid'])) {
$attrs['from'] = $this->jaxl->cfg['jid'];
}
- $body = new JAXLXml('body', NS_HTTP_BIND, $attrs);
+ $body = new JAXLXml('body', self::NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
- $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
+ $body = new JAXLXml('body', self::NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
_debug("disconnecting");
}
}
diff --git a/xep/xep_0249.php b/xep/xep_0249.php
index 2438300..e776077 100644
--- a/xep/xep_0249.php
+++ b/xep/xep_0249.php
@@ -1,98 +1,97 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
-define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference');
-
class XEP_0249 extends XMPPXep
{
+ const NS_DIRECT_MUC_INVITATION = 'jabber:x:conference';
//
// abstract method
//
public function init()
{
return array();
}
//
// api methods
//
public function get_invite_pkt(
$to_bare_jid,
$room_jid,
$password = null,
$reason = null,
$thread = null,
$continue = null
) {
$xattrs = array('jid' => $room_jid);
if ($password) {
$xattrs['password'] = $password;
}
if ($reason) {
$xattrs['reason'] = $reason;
}
if ($thread) {
$xattrs['thread'] = $thread;
}
if ($continue) {
$xattrs['continue'] = $continue;
}
return $this->jaxl->get_msg_pkt(
array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid),
null,
null,
null,
- new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs)
+ new JAXLXml('x', self::NS_DIRECT_MUC_INVITATION, $xattrs)
);
}
public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null)
{
$this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue));
}
//
// event callbacks
//
}
|
jaxl/JAXL | 1c75699959fc12eae6bfe4d6b9dbc9eec52af161 | Move HTTP_* to HTTPServer | diff --git a/CHANGES.md b/CHANGES.md
index ffb1b38..1fbf40d 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,19 +1,20 @@
Changes
=======
JAXL introduces changes that affect compatibility:
v3.1.0
* PHP version >= 5.3: namespaces and anonymous functions.
* All methods now in camel case format (i.e. JAXL->require_xep => JAXL->requireXep).
* All constants now in upper case format (i.e. JAXL::version => JAXL::VERSION).
* Renaming of methods that starts with _ prefix, they only used in private API
and shouldn't affect you.
* JAXL_ERROR and other log levels goes to JAXLLogger::ERROR constant and so on.
+* HTTP_CRLF and other HTTP_* codes goes to HTTPServer::HTTP_* constants.
* JAXLEvent->reg is not public property anymore, but you can get
it with JAXLEvent->getRegistry()
* In JAXLXml::construct first argument $name is required.
* If some of your applications watch for debug message that starts with
"active read fds: " then you've warned about new message format
"Watch: active read fds: " and "Unwatch: active read fds: ".
diff --git a/http/http_request.php b/http/http_request.php
index a5f194e..e54d0d5 100644
--- a/http/http_request.php
+++ b/http/http_request.php
@@ -1,512 +1,512 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/http/http_multipart.php';
//
// These methods are available only once
// $request FSM has reached 'headers_received' state
//
// following shortcuts are available
// on received $request object:
//
// $request->{status_code_name}($headers, $body)
// $request->{status_code_name}($body, $headers)
//
// $request->{status_code_name}($headers)
// $request->{status_code_name}($body)
//
// following specific methods are also available:
//
// $request->send_line($code)
// $request->send_header($key, $value)
// $request->send_headers($headers)
// $request->send_message($string)
//
// all the above methods can also be directly performed using:
//
// $request->send_response($code, $headers = array(), $body = null)
//
// Note: All the send_* methods do not manage connection close/keep-alive logic,
// it is upto you to do that, by default connection will usually be dropped
// on client disconnect if not handled by you.
//
class HTTPRequest extends JAXLFsm
{
// peer identifier
public $sock = null;
public $ip = null;
public $port = null;
// request line
public $version = null;
public $method = null;
public $resource = null;
public $path = null;
public $query = array();
// headers and body
public $headers = array();
public $body = null;
public $recvd_body_len = 0;
// is true if 'Expect: 100-Continue'
// request header has been seen
public $expect = false;
// set if there is Content-Type: multipart/form-data; boundary=...
// header already seen
public $multipart = null;
// callback for send/read/close actions on accepted sock
private $send_cb = null;
private $read_cb = null;
private $close_cb = null;
private $shortcuts = array(
'ok' => 200, // 2xx
'redirect' => 302, 'not_modified' => 304, // 3xx
'not_found' => 404, 'bad_request' => 400, // 4xx
'internal_error' => 500, // 5xx
'recv_body' => true, 'close' => true // others
);
public function __construct($sock, $addr)
{
$this->sock = $sock;
$addr = explode(":", $addr);
$this->ip = $addr[0];
if (count($addr) == 2) {
$this->port = $addr[1];
}
parent::__construct("setup");
}
public function __destruct()
{
_debug("http request going down in ".$this->state." state");
}
public function state()
{
return $this->state;
}
//
// abstract method implementation
//
public function handle_invalid_state($r)
{
_debug("handle invalid state called with");
var_dump($r);
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case 'set_sock_cb':
$this->send_cb = $args[0];
$this->read_cb = $args[1];
$this->close_cb = $args[2];
return 'wait_for_request_line';
break;
default:
_warning("uncatched $event");
return 'setup';
}
}
public function wait_for_request_line($event, $args)
{
switch ($event) {
case 'line':
$this->line($args[0], $args[1], $args[2]);
return 'wait_for_headers';
break;
default:
_warning("uncatched $event");
return 'wait_for_request_line';
}
}
public function wait_for_headers($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'maybe_headers_received';
default:
_warning("uncatched $event");
return 'wait_for_headers';
}
}
public function maybe_headers_received($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'headers_received';
break;
case 'body':
return $this->wait_for_body($event, $args);
break;
default:
_warning("uncatched $event");
return 'maybe_headers_received';
}
}
public function wait_for_body($event, $args)
{
switch ($event) {
case 'body':
$content_length = $this->headers['Content-Length'];
$rcvd = $args[0];
$rcvd_len = strlen($rcvd);
$this->recvd_body_len += $rcvd_len;
if ($this->body === null) {
$this->body = $rcvd;
} else {
$this->body .= $rcvd;
}
if ($this->multipart) {
// boundary start, content_disposition, form data, boundary start, ....., boundary end
// these define various states of a multipart/form-data
$form_data = explode("\r\n", $rcvd);
foreach ($form_data as $data) {
//_debug("passing $data to multipart fsm");
if (!$this->multipart->process($data)) {
_debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
}
}
if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'set_header':
$content_length = $this->headers['Content-Length'];
$body = implode(":", $args);
$rcvd_len = strlen($body);
$this->recvd_body_len += $rcvd_len;
if (!$this->multipart->process($body)) {
_debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'empty_line':
$content_length = $this->headers['Content-Length'];
if (!$this->multipart->process('')) {
_debug("multipart fsm returned false");
$this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
default:
_warning("uncatched $event");
return 'wait_for_body';
}
}
// headers and may be body received
public function headers_received($event, $args)
{
switch ($event) {
case 'empty_line':
return 'headers_received';
break;
default:
if (substr($event, 0, 5) == 'send_') {
$protected = '_'.$event;
if (method_exists($this, $protected)) {
call_user_func_array(array(&$this, $protected), $args);
return 'headers_received';
} else {
_debug("non-existant method $event called");
return 'headers_received';
}
} elseif (isset($this->shortcuts[$event])) {
return $this->handle_shortcut($event, $args);
} else {
_warning("uncatched $event ".$args[0]);
return 'headers_received';
}
}
}
public function closed($event, $args)
{
_warning("uncatched $event");
}
// sets input headers
// called internally for every header received
protected function set_header($k, $v)
{
$k = trim($k);
$v = ltrim($v);
// is expect header?
if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') {
$this->expect = true;
}
// is multipart form data?
if (strtolower($k) == 'content-type') {
$ctype = explode(';', $v);
if (count($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') {
$boundary = explode('=', trim($ctype[1]));
if (strtolower(trim($boundary[0])) == 'boundary') {
_debug("multipart with boundary $boundary[1] detected");
$this->multipart = new HTTPMultiPart(ltrim($boundary[1]));
}
}
}
$this->headers[trim($k)] = trim($v);
}
// shortcut handler
protected function handle_shortcut($event, $args)
{
_debug("executing shortcut '$event'");
switch ($event) {
// http status code shortcuts
case 'ok':
case 'redirect':
case 'not_modified':
case 'bad_request':
case 'not_found':
case 'internal_error':
list($headers, $body) = $this->parse_shortcut_args($args);
$code = $this->shortcuts[$event];
$this->send_response($code, $headers, $body);
$this->close();
return 'closed';
break;
// others
case 'recv_body':
// send expect header if required
if ($this->expect) {
$this->expect = false;
$this->send_line(100);
}
// read data
$this->read();
return 'wait_for_body';
break;
case 'close':
$this->close();
return 'closed';
break;
}
}
private function parse_shortcut_args($args)
{
if (count($args) == 0) {
$body = null;
$headers = array();
}
if (count($args) == 1) {
// http headers or body only received
if (is_array($args[0])) {
// http headers only
$headers = $args[0];
$body = null;
} else {
// body only
$body = $args[0];
$headers = array();
}
} elseif (count($args) == 2) {
// body and http headers both received
if (is_array($args[0])) {
// header first
$body = $args[1];
$headers = $args[0];
} else {
// body first
$body = $args[0];
$headers = $args[1];
}
}
return array($headers, $body);
}
//
// send methods
// available only on 'headers_received' state
//
protected function send_line($code)
{
- $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF;
+ $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTPServer::HTTP_CRLF;
$this->send($raw);
}
protected function send_header($k, $v)
{
- $raw = $k.': '.$v.HTTP_CRLF;
+ $raw = $k.': '.$v.HTTPServer::HTTP_CRLF;
$this->send($raw);
}
protected function send_headers($code, $headers)
{
foreach ($headers as $k => $v) {
$this->send_header($k, $v);
}
}
protected function send_body($body)
{
$this->send($body);
}
protected function send_response($code, array $headers = array(), $body = null)
{
// send out response line
$this->send_line($code);
// set content length of body exists and is not already set
if ($body && !isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($body);
}
// send out headers
$this->send_headers($code, $headers);
// send body
// prefixed with an empty line
_debug("sending out HTTP_CRLF prefixed body");
if ($body) {
- $this->send_body(HTTP_CRLF.$body);
+ $this->send_body(HTTPServer::HTTP_CRLF.$body);
}
}
//
// internal methods
//
// initializes status line elements
private function line($method, $resource, $version)
{
$this->method = $method;
$this->resource = $resource;
$resource = explode("?", $resource);
$this->path = $resource[0];
if (count($resource) == 2) {
$query = $resource[1];
$query = explode("&", $query);
foreach ($query as $q) {
$q = explode("=", $q);
if (count($q) == 1) {
$q[1] = "";
}
$this->query[$q[0]] = $q[1];
}
}
$this->version = $version;
}
private function send($raw)
{
call_user_func($this->send_cb, $this->sock, $raw);
}
private function read()
{
call_user_func($this->read_cb, $this->sock);
}
private function close()
{
call_user_func($this->close_cb, $this->sock);
}
}
diff --git a/http/http_server.php b/http/http_server.php
index f0cf621..f85a1d1 100644
--- a/http/http_server.php
+++ b/http/http_server.php
@@ -1,204 +1,203 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/http/http_dispatcher.php';
require_once JAXL_CWD.'/http/http_request.php';
-// carriage return and line feed
-define('HTTP_CRLF', "\r\n");
-
-// 1xx informational
-define('HTTP_100', "Continue");
-define('HTTP_101', "Switching Protocols");
-
-// 2xx success
-define('HTTP_200', "OK");
-
-// 3xx redirection
-define('HTTP_301', 'Moved Permanently');
-define('HTTP_304', 'Not Modified');
-
-// 4xx client error
-define('HTTP_400', 'Bad Request');
-define('HTTP_403', 'Forbidden');
-define('HTTP_404', 'Not Found');
-define('HTTP_405', 'Method Not Allowed');
-define('HTTP_499', 'Client Closed Request'); // Nginx
-
-// 5xx server error
-define('HTTP_500', 'Internal Server Error');
-define('HTTP_503', 'Service Unavailable');
-
class HTTPServer
{
+ // Carriage return and line feed.
+ const HTTP_CRLF = "\r\n";
+
+ // 1xx informational
+ const HTTP_100 = 'Continue';
+ const HTTP_101 = 'Switching Protocols';
+
+ // 2xx success
+ const HTTP_200 = 'OK';
+
+ // 3xx redirection
+ const HTTP_301 = 'Moved Permanently';
+ const HTTP_304 = 'Not Modified';
+
+ // 4xx client error
+ const HTTP_400 = 'Bad Request';
+ const HTTP_403 = 'Forbidden';
+ const HTTP_404 = 'Not Found';
+ const HTTP_405 = 'Method Not Allowed';
+ const HTTP_499 = 'Client Closed Request'; // Nginx
+
+ // 5xx server error
+ const HTTP_500 = 'Internal Server Error';
+ const HTTP_503 = 'Service Unavailable';
/** @var JAXLSocketServer */
private $server = null;
/** @var callable */
public $cb = null;
private $dispatcher = null;
private $requests = array();
public function __construct($port = 9699, $address = "127.0.0.1")
{
$path = 'tcp://'.$address.':'.$port;
$this->server = new JAXLSocketServer(
$path,
array(&$this, 'on_accept'),
array(&$this, 'on_request')
);
$this->dispatcher = new HTTPDispatcher();
}
public function __destruct()
{
$this->server = null;
}
public function dispatch($rules)
{
foreach ($rules as $rule) {
$this->dispatcher->add_rule($rule);
}
}
/**
* @param callable $cb
*/
public function start($cb = null)
{
$this->cb = $cb;
JAXLLoop::run();
}
public function on_accept($sock, $addr)
{
_debug("on_accept for client#$sock, addr:$addr");
// initialize new request obj
$request = new HTTPRequest($sock, $addr);
// setup sock cb
$request->set_sock_cb(
array(&$this->server, 'send'),
array(&$this->server, 'read'),
array(&$this->server, 'close')
);
// cache request object
$this->requests[$sock] = &$request;
// reactive client for further read
$this->server->read($sock);
}
public function on_request($sock, $raw)
{
_debug("on_request for client#$sock");
$request = $this->requests[$sock];
// 'wait_for_body' state is reached when ever
// application calls recv_body() method
// on received $request object
if ($request->state() == 'wait_for_body') {
$request->body($raw);
} else {
// break on crlf
$lines = explode(HTTP_CRLF, $raw);
// parse request line
if ($request->state() == 'wait_for_request_line') {
list($method, $resource, $version) = explode(" ", $lines[0]);
$request->line($method, $resource, $version);
unset($lines[0]);
_info($request->ip." ".$request->method." ".$request->resource." ".$request->version);
}
// parse headers
foreach ($lines as $line) {
$line_parts = explode(":", $line);
if (count($line_parts) > 1) {
if (strlen($line_parts[0]) > 0) {
$k = $line_parts[0];
unset($line_parts[0]);
$v = implode(":", $line_parts);
$request->set_header($k, $v);
}
} elseif (strlen(trim($line_parts[0])) == 0) {
$request->empty_line();
} else {
// if exploded line array size is 1
// and there is something in $line_parts[0]
// must be request body
$request->body($line);
}
}
}
// if request has reached 'headers_received' state?
if ($request->state() == 'headers_received') {
// dispatch to any matching rule found
_debug("delegating to dispatcher for further routing");
$dispatched = $this->dispatcher->dispatch($request);
// if no dispatch rule matched call generic callback
if (!$dispatched && $this->cb) {
_debug("no dispatch rule matched, sending to generic callback");
call_user_func($this->cb, $request);
} elseif (!$dispatched) {
// elseif not dispatched and not generic callbacked
// send 404 not_found
// TODO: send 404 if no callback is registered for this request
_debug("dropping request since no matching dispatch rule or generic callback was specified");
$request->not_found('404 Not Found');
}
} else {
// if state is not 'headers_received'
// reactivate client socket for read event
$this->server->read($sock);
}
}
}
|
jaxl/JAXL | 56152e38aa4c047974a8944d962b7fc835131b73 | Add setColors to setup logger colors | diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php
index 1d792c0..1a5acff 100644
--- a/core/jaxl_logger.php
+++ b/core/jaxl_logger.php
@@ -1,122 +1,137 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// generic global logging shortcuts for different level of verbosity
function _error($msg)
{
JAXLLogger::log($msg, JAXLLogger::ERROR);
}
function _warning($msg)
{
JAXLLogger::log($msg, JAXLLogger::WARNING);
}
function _notice($msg)
{
JAXLLogger::log($msg, JAXLLogger::NOTICE);
}
function _info($msg)
{
JAXLLogger::log($msg, JAXLLogger::INFO);
}
function _debug($msg)
{
JAXLLogger::log($msg, JAXLLogger::DEBUG);
}
// generic global terminal output colorize method
// finally sends colorized message to terminal using error_log/1
// this method is mainly to escape $msg from file:line and time
// prefix done by _debug, _error, ... methods
function _colorize($msg, $verbosity)
{
error_log(JAXLLogger::colorize($msg, $verbosity));
}
class JAXLLogger
{
// Log levels.
const ERROR = 1;
const WARNING = 2;
const NOTICE = 3;
const INFO = 4;
const DEBUG = 5;
public static $colorize = true;
public static $level = self::DEBUG;
public static $path = null;
public static $max_log_size = 1000;
protected static $colors = array(
self::ERROR => 31, // red
self::WARNING => 34, // blue
self::NOTICE => 33, // yellow
self::INFO => 32, // green
self::DEBUG => 37 // white
);
public static function log($msg, $verbosity = self::ERROR)
{
if ($verbosity <= self::$level) {
$bt = debug_backtrace();
array_shift($bt);
$callee = array_shift($bt);
$msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg;
$size = strlen($msg);
if ($size > self::$max_log_size) {
$msg = substr($msg, 0, self::$max_log_size) . ' ...';
}
if (isset(self::$path)) {
error_log($msg . PHP_EOL, 3, self::$path);
} else {
error_log(self::colorize($msg, $verbosity));
}
}
}
+ /**
+ * @param string $msg
+ * @param int $verbosity
+ * @return string
+ */
public static function colorize($msg, $verbosity)
{
if (self::$colorize) {
return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m";
} else {
return $msg;
}
}
+
+ /**
+ * @param array $colors
+ */
+ public static function setColors(array $colors)
+ {
+ foreach ($colors as $k => $v) {
+ self::$colors[$k] = $v;
+ }
+ }
}
diff --git a/tests/JAXLLoggerTest.php b/tests/JAXLLoggerTest.php
new file mode 100644
index 0000000..0b292ee
--- /dev/null
+++ b/tests/JAXLLoggerTest.php
@@ -0,0 +1,44 @@
+<?php
+
+JAXL::dummy();
+
+class JAXLLoggerTest extends PHPUnit_Framework_TestCase
+{
+
+ /**
+ * @runInSeparateProcess<--fixme
+ */
+ public function testColorize()
+ {
+ $msg = 'Test message';
+
+ // TODO: Fix JAXL to run with @runInSeparateProcess and remove following line.
+ $current = JAXLLogger::$colorize;
+
+ JAXLLogger::$colorize = false;
+ $this->assertEquals($msg, JAXLLogger::colorize($msg, JAXLLogger::ERROR));
+
+ JAXLLogger::$colorize = true;
+ $this->assertNotEquals($msg, JAXLLogger::colorize($msg, JAXLLogger::ERROR));
+
+ $color = 123;
+ JAXLLogger::setColors(array(
+ JAXLLogger::ERROR => $color
+ ));
+ $this->assertEquals("\033[" . $color . "m" . $msg . "\033[0m", JAXLLogger::colorize($msg, JAXLLogger::ERROR));
+
+ // TODO: Fix JAXL to run with @runInSeparateProcess and remove following line.
+ JAXLLogger::$colorize = $current;
+ }
+
+ /**
+ * @requires PHP 5.4
+ * @requires function uopz_backup
+ */
+ public function testLog()
+ {
+ $msg = 'Test message';
+ uopz_backup('error_log');
+ JAXLLogger::log($msg);
+ }
+}
|
jaxl/JAXL | 40de6b81b9569f0e706605875e0b198ffaeedd71 | Move log levels to JAXLLogger | diff --git a/CHANGES.md b/CHANGES.md
index 9cab571..ffb1b38 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,18 +1,19 @@
Changes
=======
JAXL introduces changes that affect compatibility:
v3.1.0
* PHP version >= 5.3: namespaces and anonymous functions.
* All methods now in camel case format (i.e. JAXL->require_xep => JAXL->requireXep).
* All constants now in upper case format (i.e. JAXL::version => JAXL::VERSION).
* Renaming of methods that starts with _ prefix, they only used in private API
and shouldn't affect you.
+* JAXL_ERROR and other log levels goes to JAXLLogger::ERROR constant and so on.
* JAXLEvent->reg is not public property anymore, but you can get
it with JAXLEvent->getRegistry()
* In JAXLXml::construct first argument $name is required.
* If some of your applications watch for debug message that starts with
"active read fds: " then you've warned about new message format
"Watch: active read fds: " and "Unwatch: active read fds: ".
diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php
index b3418b4..1d792c0 100644
--- a/core/jaxl_logger.php
+++ b/core/jaxl_logger.php
@@ -1,122 +1,122 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
-// log level
-define('JAXL_ERROR', 1);
-define('JAXL_WARNING', 2);
-define('JAXL_NOTICE', 3);
-define('JAXL_INFO', 4);
-define('JAXL_DEBUG', 5);
-
// generic global logging shortcuts for different level of verbosity
function _error($msg)
{
- JAXLLogger::log($msg, JAXL_ERROR);
+ JAXLLogger::log($msg, JAXLLogger::ERROR);
}
function _warning($msg)
{
- JAXLLogger::log($msg, JAXL_WARNING);
+ JAXLLogger::log($msg, JAXLLogger::WARNING);
}
function _notice($msg)
{
- JAXLLogger::log($msg, JAXL_NOTICE);
+ JAXLLogger::log($msg, JAXLLogger::NOTICE);
}
function _info($msg)
{
- JAXLLogger::log($msg, JAXL_INFO);
+ JAXLLogger::log($msg, JAXLLogger::INFO);
}
function _debug($msg)
{
- JAXLLogger::log($msg, JAXL_DEBUG);
+ JAXLLogger::log($msg, JAXLLogger::DEBUG);
}
// generic global terminal output colorize method
// finally sends colorized message to terminal using error_log/1
// this method is mainly to escape $msg from file:line and time
// prefix done by _debug, _error, ... methods
function _colorize($msg, $verbosity)
{
error_log(JAXLLogger::colorize($msg, $verbosity));
}
class JAXLLogger
{
-
+
+ // Log levels.
+ const ERROR = 1;
+ const WARNING = 2;
+ const NOTICE = 3;
+ const INFO = 4;
+ const DEBUG = 5;
+
public static $colorize = true;
- public static $level = JAXL_DEBUG;
+ public static $level = self::DEBUG;
public static $path = null;
public static $max_log_size = 1000;
-
+
protected static $colors = array(
- 1 => 31, // error: red
- 2 => 34, // warning: blue
- 3 => 33, // notice: yellow
- 4 => 32, // info: green
- 5 => 37 // debug: white
+ self::ERROR => 31, // red
+ self::WARNING => 34, // blue
+ self::NOTICE => 33, // yellow
+ self::INFO => 32, // green
+ self::DEBUG => 37 // white
);
-
- public static function log($msg, $verbosity = 1)
+
+ public static function log($msg, $verbosity = self::ERROR)
{
if ($verbosity <= self::$level) {
$bt = debug_backtrace();
array_shift($bt);
$callee = array_shift($bt);
$msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg;
$size = strlen($msg);
if ($size > self::$max_log_size) {
$msg = substr($msg, 0, self::$max_log_size) . ' ...';
}
if (isset(self::$path)) {
error_log($msg . PHP_EOL, 3, self::$path);
} else {
error_log(self::colorize($msg, $verbosity));
}
}
}
-
+
public static function colorize($msg, $verbosity)
{
if (self::$colorize) {
return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m";
} else {
return $msg;
}
}
}
diff --git a/docs/users/jaxl_instance.rst b/docs/users/jaxl_instance.rst
index 501db1e..b25e390 100644
--- a/docs/users/jaxl_instance.rst
+++ b/docs/users/jaxl_instance.rst
@@ -1,166 +1,167 @@
.. _jaxl-instance:
JAXL Instance
=============
+
``JAXL`` instance configure/manage other :ref:`sub-packages <jaxl-instance>`.
It provides an event based callback methodology on various underlying object. Whenever required
``JAXL`` instance will itself perform the configured defaults.
Constructor options
-------------------
#. ``jid``
#. ``pass``
#. ``resource``
If not passed Jaxl will use a random resource value
#. ``auth_type``
DIGEST-MD5, PLAIN (default), CRAM-MD5, ANONYMOUS, X-FACEBOOK-PLATFORM
#. ``host``
#. ``port``
#. ``bosh_url``
#. ``log_path``
#. ``log_level``
- ``JAXL_ERROR``, ``JAXL_WARNING``, ``JAXL_NOTICE``, ``JAXL_INFO`` (default), ``JAXL_DEBUG``
+ ``ERROR``, ``WARNING``, ``NOTICE``, ``INFO`` (default), ``DEBUG``
#. ``fb_access_token``
required when using X-FACEBOOK-PLATFORM auth mechanism
#. ``fb_app_key``
required when using X-FACEBOOK-PLATFORM auth mechanism
#. ``force_tls``
#. ``stream_context``
#. ``priv_dir``
Jaxl creates 4 directories names ``log``, ``tmp``, ``run`` and ``sock`` inside a private directory
which defaults to ``JAXL_CWD.'/.jaxl'``. If this option is passed, it will overwrite default private
directory.
.. note::
Jaxl currently doesn't check upon the permissions of passed ``priv_dir``. Make sure Jaxl library
have sufficient permissions to create above mentioned directories.
Available Event Callbacks
-------------------------
Following ``$ev`` are available on ``JAXL`` lifecycle for registering callbacks:
#. ``on_connect``
``JAXL`` instance has connected successfully
#. ``on_connect_error``
``JAXL`` instance failed to connect
#. ``on_stream_start``
``JAXL`` instance has successfully initiated XMPP stream with the jabber server
#. ``on_stream_features``
``JAXL`` instance has received supported stream features
#. ``on_auth_success``
authentication successful
#. ``on_auth_failure``
authentication failed
#. ``on_presence_stanza``
``JAXL`` instance has received a presence stanza
#. ``on_{$type}_message``
``JAXL`` instance has received a message stanza. ``$type`` can be ``chat``, ``groupchat``, ``headline``, ``normal``, ``error``
#. ``on_stanza_id_{$id}``
Useful when dealing with iq stanza. This event is fired when ``JAXL`` instance has received response to a particular
xmpp stanza id
#. ``on_{$name}_stanza``
Useful when dealing with custom xmpp stanza
#. ``on_disconnect``
``JAXL`` instance has disconnected from the jabber server
Available Methods
-----------------
Following methods are available on initialized ``JAXL`` instance object:
#. ``get_pid_file_path()``
returns path of ``JAXL`` instance pid file
#. ``get_sock_file_path()``
returns path to ``JAXL`` ipc unix socket domain
#. ``require_xep($xeps = array())``
autoload and initialize passed XEP's
#. ``add_cb($ev, $cb, $priority = 1)``
add a callback to function ``$cb`` on event ``$ev``, returns a reference of added callback
#. ``del_cb($ref)``
delete previously registered event callback
#. ``set_status($status, $show, $priority)``
send a presence status stanza
#. ``send_chat_msg($to, $body, $thread = null, $subject = null)``
send a message stanza of type chat
#. ``get_vcard($jid = null, $cb = null)``
fetch vcard for bare ``$jid``, passed ``$cb`` will be called with received vcard stanza
#. ``get_roster($cb = null)``
fetch roster list of connected jabber client, passed ``$cb`` will be called with received roster stanza
#. ``start($opts = array())``
start configured ``JAXL`` instance, optionally accepts two options specified below:
#. ``--with-debug-shell``
start ``JAXL`` instance and enter an interactive console
#. ``--with-unix-sock``
start ``JAXL`` instance with support for IPC and remote debugging
#. ``send($stanza)``
send an instance of JAXLXml packet over connected socket
#. ``send_raw($data)``
send raw payload over connected socket
#. ``get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)``
#. ``get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)``
- #. ``get_iq_pkt($attrs, $payload)``
\ No newline at end of file
+ #. ``get_iq_pkt($attrs, $payload)``
diff --git a/docs/users/logging.rst b/docs/users/logging.rst
index 687d606..6abc18b 100644
--- a/docs/users/logging.rst
+++ b/docs/users/logging.rst
@@ -1,29 +1,30 @@
Logging Interface
=================
+
``JAXLLogger`` provides all the logging facilities that we will ever require.
When logging to ``STDOUT`` it also colorizes the log message depending upon its severity level.
When logging to a file it can also do periodic log rotation.
log levels
----------
- * JAXL_ERROR (red)
- * JAXL_WARNING (blue)
- * JAXL_NOTICE (yellow)
- * JAXL_INFO (green)
- * JAXL_DEBUG (white)
+ * ERROR (red)
+ * WARNING (blue)
+ * NOTICE (yellow)
+ * INFO (green)
+ * DEBUG (white)
global logging methods
----------------------
Following global methods for logging are available:
* ``_error($msg)``
* ``_warning($msg)``
* ``_notice($msg)``
* ``_info($msg)``
* ``_debug($msg)``
_colorize/2
-----------
All the above global logging methods internally use ``_colorize($msg, $verbosity)`` to output colored
-log message on the terminal.
\ No newline at end of file
+log message on the terminal.
diff --git a/examples/curl.php b/examples/curl.php
index 86b82bf..6937297 100644
--- a/examples/curl.php
+++ b/examples/curl.php
@@ -1,49 +1,49 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 2) {
echo "Usage: $argv[0] url\n";
exit;
}
require_once 'jaxl.php';
-JAXLLogger::$level = JAXL_DEBUG;
+JAXLLogger::$level = JAXLLogger::DEBUG;
require_once JAXL_CWD.'/http/http_client.php';
$request = new HTTPClient($argv[1]);
$request->start();
diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php
index 445a9c5..552321c 100644
--- a/examples/echo_bosh_bot.php
+++ b/examples/echo_bosh_bot.php
@@ -1,106 +1,106 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'bosh_url' => 'http://localhost:5280/http-bind',
// (optional) srv lookup is done if not provided
// for bosh client 'host' value is used for 'route' attribute
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
// for bosh client 'port' value is used for 'route' attribute
//'port' => 5222,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
- 'log_level' => JAXL_INFO
+ 'log_level' => JAXLLogger::INFO
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/echo_bot.php b/examples/echo_bot.php
index ad2377d..b4d1dc0 100644
--- a/examples/echo_bot.php
+++ b/examples/echo_bot.php
@@ -1,147 +1,147 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// Run as:
// php examples/echo_bot.php root@localhost password
// php examples/echo_bot.php root@localhost password DIGEST-MD5
// php examples/echo_bot.php localhost "" ANONYMOUS
if ($argc < 3) {
echo "Usage: $argv[0] jid pass auth_type\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (optional) srv lookup is done if not provided
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
//'port' => 5222,
// (optional) defaults to false
//'force_tls' => true,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
- 'log_level' => JAXL_INFO
+ 'log_level' => JAXLLogger::INFO
));
//
// required XEP's
//
$client->require_xep(array(
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
});
// by default JAXL instance catches incoming roster list results and updates
// roster list is parsed/cached and an event 'on_roster_update' is emitted
$client->add_cb('on_roster_update', function () {
//global $client;
//print_r($client->roster);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
_info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_presence_stanza', function ($stanza) {
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
_info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start(array(
'--with-debug-shell' => true,
'--with-unix-sock' => true
));
echo "done\n";
diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php
index 2e55019..aa64145 100644
--- a/examples/echo_component_bot.php
+++ b/examples/echo_component_bot.php
@@ -1,98 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc != 5) {
echo "Usage: $argv[0] jid pass host port\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'host' => $argv[3],
'port' => $argv[4],
- 'log_level' => JAXL_INFO
+ 'log_level' => JAXLLogger::INFO
));
//
// XEP's required (required)
//
$comp->require_xep(array(
'0114' // jabber component protocol
));
//
// add necessary event callbacks here
//
$comp->add_cb('on_auth_success', function () {
_info("got on_auth_success cb");
});
$comp->add_cb('on_auth_failure', function ($reason) {
global $comp;
$comp->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$comp->add_cb('on_chat_message', function ($stanza) {
global $comp;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $comp->jid->to_string();
$comp->send($stanza);
});
$comp->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$comp->start();
echo "done\n";
diff --git a/examples/echo_http_server.php b/examples/echo_http_server.php
index 0ad9d31..2eb0e0c 100644
--- a/examples/echo_http_server.php
+++ b/examples/echo_http_server.php
@@ -1,59 +1,59 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// include and configure logger
require_once 'jaxl.php';
-JAXLLogger::$level = JAXL_INFO;
+JAXLLogger::$level = JAXLLogger::INFO;
// print usage notice and parse addr/port parameters if passed
-_colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE);
+_colorize("Usage: $argv[0] port (default: 9699)", JAXLLogger::NOTICE);
$port = ($argc == 2 ? $argv[1] : 9699);
// initialize http server
require_once JAXL_CWD.'/http/http_server.php';
$http = new HTTPServer($port);
// catch all incoming requests here
function on_request($request)
{
$body = json_encode($request);
$request->ok($body, array('Content-Type' => 'application/json'));
}
// start http server
$http->start('on_request');
diff --git a/examples/echo_unix_sock_server.php b/examples/echo_unix_sock_server.php
index 7e7421b..1e2c6a9 100644
--- a/examples/echo_unix_sock_server.php
+++ b/examples/echo_unix_sock_server.php
@@ -1,62 +1,62 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 2) {
echo "Usage: $argv[0] /path/to/server.sock\n";
exit;
}
require_once 'jaxl.php';
-JAXLLogger::$level = JAXL_INFO;
+JAXLLogger::$level = JAXLLogger::INFO;
$server = null;
function on_request($client, $raw)
{
global $server;
$server->send($client, $raw);
_info("got client callback ".$raw);
}
if (file_exists($argv[1])) {
unlink($argv[1]);
}
$server = new JAXLSocketServer('unix://'.$argv[1], null, 'on_request');
JAXLLoop::run();
echo "done\n";
diff --git a/examples/http_bind.php b/examples/http_bind.php
index 0ae7c87..de1ce9e 100644
--- a/examples/http_bind.php
+++ b/examples/http_bind.php
@@ -1,64 +1,64 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if (!isset($_GET['jid']) || !isset($_GET['pass'])) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
require_once '../jaxl.php';
$client = new JAXL(array(
'jid' => $_GET['jid'],
'pass' => $_GET['pass'],
'bosh_url' => 'http://localhost:5280/http-bind',
- 'log_level' => JAXL_DEBUG
+ 'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php
index d3a1faa..a1bc945 100644
--- a/examples/http_pre_bind.php
+++ b/examples/http_pre_bind.php
@@ -1,99 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// http pre bind php script
$body = file_get_contents("php://input");
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (!isset($attrs['to']) &&
!isset($attrs['rid']) &&
!isset($attrs['wait']) &&
!isset($attrs['hold'])
) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
require_once '../jaxl.php';
$to = (string)$attrs['to'];
$rid = (int)$attrs['rid'];
$wait = (int)$attrs['wait'];
$hold = (int)$attrs['hold'];
list($host, $port) = JAXLUtil::get_dns_srv($to);
$client = new JAXL(array(
'domain' => $to,
'host' => $host,
'port' => $port,
'bosh_url' => 'http://localhost:5280/http-bind',
'bosh_rid' => $rid,
'bosh_wait' => $wait,
'bosh_hold' => $hold,
'auth_type' => 'ANONYMOUS',
- 'log_level' => JAXL_INFO
+ 'log_level' => JAXLLogger::INFO
));
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
echo sprintf(
'<body xmlns="%s" sid="%s" rid="%s" jid="%s"/>',
NS_HTTP_BIND,
$client->xeps['0206']->sid,
$client->xeps['0206']->rid,
$client->full_jid->to_string()
);
exit;
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
_info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php
index 8d16912..784f499 100644
--- a/examples/http_rest_server.php
+++ b/examples/http_rest_server.php
@@ -1,127 +1,127 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// include and configure logger
require_once 'jaxl.php';
-JAXLLogger::$level = JAXL_INFO;
+JAXLLogger::$level = JAXLLogger::INFO;
// print usage notice and parse addr/port parameters if passed
-_colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE);
+_colorize("Usage: $argv[0] port (default: 9699)", JAXLLogger::NOTICE);
$port = ($argc == 2 ? $argv[1] : 9699);
// initialize http server
require_once JAXL_CWD.'/http/http_server.php';
$http = new HTTPServer($port);
// callback method for dispatch rule (see below)
function index($request)
{
$request->send_response(
200,
array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>'
);
$request->close();
}
// callback method for dispatch rule (see below)
function upload($request)
{
if ($request->method == 'GET') {
$request->ok(
array('Content-Type' => 'text/html'),
'<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" ' .
'action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" ' .
'value="upload"/></form></body></html>'
);
} elseif ($request->method == 'POST') {
if ($request->body === null && $request->expect) {
$request->recv_body();
} else {
// got upload body, save it
_info("file upload complete, got ".strlen($request->body)." bytes of data");
$upload_data = $request->multipart->form_data[0]['body'];
$request->ok(
$upload_data,
array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])
);
}
}
}
// add dispatch rules with callback method as first argument
$index = array('index', '^/$');
$upload = array('upload', '^/upload', array('GET', 'POST'));
// some REST CRUD style callback methods
// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules
function create_event($request)
{
_info("got event create request");
$request->close();
}
function read_event($request, $pk)
{
_info("got event read request for $pk");
$request->close();
}
function update_event($request, $pk)
{
_info("got event update request for $pk");
$request->close();
}
function delete_event($request, $pk)
{
_info("got event delete request for $pk");
$request->close();
}
$event_create = array('create_event', '^/event/create/$', array('PUT'));
$event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD'));
$event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST'));
$event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE'));
// prepare rule set
$rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete);
$http->dispatch($rules);
// start http server
$http->start();
diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php
index 19bd013..00a33fd 100644
--- a/examples/muc_log_bot.php
+++ b/examples/muc_log_bot.php
@@ -1,146 +1,146 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 5) {
echo "Usage: $argv[0] host jid pass [email protected] nickname\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[2],
'pass' => $argv[3],
'host' => $argv[1],
- 'log_level' => JAXL_INFO
+ 'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0045', // MUC
'0203', // Delayed Delivery
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$_room_full_jid = $argv[4]."/".$argv[5];
$room_full_jid = new XMPPJid($_room_full_jid);
$client->add_cb('on_auth_success', function () {
global $client, $room_full_jid;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// join muc room
$client->xeps['0045']->join_room($room_full_jid);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_groupchat_message', function ($stanza) {
global $client;
$from = new XMPPJid($stanza->from);
$delay = $stanza->exists('delay', NS_DELAYED_DELIVERY);
if ($from->resource) {
echo sprintf(
"message stanza rcvd from %s saying... %s, %s".PHP_EOL,
$from->resource,
$stanza->body,
$delay ? "delay timestamp ".$delay->attrs['stamp'] : "timestamp ".gmdate("Y-m-dTH:i:sZ")
);
} else {
$subject = $stanza->exists('subject');
if ($subject) {
echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".
$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL;
}
}
});
$client->add_cb('on_presence_stanza', function ($stanza) {
global $client, $room_full_jid;
$from = new XMPPJid($stanza->from);
// self-stanza received, we now have complete room roster
if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) {
if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) {
if (($status = $x->exists('status', null, array('code' => '110'))) !== false) {
$item = $x->exists('item');
_info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].
", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']);
} else {
_info("xmlns #user have no x child element");
}
} else {
_warning("=======> odd case 1");
}
} elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) {
// stanza from other users received
if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) {
$item = $x->exists('item');
echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".
$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL;
} else {
_warning("=======> odd case 2");
}
} else {
_warning("=======> odd case 3");
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/multi_client.php b/examples/multi_client.php
index 97757a5..4d0bdd3 100644
--- a/examples/multi_client.php
+++ b/examples/multi_client.php
@@ -1,132 +1,132 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// enable multi client support
// this will force 1st parameter of callbacks
// as connected client instance
define('JAXL_MULTI_CLIENT', true);
// input multiple account credentials
$accounts = array();
$add_new = true;
while ($add_new) {
$jid = readline('Enter Jabber Id: ');
$pass = readline('Enter Password: ');
$accounts[] = array($jid, $pass);
$next = readline('Add another account (y/n): ');
$add_new = $next == 'y' ? true : false;
}
// setup jaxl
require_once 'jaxl.php';
//
// common callbacks
//
function on_auth_success($client)
{
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
}
function on_auth_failure($client, $reason)
{
_info("got on_auth_failure cb with reason $reason");
$client->send_end_stream();
}
function on_chat_message($client, $stanza)
{
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
}
function on_presence_stanza($client, $stanza)
{
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
_info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
}
function on_disconnect($client)
{
_info("got on_disconnect cb");
}
//
// bootstrap all account instances
//
foreach ($accounts as $account) {
$client = new JAXL(array(
'jid' => $account[0],
'pass' => $account[1],
- 'log_level' => JAXL_DEBUG
+ 'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', 'on_auth_success');
$client->add_cb('on_auth_failure', 'on_auth_failure');
$client->add_cb('on_chat_message', 'on_chat_message');
$client->add_cb('on_presence_stanza', 'on_presence_stanza');
$client->add_cb('on_disconnect', 'on_disconnect');
$client->connect($client->get_socket_path());
$client->start_stream();
}
// start core loop
JAXLLoop::run();
echo "done\n";
diff --git a/examples/pipes.php b/examples/pipes.php
index 1f7a1a8..697251f 100644
--- a/examples/pipes.php
+++ b/examples/pipes.php
@@ -1,57 +1,57 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// include and configure logger
require_once 'jaxl.php';
-JAXLLogger::$level = JAXL_INFO;
+JAXLLogger::$level = JAXLLogger::INFO;
// include jaxl pipes
require_once JAXL_CWD.'/core/jaxl_pipe.php';
// initialize
$pipe_name = getmypid();
$pipe = new JAXLPipe($pipe_name);
// add read event callback
$pipe->set_callback(function ($data) {
global $pipe;
_info("read ".trim($data)." from pipe");
});
JAXLLoop::run();
echo "done\n";
diff --git a/examples/publisher.php b/examples/publisher.php
index 51730e1..d66a78e 100644
--- a/examples/publisher.php
+++ b/examples/publisher.php
@@ -1,101 +1,101 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
- 'log_level' => JAXL_INFO
+ 'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// publish
$item = new JAXLXml('item', null, array('id' => time()));
$item->c('entry', 'http://www.w3.org/2005/Atom');
$item->c('title')->t('Soliloquy')->up();
$item->c('summary')->t('To be, or not to be: that is the question')->up();
$item->c(
'link',
null,
array('rel' => 'alternate', 'type' => 'text/html', 'href' => 'http://denmark.lit/2003/12/13/atom03')
)->up();
$item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up();
$item->c('published')->t('2003-12-13T18:30:02Z')->up();
$item->c('updated')->t('2003-12-13T18:30:02Z')->up();
$client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/register_user.php b/examples/register_user.php
index 77bf93b..1e17b45 100644
--- a/examples/register_user.php
+++ b/examples/register_user.php
@@ -1,167 +1,167 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 2) {
echo "Usage: $argv[0] domain\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
- 'log_level' => JAXL_DEBUG
+ 'log_level' => JAXLLogger::DEBUG
));
$client->require_xep(array(
'0077' // InBand Registration
));
//
// below are two states which become part of
// our client's xmpp_stream lifecycle
// consider as if these methods are directly
// inside xmpp_stream state machine
//
// Note: $stanza = $args[0] is an instance of
// JAXLXml in xmpp_stream state methods,
// it is yet not ready for easy access
// patterns available on XMPPStanza instances
//
$form = array();
function wait_for_register_response($event, $args)
{
global $client, $form;
if ($event == 'stanza_cb') {
$stanza = $args[0];
if ($stanza->name == 'iq') {
$form['type'] = $stanza->attrs['type'];
if ($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
} elseif ($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo sprintf(
"registration failed with error code: %s and type: %s".PHP_EOL,
$error->attrs['code'],
$error->attrs['type']
);
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
}
}
} else {
_notice("unhandled event $event rcvd");
}
}
function wait_for_register_form($event, $args)
{
global $client, $form;
$stanza = $args[0];
$query = $stanza->exists('query', NS_INBAND_REGISTER);
if ($query) {
$instructions = $query->exists('instructions');
if ($instructions) {
echo $instructions->text.PHP_EOL;
}
foreach ($query->childrens as $k => $child) {
if ($child->name != 'instructions') {
$form[$child->name] = readline($child->name.":");
}
}
$client->xeps['0077']->set_form($stanza->attrs['from'], $form);
return "wait_for_register_response";
} else {
$client->end_stream();
return "logged_out";
}
}
//
// add necessary event callbacks here
//
$client->add_cb('on_stream_features', function ($stanza) {
global $client, $argv;
$client->xeps['0077']->get_form($argv[1]);
return "wait_for_register_form";
});
$client->add_cb('on_disconnect', function () {
global $form;
_info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
});
//
// finally start configured xmpp stream
//
$client->start();
//
// if registration was successful
// try to connect with newly registered account
//
if ($form['type'] == 'result') {
_info("connecting newly registered user account");
$client = new JAXL(array(
'jid' => $form['username'].'@'.$argv[1],
'pass' => $form['password'],
- 'log_level' => JAXL_DEBUG
+ 'log_level' => JAXLLogger::DEBUG
));
$client->add_cb('on_auth_success', function () {
global $client;
$client->set_status('Available');
});
$client->start();
}
echo "done\n";
diff --git a/examples/subscriber.php b/examples/subscriber.php
index 62da19f..f5b54d7 100644
--- a/examples/subscriber.php
+++ b/examples/subscriber.php
@@ -1,96 +1,96 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
- 'log_level' => JAXL_INFO
+ 'log_level' => JAXLLogger::INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// subscribe
$client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node');
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_headline_message', function ($stanza) {
global $client;
if (($event = $stanza->exists('event', NS_PUBSUB.'#event'))) {
_info("got pubsub event");
} else {
_warning("unknown headline message rcvd");
}
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/xfacebook_platform_client.php b/examples/xfacebook_platform_client.php
index 6eca5af..a64ef40 100644
--- a/examples/xfacebook_platform_client.php
+++ b/examples/xfacebook_platform_client.php
@@ -1,98 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc != 4) {
echo "Usage: $argv[0] fb_user_id_or_username fb_app_key fb_access_token\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1].'@chat.facebook.com',
'fb_app_key' => $argv[2],
'fb_access_token' => $argv[3],
// force tls (facebook require this now)
'force_tls' => true,
// (required) force facebook oauth
'auth_type' => 'X-FACEBOOK-PLATFORM',
// (optional)
//'resource' => 'resource',
- 'log_level' => JAXL_INFO
+ 'log_level' => JAXLLogger::INFO
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php
index ec04b96..a470a67 100644
--- a/examples/xmpp_rest.php
+++ b/examples/xmpp_rest.php
@@ -1,75 +1,75 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// View explanation for this example here:
// https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
// initialize xmpp client
require_once 'jaxl.php';
$xmpp = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
- 'log_level' => JAXL_INFO
+ 'log_level' => JAXLLogger::INFO
));
// register callbacks on required xmpp events
$xmpp->add_cb('on_auth_success', function () {
global $xmpp;
_info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string());
});
// initialize http server
require_once JAXL_CWD.'/http/http_server.php';
$http = new HTTPServer();
// add generic callback
// you can also dispatch REST style callback
// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules
$http->cb = function ($request) {
// For demo purposes we simply return xmpp client full jid
global $xmpp;
$request->ok($xmpp->full_jid->to_string());
};
// This will start main JAXLLoop,
// hence we don't need to call $http->start() explicitly
$xmpp->start();
diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php
index 0d3acc7..85c0387 100644
--- a/examples/xoauth2_gtalk_client.php
+++ b/examples/xoauth2_gtalk_client.php
@@ -1,97 +1,97 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc != 3) {
echo "Usage: $argv[0] jid access_token\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// force tls
'force_tls' => true,
// (required) perform X-OAUTH2
'auth_type' => 'X-OAUTH2',
// (optional)
//'resource' => 'resource',
- 'log_level' => JAXL_DEBUG
+ 'log_level' => JAXLLogger::DEBUG
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
});
$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
});
$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/jaxl.php b/jaxl.php
index d555b34..62fbbb0 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,611 +1,611 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
- public $log_level = JAXL_INFO;
+ public $log_level = JAXLLogger::INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
/**
* @return JAXLSocketClient|XEP_0206
*/
public function getTransport()
{
return $this->trans;
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
diff --git a/jaxlctl b/jaxlctl
index ce513fd..5269121 100755
--- a/jaxlctl
+++ b/jaxlctl
@@ -1,200 +1,200 @@
#!/usr/bin/env php
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
error_reporting(E_ALL | E_STRICT);
date_default_timezone_set('UTC');
$params = $argv;
$exe = array_shift($params);
$command = array_shift($params);
require_once 'jaxl.php';
-JAXLLogger::$level = JAXL_INFO;
+JAXLLogger::$level = JAXLLogger::INFO;
// TODO: an abstract JAXLCtlCommand class
// with seperate class per command
// a mechanism to register new commands
class JAXLCtl
{
protected $ipc = null;
protected $buffer = '';
protected $buffer_cb = null;
protected $cli = null;
public $dots = "....... ";
protected $symbols = array();
public function __construct($command, $params)
{
global $exe;
if (method_exists($this, $command)) {
$r = call_user_func_array(array(&$this, $command), $params);
if (count($r) == 2) {
list($buffer_cb, $quit_cb) = $r;
$this->buffer_cb = $buffer_cb;
$this->cli = new JAXLCli(array(&$this, 'onTerminalInput'), $quit_cb);
$this->run();
} else {
- _colorize("oops! internal command error", JAXL_ERROR);
+ _colorize("oops! internal command error", JAXLLogger::ERROR);
exit;
}
} else {
- _colorize("error: invalid command '$command' received", JAXL_ERROR);
- _colorize("type '$exe help' for list of available commands", JAXL_NOTICE);
+ _colorize("error: invalid command '$command' received", JAXLLogger::ERROR);
+ _colorize("type '$exe help' for list of available commands", JAXLLogger::NOTICE);
exit;
}
}
public function run()
{
JAXLCli::prompt();
JAXLLoop::run();
}
public function onTerminalInput($raw)
{
$raw = trim($raw);
$last = substr($raw, -1, 1);
if ($last == ";") {
// dispatch to buffer callback
call_user_func($this->buffer_cb, $this->buffer.$raw);
$this->buffer = '';
} elseif ($last == '\\') {
$this->buffer .= substr($raw, 0, -1);
echo $this->dots;
} else {
// buffer command
$this->buffer .= $raw."; ";
echo $this->dots;
}
}
public static function printHelp()
{
global $exe;
- _colorize("Usage: $exe command [options...]\n", JAXL_INFO);
- _colorize("Commands:", JAXL_NOTICE);
- _colorize(" help This help text", JAXL_DEBUG);
- _colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG);
- _colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG);
+ _colorize("Usage: $exe command [options...]\n", JAXLLogger::INFO);
+ _colorize("Commands:", JAXLLogger::NOTICE);
+ _colorize(" help This help text", JAXLLogger::DEBUG);
+ _colorize(" debug Attach a debug console to a running JAXL daemon", JAXLLogger::DEBUG);
+ _colorize(" shell Open up Jaxl shell emulator", JAXLLogger::DEBUG);
echo "\n";
}
protected function help()
{
JAXLCtl::printHelp();
exit;
}
//
// shell command
//
protected function shell()
{
return array(array(&$this, 'onShellInput'), array(&$this, 'onShellQuit'));
}
private function eval_($raw, $symbols)
{
extract($symbols);
eval($raw);
$g = get_defined_vars();
unset($g['raw']);
unset($g['symbols']);
return $g;
}
public function onShellInput($raw)
{
$this->symbols = $this->eval_($raw, $this->symbols);
JAXLCli::prompt();
}
public function onShellQuit()
{
exit;
}
//
// debug command
//
protected function debug($sock_path)
{
$this->ipc = new JAXLSocketClient();
$this->ipc->set_callback(array(&$this, 'onDebugResponse'));
$this->ipc->connect('unix://'.$sock_path);
return array(array(&$this, 'onDebugInput'), array(&$this, 'onDebugQuit'));
}
public function onDebugResponse($raw)
{
$ret = unserialize($raw);
print_r($ret);
echo "\n";
JAXLCli::prompt();
}
public function onDebugInput($raw)
{
$this->ipc->send($this->buffer.$raw);
}
public function onDebugQuit()
{
$this->ipc->disconnect();
exit;
}
}
// we atleast need a command argument
if ($argc < 2) {
JAXLCtl::printHelp();
exit;
}
$ctl = new JAXLCtl($command, $params);
echo "done\n";
|
jaxl/JAXL | 7c4dc7441f9e80c0fa3a1606fc5b94ecfd13bcd0 | JAXLEvent->reg is not public anymore | diff --git a/CHANGES.md b/CHANGES.md
index 64d3b75..9cab571 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,16 +1,18 @@
Changes
=======
JAXL introduces changes that affect compatibility:
v3.1.0
* PHP version >= 5.3: namespaces and anonymous functions.
* All methods now in camel case format (i.e. JAXL->require_xep => JAXL->requireXep).
* All constants now in upper case format (i.e. JAXL::version => JAXL::VERSION).
* Renaming of methods that starts with _ prefix, they only used in private API
and shouldn't affect you.
+* JAXLEvent->reg is not public property anymore, but you can get
+ it with JAXLEvent->getRegistry()
* In JAXLXml::construct first argument $name is required.
* If some of your applications watch for debug message that starts with
"active read fds: " then you've warned about new message format
"Watch: active read fds: " and "Unwatch: active read fds: ".
diff --git a/core/jaxl_event.php b/core/jaxl_event.php
index 91a3168..fa81072 100644
--- a/core/jaxl_event.php
+++ b/core/jaxl_event.php
@@ -1,156 +1,164 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Following kind of events are possible:
* 1) hook i.e. if a callback for such an event is registered, calling function
* is responsible for the workflow from their on
* 2) filter i.e. calling function will manipulate passed arguments
* and modified arguments will be passed to next chain of filter
*
* As a rule of thumb, only 1 hook can be registered for an event, while more
* than 1 filter is allowed for an event hook and filter both cannot be applied
* on an event.
*
* @author abhinavsingh
*
*/
class JAXLEvent
{
protected $common = array();
- public $reg = array();
+ protected $reg = array();
public function __construct($common)
{
$this->common = $common;
}
public function __destruct()
{
}
/**
* Add callback on a event.
*
* Callback'd method must return `true` to be persistent, otherwise
* if returned `null` or `false`, callback will be removed automatically.
*
* @param string $ev
* @param callable $cb
* @param int $priority
* @return string Reference to be used while deleting callback.
*/
public function add($ev, $cb, $priority)
{
if (!isset($this->reg[$ev])) {
$this->reg[$ev] = array();
}
$ref = count($this->reg[$ev]);
$this->reg[$ev][] = array($priority, $cb);
return $ev."-".$ref;
}
/**
* Emit event to notify registered callbacks.
*
* TODO: Is a pqueue required here for performance enhancement in case we
* have too many cbs on a specific event?
*
* @param string $ev
* @param array $data
* @return array
*/
public function emit($ev, array $data = array())
{
$data = array_merge($this->common, $data);
$cbs = array();
if (!isset($this->reg[$ev])) {
return $data;
}
foreach ($this->reg[$ev] as $cb) {
if (!isset($cbs[$cb[0]])) {
$cbs[$cb[0]] = array();
}
$cbs[$cb[0]][] = $cb[1];
}
foreach ($cbs as $pri => $cb) {
foreach ($cb as $c) {
$ret = call_user_func_array($c, $data);
// This line is for fixing situation where callback function doesn't return an array type.
// In such cases next call of call_user_func_array will report error since $data is not
// an array type as expected.
// Things will change in future, atleast put the callback inside a try/catch block.
// Here we only check if there was a return, if yes we update $data with return value.
// This is bad design, need more thoughts, should work as of now.
if ($ret) {
$data = $ret;
}
}
}
unset($cbs);
return $data;
}
/**
* Remove previous registered callback.
*
* @param string $ref
*/
public function del($ref)
{
$ref = explode("-", $ref);
unset($this->reg[$ref[0]][$ref[1]]);
}
/**
* @param string $ev
* @return bool
*/
public function exists($ev)
{
$ret = isset($this->reg[$ev]);
//_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists"));
return $ret;
}
+
+ /**
+ * @return array List of registered events.
+ */
+ public function getRegistry()
+ {
+ return $this->reg;
+ }
}
diff --git a/tests/JAXLEventTest.php b/tests/JAXLEventTest.php
index 9f1fa25..a8a0ac6 100644
--- a/tests/JAXLEventTest.php
+++ b/tests/JAXLEventTest.php
@@ -1,71 +1,74 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
JAXL::dummy();
/**
*
* @author abhinavsingh
*
*/
class JAXLEventTest extends PHPUnit_Framework_TestCase
{
public function test_jaxl_event()
{
$ev = new JAXLEvent(array());
$ref1 = $ev->add('on_connect', 'some_func', 0);
$ref2 = $ev->add('on_connect', 'some_func1', 0);
$ref3 = $ev->add('on_connect', 'some_func2', 1);
$ref4 = $ev->add('on_connect', 'some_func3', 4);
$ref5 = $ev->add('on_disconnect', 'some_func', 1);
$ref6 = $ev->add('on_disconnect', 'some_func1', 1);
//$ev->emit('on_connect', null);
+ $registry = $ev->getRegistry();
+ $this->assertEquals(2, count($registry));
+ $this->assertEquals(4, count($registry['on_connect']));
+ $this->assertEquals(2, count($registry['on_disconnect']));
+
$ev->del($ref2);
$ev->del($ref1);
$ev->del($ref6);
$ev->del($ref5);
$ev->del($ref4);
$ev->del($ref3);
-
- //print_r($ev->reg);
}
}
|
jaxl/JAXL | d57350495ed9945ae0e456b45151cc81597aaaa1 | Add required in JAXLXml::construct | diff --git a/CHANGES.md b/CHANGES.md
index 8b95051..64d3b75 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,15 +1,16 @@
Changes
=======
JAXL introduces changes that affect compatibility:
v3.1.0
* PHP version >= 5.3: namespaces and anonymous functions.
* All methods now in camel case format (i.e. JAXL->require_xep => JAXL->requireXep).
* All constants now in upper case format (i.e. JAXL::version => JAXL::VERSION).
* Renaming of methods that starts with _ prefix, they only used in private API
and shouldn't affect you.
+* In JAXLXml::construct first argument $name is required.
* If some of your applications watch for debug message that starts with
"active read fds: " then you've warned about new message format
"Watch: active read fds: " and "Unwatch: active read fds: ".
diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php
index 53c13be..3f34785 100644
--- a/core/jaxl_xml.php
+++ b/core/jaxl_xml.php
@@ -1,307 +1,307 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/
* Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml
*
* @author abhinavsingh
*
*/
class JAXLXml
{
public $name;
public $ns = null;
public $attrs = array();
public $xml = null;
public $text = null;
/** @var JAXLXml[] */
public $childrens = array();
public $parent = null;
public $rover = null;
/**
* Accepts any of the following constructors:
*
* * JAXLXml($name, $ns, $attrs, $text)
* * JAXLXml($name, $ns, $attrs)
* * JAXLXml($name, $ns, $text)
* * JAXLXml($name, $attrs, $text)
* * JAXLXml($name, $attrs)
* * JAXLXml($name, $ns)
* * JAXLXml($name)
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
- public function __construct()
+ public function __construct($name)
{
$argv = func_get_args();
$argc = count($argv);
- $this->name = $argv[0];
+ $this->name = $name;
switch ($argc) {
case 4:
$this->ns = $argv[1];
$this->attrs = $argv[2];
$this->text = $argv[3];
break;
case 3:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
$this->text = $argv[2];
} else {
$this->ns = $argv[1];
if (is_array($argv[2])) {
$this->attrs = $argv[2];
} else {
$this->text = $argv[2];
}
}
break;
case 2:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
} else {
$this->ns = $argv[1];
}
break;
default:
break;
}
$this->rover = &$this;
}
public function __destruct()
{
}
/**
* @param array $attrs
* @return JAXLXml
*/
public function attrs(array $attrs)
{
$this->rover->attrs = array_merge($this->rover->attrs, $attrs);
return $this;
}
/**
* @param array $attrs
* @return bool
*/
public function match_attrs(array $attrs)
{
$matches = true;
foreach ($attrs as $k => $v) {
if ($this->attrs[$k] !== $v) {
$matches = false;
break;
}
}
return $matches;
}
/**
* Set or append XML.
*
* @param unknown $xml
* @param bool $append
* @return JAXLXml
*/
public function x($xml, $append = false)
{
if (!$append) {
$this->rover->xml = $xml;
} else {
if ($this->rover->xml === null) {
$this->rover->xml = '';
}
$this->rover->xml .= $xml;
}
return $this;
}
/**
* Set or append text.
*
* @param string $text
* @param bool $append
* @return JAXLXml
*/
public function t($text, $append = false)
{
if (!$append) {
$this->rover->text = $text;
} else {
if ($this->rover->text === null) {
$this->rover->text = '';
}
$this->rover->text .= $text;
}
return $this;
}
/**
* Create child.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
* @return JAXLXml
*/
public function c($name, $ns = null, array $attrs = array(), $text = null)
{
$node = new JAXLXml($name, $ns, $attrs, $text);
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
/**
* Append child node.
*
* @param JAXLXml $node
* @return JAXLXml
*/
public function cnode($node)
{
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
public function up()
{
if ($this->rover->parent) {
$this->rover = &$this->rover->parent;
}
return $this;
}
public function top()
{
$this->rover = &$this;
return $this;
}
/**
* @param string $name
* @param string $ns
* @param array $attrs
* @return JAXLXml|bool
*/
public function exists($name, $ns = null, array $attrs = array())
{
foreach ($this->childrens as $child) {
if ($ns) {
if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) {
return $child;
}
} elseif ($child->name == $name && $child->match_attrs($attrs)) {
return $child;
}
}
return false;
}
/**
* Update child with name ``$name``.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
public function update($name, $ns = null, array $attrs = array(), $text = null)
{
foreach ($this->childrens as $k => $child) {
if ($child->name == $name) {
$child->ns = $ns;
$child->attrs($attrs);
$child->text = $text;
$this->childrens[$k] = $child;
break;
}
}
}
/**
* @param string $parent_ns
* @return string
*/
public function to_string($parent_ns = null)
{
$xml = '';
$xml .= '<'.$this->name;
if ($this->ns && $this->ns != $parent_ns) {
$xml .= ' xmlns="'.$this->ns.'"';
}
foreach ($this->attrs as $k => $v) {
if (!is_null($v) && $v !== false) {
$xml .= ' '.$k.'="'.htmlspecialchars($v).'"';
}
}
$xml .= '>';
foreach ($this->childrens as $child) {
$xml .= $child->to_string($this->ns);
}
if ($this->xml !== null) {
$xml .= $this->xml;
}
if ($this->text !== null) {
$xml .= htmlspecialchars($this->text);
}
$xml .= '</'.$this->name.'>';
return $xml;
}
}
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index aa9859d..92f8f0e 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,18 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
- convertNoticesToExceptions="false"
- convertWarningsToExceptions="false"
+ convertNoticesToExceptions="true"
+ convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
>
<testsuites>
<testsuite>
<directory suffix="Test.php">tests/</directory>
</testsuite>
</testsuites>
</phpunit>
diff --git a/tests/test_jaxl_xml.php b/tests/JAXLXmlTest.php
similarity index 88%
rename from tests/test_jaxl_xml.php
rename to tests/JAXLXmlTest.php
index 6bcb581..3bd5436 100644
--- a/tests/test_jaxl_xml.php
+++ b/tests/JAXLXmlTest.php
@@ -1,81 +1,85 @@
<?php
JAXL::dummy();
-/**
- *
- * @author abhinavsingh
- *
- */
class JAXLXmlTest extends PHPUnit_Framework_TestCase
{
public static $NS = 'SOME_NAMESPACE';
public static $attrs = array('attr1' => 'value1');
+ /**
+ * @expectedException PHPUnit_Framework_Error_Warning
+ */
public function testJAXLXml_0()
{
$xml = new JAXLXml();
$this->assertEquals('<></>', $xml->to_string());
}
- public function testJAXLXml_1()
+ public function testJAXLXml_1_1()
+ {
+ $xml = new JAXLXml('');
+ $this->assertEquals('<></>', $xml->to_string());
+ }
+
+ public function testJAXLXml_1_2()
{
$xml = new JAXLXml('html');
$this->assertEquals('<html></html>', $xml->to_string());
}
public function testJAXLXml_2_1()
{
$xml = new JAXLXml('html', self::$NS);
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE"></html>',
$xml->to_string()
);
}
public function testJAXLXml_2_2()
{
$xml = new JAXLXml('html', self::$attrs);
$this->assertEquals(
'<html attr1="value1"></html>',
$xml->to_string()
);
}
public function testJAXLXml_3_1()
{
$xml = new JAXLXml('html', self::$attrs, 'Some text');
$this->assertEquals(
'<html attr1="value1">Some text</html>',
$xml->to_string()
);
}
public function testJAXLXml_3_2()
{
$xml = new JAXLXml('html', self::$NS, 'Some text');
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE">Some text</html>',
$xml->to_string()
);
}
public function testJAXLXml_3_3()
{
$xml = new JAXLXml('html', self::$NS, self::$attrs);
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE" attr1="value1"></html>',
$xml->to_string()
);
}
public function testJAXLXml_4()
{
$xml = new JAXLXml('html', self::$NS, self::$attrs, 'Some text');
$this->assertEquals(
'<html xmlns="SOME_NAMESPACE" attr1="value1">Some text</html>',
$xml->to_string()
);
}
}
|
jaxl/JAXL | 8a334ca81006119d1f300a1436498d37ce5b7e08 | Make transport obtainable | diff --git a/jaxl.php b/jaxl.php
index 68d1aad..d555b34 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,785 +1,793 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const VERSION = '3.0.2';
const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
-
+
+ /**
+ * @return JAXLSocketClient|XEP_0206
+ */
+ public function getTransport()
+ {
+ return $this->trans;
+ }
+
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
if (isset($this->cfg['fb_access_token'])) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
diff --git a/tests/JAXLTest.php b/tests/JAXLTest.php
index 250bf82..138382a 100644
--- a/tests/JAXLTest.php
+++ b/tests/JAXLTest.php
@@ -1,58 +1,59 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
JAXL::dummy();
/**
*
* @author abhinavsingh
*
*/
class JAXLTest extends PHPUnit_Framework_TestCase
{
public function testProtocolOption()
{
$config = array(
'host' => 'domain.tld',
'port' => 5223,
'protocol' => 'tcp'
);
$jaxl = new JAXL($config);
$this->assertEquals('tcp://domain.tld:5223', $jaxl->get_socket_path());
+ $this->assertInstanceOf('JAXLSocketClient', $jaxl->getTransport());
}
}
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php
index b366fdb..99794b5 100644
--- a/xmpp/xmpp_stream.php
+++ b/xmpp/xmpp_stream.php
@@ -1,617 +1,617 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
require_once JAXL_CWD.'/core/jaxl_xml_stream.php';
require_once JAXL_CWD.'/core/jaxl_util.php';
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/xmpp/xmpp_msg.php';
require_once JAXL_CWD.'/xmpp/xmpp_pres.php';
require_once JAXL_CWD.'/xmpp/xmpp_iq.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
* @var JAXLSocketClient|XEP_0206
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
- * @param string $transport
+ * @param JAXLSocketClient|XEP_0206 $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
$jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//_debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
_error("got invalid return value from state handler '".$this->state."', sending end stream...");
$this->send_end_stream();
$this->state = "logged_out";
_notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers");
}
/**
* @param JAXLXml|XMPPStanza $stanza
*/
public function send($stanza)
{
$this->trans->send($stanza->to_string());
}
/**
* @param string $data
*/
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
_debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//_debug("stream started");
return "wait_for_stream_features";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', NS_BIND) ? true : false;
$sess = $stanza->exists('session', NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
_debug("no catch");
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) {
|
jaxl/JAXL | 5cec396a76a9fd7f62504ba3f26dbb0a9e4f56c7 | Set unique verbose log message | diff --git a/CHANGES.md b/CHANGES.md
index f3df771..8b95051 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,11 +1,15 @@
Changes
=======
JAXL introduces changes that affect compatibility:
v3.1.0
* PHP version >= 5.3: namespaces and anonymous functions.
* All methods now in camel case format (i.e. JAXL->require_xep => JAXL->requireXep).
* All constants now in upper case format (i.e. JAXL::version => JAXL::VERSION).
-* Renaming of methods that starts with _ prefix, they only used in private API and shouldn't affect you.
+* Renaming of methods that starts with _ prefix, they only used in private API
+ and shouldn't affect you.
+* If some of your applications watch for debug message that starts with
+ "active read fds: " then you've warned about new message format
+ "Watch: active read fds: " and "Unwatch: active read fds: ".
diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php
index cdc13ea..5103ad4 100644
--- a/core/jaxl_loop.php
+++ b/core/jaxl_loop.php
@@ -1,171 +1,171 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_clock.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLLoop
{
/**
* @var JAXLClock
*/
public static $clock = null;
private static $is_running = false;
private static $active_read_fds = 0;
private static $active_write_fds = 0;
private static $read_fds = array();
private static $read_cbs = array();
private static $write_fds = array();
private static $write_cbs = array();
private static $secs = 0;
private static $usecs = 30000;
private function __construct()
{
}
private function __clone()
{
}
public static function watch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
self::$read_fds[$fdid] = $fd;
self::$read_cbs[$fdid] = $opts['read'];
++self::$active_read_fds;
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
self::$write_fds[$fdid] = $fd;
self::$write_cbs[$fdid] = $opts['write'];
++self::$active_write_fds;
}
- _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
+ _debug("Watch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function unwatch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
if (isset(self::$read_fds[$fdid])) {
unset(self::$read_fds[$fdid]);
unset(self::$read_cbs[$fdid]);
--self::$active_read_fds;
}
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
if (isset(self::$write_fds[$fdid])) {
unset(self::$write_fds[$fdid]);
unset(self::$write_cbs[$fdid]);
--self::$active_write_fds;
}
}
- _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
+ _debug("Unwatch: active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function run()
{
if (!self::$is_running) {
self::$is_running = true;
self::$clock = new JAXLClock();
while ((self::$active_read_fds + self::$active_write_fds) > 0) {
self::select();
}
_debug("no more active fd's to select");
self::$is_running = false;
}
}
public static function select()
{
$read = self::$read_fds;
$write = self::$write_fds;
$except = null;
$changed = @stream_select($read, $write, $except, self::$secs, self::$usecs);
if ($changed === false) {
_error("error in the event loop, shutting down...");
/*foreach (self::$read_fds as $fd) {
if (is_resource($fd)) {
print_r(stream_get_meta_data($fd));
}
}*/
exit;
} elseif ($changed > 0) {
// read callback
foreach ($read as $r) {
$fdid = array_search($r, self::$read_fds);
if (isset(self::$read_fds[$fdid])) {
call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]);
}
}
// write callback
foreach ($write as $w) {
$fdid = array_search($w, self::$write_fds);
if (isset(self::$write_fds[$fdid])) {
call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]);
}
}
self::$clock->tick();
} elseif ($changed === 0) {
//_debug("nothing changed while selecting for read");
self::$clock->tick((self::$secs * pow(10, 6)) + self::$usecs);
}
}
}
|
jaxl/JAXL | 1b5477426f3001a200c9d4ba7bfbbc9a592b3755 | Bump version to v3.0.2 | diff --git a/README.md b/README.md
index 71e38f7..97f3e56 100644
--- a/README.md
+++ b/README.md
@@ -1,51 +1,51 @@
-Jaxl v3.0.1
+Jaxl v3.0.2
-----------
Jaxl v3.x is a successor of v2.x (and is NOT backward compatible),
carrying a lot of code from v2.x while throwing away the ugly parts.
A lot of components have been re-written keeping in mind the feedback from
the developer community over the last 4 years. Also Jaxl shares a few
philosophies from my experience with erlang and python languages.
Jaxl is an asynchronous, non-blocking I/O, event based PHP library
for writing custom TCP/IP client and server implementations.
From it's previous versions, library inherits a full blown stable support
-for [XMPP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.1/xmpp).
-In v3.0, support for [HTTP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.1/http)
+for [XMPP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.2/xmpp).
+In v3.0, support for [HTTP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.2/http)
has also been added.
-At the heart of every protocol stack sits the [Core stack](https://github.com/jaxl/JAXL/tree/v3.0.1/core).
+At the heart of every protocol stack sits the [Core stack](https://github.com/jaxl/JAXL/tree/v3.0.2/core).
It contains all the building blocks for everything that we aim to do with Jaxl library.
Both XMPP and HTTP protocol stacks are written on top of the Core stack.
Infact the source code of protocol implementations knows nothing
about the standard (inbuilt) PHP socket and stream methods.
-[Examples](https://github.com/jaxl/JAXL/tree/v3.0.1/examples/)
+[Examples](https://github.com/jaxl/JAXL/tree/v3.0.2/examples/)
[Documentation](http://jaxl.readthedocs.org/)
[Group and Mailing List](https://groups.google.com/forum/#!forum/jaxl)
[Create a bug/issue](https://github.com/jaxl/JAXL/issues/new)
[Author](http://abhinavsingh.com/)
## Contributing
-JAXL v3.0.1 adopt [PSR-2](http://www.php-fig.org/psr/psr-2/).
+JAXL since v3.0.1 adopt [PSR-2](http://www.php-fig.org/psr/psr-2/).
To make it easier to maintain the code contribute your changes after they have
passed [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer)
and [PHPUnit](https://github.com/sebastianbergmann/phpunit). If possible, add
a unit tests for your changes into the *tests* folder.
To know current errors and failed tests, run:
```ShellSession
./vendor/bin/phpcs
./vendor/bin/phpunit
```
## License
The product licensed under the BSD 3-Clause license.
See [LICENSE](https://github.com/jaxl/JAXL/blob/master/LICENSE).
diff --git a/docs/conf.py b/docs/conf.py
index f2e3aa4..2371394 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,242 +1,242 @@
# -*- coding: utf-8 -*-
#
# Jaxl documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 15 03:08:42 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode']
# , 'sphinxcontrib.phpdomain'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Jaxl'
copyright = u'2012, Abhinav Singh'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '3.0'
# The full version, including alpha/beta/rc tags.
-release = '3.0.1'
+release = '3.0.2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'pastie'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Jaxldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Jaxl.tex', u'Jaxl Documentation',
u'Abhinav Singh', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'jaxl', u'Jaxl Documentation',
[u'Abhinav Singh'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Jaxl', u'Jaxl Documentation',
u'Abhinav Singh', 'Jaxl', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
diff --git a/jaxl.php b/jaxl.php
index f857f55..57ab060 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,579 +1,579 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
- const version = '3.0.1';
+ const version = '3.0.2';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
/**
* Signals callback handler.
*
* Not for public API consumption.
*
* @param int $sig
*/
public function signal_handler($sig)
{
$this->end_stream();
$this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
|
jaxl/JAXL | 643048ab8b37126606de218ef9fd24c3506a47f6 | Add license name | diff --git a/LICENSE b/LICENSE
index 59792ca..6e7e778 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,33 +1,33 @@
Jaxl (Jabber XMPP Library)
Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
Neither the name of Abhinav Singh nor the names of his
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
diff --git a/README.md b/README.md
index b84d867..71e38f7 100644
--- a/README.md
+++ b/README.md
@@ -1,46 +1,51 @@
Jaxl v3.0.1
-----------
Jaxl v3.x is a successor of v2.x (and is NOT backward compatible),
carrying a lot of code from v2.x while throwing away the ugly parts.
A lot of components have been re-written keeping in mind the feedback from
the developer community over the last 4 years. Also Jaxl shares a few
philosophies from my experience with erlang and python languages.
Jaxl is an asynchronous, non-blocking I/O, event based PHP library
for writing custom TCP/IP client and server implementations.
From it's previous versions, library inherits a full blown stable support
for [XMPP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.1/xmpp).
In v3.0, support for [HTTP protocol stack](https://github.com/jaxl/JAXL/tree/v3.0.1/http)
has also been added.
At the heart of every protocol stack sits the [Core stack](https://github.com/jaxl/JAXL/tree/v3.0.1/core).
It contains all the building blocks for everything that we aim to do with Jaxl library.
Both XMPP and HTTP protocol stacks are written on top of the Core stack.
Infact the source code of protocol implementations knows nothing
about the standard (inbuilt) PHP socket and stream methods.
[Examples](https://github.com/jaxl/JAXL/tree/v3.0.1/examples/)
[Documentation](http://jaxl.readthedocs.org/)
[Group and Mailing List](https://groups.google.com/forum/#!forum/jaxl)
[Create a bug/issue](https://github.com/jaxl/JAXL/issues/new)
[Author](http://abhinavsingh.com/)
## Contributing
JAXL v3.0.1 adopt [PSR-2](http://www.php-fig.org/psr/psr-2/).
To make it easier to maintain the code contribute your changes after they have
passed [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer)
and [PHPUnit](https://github.com/sebastianbergmann/phpunit). If possible, add
a unit tests for your changes into the *tests* folder.
To know current errors and failed tests, run:
```ShellSession
./vendor/bin/phpcs
./vendor/bin/phpunit
```
+
+## License
+
+The product licensed under the BSD 3-Clause license.
+See [LICENSE](https://github.com/jaxl/JAXL/blob/master/LICENSE).
|
jaxl/JAXL | 2e6545bf87b3ba2b540d63652c1e2c0a312813f3 | Add tests for JAXLXml | diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index 4ef33a8..a2b44df 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,18 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
- convertNoticesToExceptions="true"
- convertWarningsToExceptions="true"
+ convertNoticesToExceptions="false"
+ convertWarningsToExceptions="false"
processIsolation="false"
stopOnFailure="false"
>
<testsuites>
<testsuite name="JAXL">
<directory suffix=".php">tests/</directory>
</testsuite>
</testsuites>
</phpunit>
diff --git a/tests/test_jaxl_xml.php b/tests/test_jaxl_xml.php
new file mode 100644
index 0000000..6bcb581
--- /dev/null
+++ b/tests/test_jaxl_xml.php
@@ -0,0 +1,81 @@
+<?php
+
+JAXL::dummy();
+
+/**
+ *
+ * @author abhinavsingh
+ *
+ */
+class JAXLXmlTest extends PHPUnit_Framework_TestCase
+{
+
+ public static $NS = 'SOME_NAMESPACE';
+ public static $attrs = array('attr1' => 'value1');
+
+ public function testJAXLXml_0()
+ {
+ $xml = new JAXLXml();
+ $this->assertEquals('<></>', $xml->to_string());
+ }
+
+ public function testJAXLXml_1()
+ {
+ $xml = new JAXLXml('html');
+ $this->assertEquals('<html></html>', $xml->to_string());
+ }
+
+ public function testJAXLXml_2_1()
+ {
+ $xml = new JAXLXml('html', self::$NS);
+ $this->assertEquals(
+ '<html xmlns="SOME_NAMESPACE"></html>',
+ $xml->to_string()
+ );
+ }
+
+ public function testJAXLXml_2_2()
+ {
+ $xml = new JAXLXml('html', self::$attrs);
+ $this->assertEquals(
+ '<html attr1="value1"></html>',
+ $xml->to_string()
+ );
+ }
+
+ public function testJAXLXml_3_1()
+ {
+ $xml = new JAXLXml('html', self::$attrs, 'Some text');
+ $this->assertEquals(
+ '<html attr1="value1">Some text</html>',
+ $xml->to_string()
+ );
+ }
+
+ public function testJAXLXml_3_2()
+ {
+ $xml = new JAXLXml('html', self::$NS, 'Some text');
+ $this->assertEquals(
+ '<html xmlns="SOME_NAMESPACE">Some text</html>',
+ $xml->to_string()
+ );
+ }
+
+ public function testJAXLXml_3_3()
+ {
+ $xml = new JAXLXml('html', self::$NS, self::$attrs);
+ $this->assertEquals(
+ '<html xmlns="SOME_NAMESPACE" attr1="value1"></html>',
+ $xml->to_string()
+ );
+ }
+
+ public function testJAXLXml_4()
+ {
+ $xml = new JAXLXml('html', self::$NS, self::$attrs, 'Some text');
+ $this->assertEquals(
+ '<html xmlns="SOME_NAMESPACE" attr1="value1">Some text</html>',
+ $xml->to_string()
+ );
+ }
+}
diff --git a/tests/test_xmpp_stanza.php b/tests/test_xmpp_stanza.php
index 1780c04..138f4f5 100644
--- a/tests/test_xmpp_stanza.php
+++ b/tests/test_xmpp_stanza.php
@@ -1,77 +1,83 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
JAXL::dummy();
/**
*
* @author abhinavsingh
*
*/
class XMPPStanzaTest extends PHPUnit_Framework_TestCase
{
public function test_xmpp_stanza_nested()
{
- $stanza = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]'));
- $stanza
- ->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up()
- ->c('thread')->t('1234')->up()
- ->c('nested')
- ->c('nest')->t('nest1')->up()
- ->c('nest')->t('nest2')->up()
- ->c('nest')->t('nest3')->up()->up()
- ->c('c')->attrs(array('hash' => '84jsdmnskd'));
+ $xml = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]'));
+ $xml->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up()
+ ->c('thread')->t('1234')->up()
+ ->c('nested')
+ ->c('nest')->t('nest1')->up()
+ ->c('nest')->t('nest2')->up()
+ ->c('nest')->t('nest3')->up()->up()
+ ->c('c')->attrs(array('hash' => '84jsdmnskd'));
+ $stanza = new XMPPStanza($xml);
$this->assertEquals(
'<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested>' .
'<nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>',
$stanza->to_string()
);
}
public function test_xmpp_stanza_from_jaxl_xml()
{
// xml to stanza test
$xml = new JAXLXml('message', NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q'));
$stanza = new XMPPStanza($xml);
$stanza->c('body')->t('hello world');
- echo $stanza->to."\n";
- echo $stanza->to_string()."\n";
+ $this->assertEquals('XMPPStanza', get_class($stanza));
+ $this->assertEquals('JAXLXml', get_class($stanza->exists('body')));
+ $this->assertEquals('[email protected]', $stanza->to);
+ $this->assertEquals(
+ '<message xmlns="jabber:client" to="[email protected]" from="[email protected]/q">' .
+ '<body>hello world</body></message>',
+ $stanza->to_string()
+ );
}
}
|
jaxl/JAXL | 84e66c8b49124c96a0edda72cc691d6295dbc3cd | Unavailable method disconnect was used | diff --git a/composer.json b/composer.json
index 3c016a5..64b0eb1 100644
--- a/composer.json
+++ b/composer.json
@@ -1,43 +1,46 @@
{
"name": "jaxl/jaxl",
"type": "library",
"description": "Jaxl - Async, Non-Blocking, Event based Networking Library in PHP.",
"keywords": ["xmpp", "jabber", "http", "asynchronous", "non blocking", "event loop", "php", "jaxl", "abhinavsingh"],
"homepage": "http://jaxl.readthedocs.org/en/latest/index.html",
"license": "MIT",
"support": {
"forum": "https://groups.google.com/forum/#!forum/jaxl",
"issues": "https://github.com/jaxl/JAXL/issues",
"source": "https://github.com/jaxl/JAXL"
},
"authors": [
{
"name": "Abhinavsingh",
"homepage": "https://abhinavsingh.com/"
}
],
"require": {
"php": ">=5.2.4",
"ext-curl": "*",
"ext-hash": "*",
"ext-json": "*",
"ext-libxml": "*",
"ext-openssl": "*",
"ext-pcre": "*",
"ext-sockets": "*"
},
"require-dev": {
"phpunit/phpunit": "^3.7.0",
"squizlabs/php_codesniffer": "*"
},
+ "suggest": {
+ "ext-pcntl": "Interrupt JAXL with signals"
+ },
"autoload": {
"classmap": [
"core",
"http",
"xep",
"xmpp",
"jaxl.php"
]
},
"bin": ["jaxlctl"]
}
diff --git a/jaxl.php b/jaxl.php
index 034b6c0..f857f55 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,932 +1,937 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const version = '3.0.1';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
-
- // signals callback handler
- // not for public api consumption
+
+ /**
+ * Signals callback handler.
+ *
+ * Not for public API consumption.
+ *
+ * @param int $sig
+ */
public function signal_handler($sig)
{
$this->end_stream();
- $this->disconnect();
+ $this->trans->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
if (isset($this->cfg['fb_access_token'])) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
|
jaxl/JAXL | 504b283528fbc80133f61024a33c300a2ae40324 | Use count is more PHP-tonic | diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php
index b03eba2..eef7931 100644
--- a/core/jaxl_clock.php
+++ b/core/jaxl_clock.php
@@ -1,129 +1,129 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
class JAXLClock
{
// current clock time in microseconds
private $tick = 0;
// current Unix timestamp with microseconds
public $time = null;
// scheduled jobs
public $jobs = array();
public function __construct()
{
$this->time = microtime(true);
}
public function __destruct()
{
_info("shutting down clock server...");
}
public function tick($by = null)
{
// update clock
if ($by) {
$this->tick += $by;
$this->time += $by / pow(10, 6);
} else {
$time = microtime(true);
$by = $time - $this->time;
$this->tick += $by * pow(10, 6);
$this->time = $time;
}
// run scheduled jobs
foreach ($this->jobs as $ref => $job) {
if ($this->tick >= $job['scheduled_on'] + $job['after']) {
//_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".
// $job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']);
call_user_func($job['cb'], $job['args']);
if (!$job['is_periodic']) {
unset($this->jobs[$ref]);
} else {
$job['scheduled_on'] = $this->tick;
$job['runs']++;
$this->jobs[$ref] = $job;
}
}
}
}
// calculate execution time of callback
public function tc($callback, $args = null)
{
}
// callback after $time microseconds
public function call_fun_after($time, $callback, $args = null)
{
$this->jobs[] = array(
'scheduled_on' => $this->tick,
'after' => $time,
'cb' => $callback,
'args' => $args,
'is_periodic' => false,
'runs' => 0
);
- return sizeof($this->jobs);
+ return count($this->jobs);
}
// callback periodically after $time microseconds
public function call_fun_periodic($time, $callback, $args = null)
{
$this->jobs[] = array(
'scheduled_on' => $this->tick,
'after' => $time,
'cb' => $callback,
'args' => $args,
'is_periodic' => true,
'runs' => 0
);
- return sizeof($this->jobs);
+ return count($this->jobs);
}
// cancel a previously scheduled callback
public function cancel_fun_call($ref)
{
unset($this->jobs[$ref-1]);
}
}
diff --git a/core/jaxl_event.php b/core/jaxl_event.php
index 57742a3..91a3168 100644
--- a/core/jaxl_event.php
+++ b/core/jaxl_event.php
@@ -1,156 +1,156 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Following kind of events are possible:
* 1) hook i.e. if a callback for such an event is registered, calling function
* is responsible for the workflow from their on
* 2) filter i.e. calling function will manipulate passed arguments
* and modified arguments will be passed to next chain of filter
*
* As a rule of thumb, only 1 hook can be registered for an event, while more
* than 1 filter is allowed for an event hook and filter both cannot be applied
* on an event.
*
* @author abhinavsingh
*
*/
class JAXLEvent
{
protected $common = array();
public $reg = array();
public function __construct($common)
{
$this->common = $common;
}
public function __destruct()
{
}
/**
* Add callback on a event.
*
* Callback'd method must return `true` to be persistent, otherwise
* if returned `null` or `false`, callback will be removed automatically.
*
* @param string $ev
* @param callable $cb
* @param int $priority
* @return string Reference to be used while deleting callback.
*/
public function add($ev, $cb, $priority)
{
if (!isset($this->reg[$ev])) {
$this->reg[$ev] = array();
}
- $ref = sizeof($this->reg[$ev]);
+ $ref = count($this->reg[$ev]);
$this->reg[$ev][] = array($priority, $cb);
return $ev."-".$ref;
}
/**
* Emit event to notify registered callbacks.
*
* TODO: Is a pqueue required here for performance enhancement in case we
* have too many cbs on a specific event?
*
* @param string $ev
* @param array $data
* @return array
*/
public function emit($ev, array $data = array())
{
$data = array_merge($this->common, $data);
$cbs = array();
if (!isset($this->reg[$ev])) {
return $data;
}
foreach ($this->reg[$ev] as $cb) {
if (!isset($cbs[$cb[0]])) {
$cbs[$cb[0]] = array();
}
$cbs[$cb[0]][] = $cb[1];
}
foreach ($cbs as $pri => $cb) {
foreach ($cb as $c) {
$ret = call_user_func_array($c, $data);
// This line is for fixing situation where callback function doesn't return an array type.
// In such cases next call of call_user_func_array will report error since $data is not
// an array type as expected.
// Things will change in future, atleast put the callback inside a try/catch block.
// Here we only check if there was a return, if yes we update $data with return value.
// This is bad design, need more thoughts, should work as of now.
if ($ret) {
$data = $ret;
}
}
}
unset($cbs);
return $data;
}
/**
* Remove previous registered callback.
*
* @param string $ref
*/
public function del($ref)
{
$ref = explode("-", $ref);
unset($this->reg[$ref[0]][$ref[1]]);
}
/**
* @param string $ev
* @return bool
*/
public function exists($ev)
{
$ret = isset($this->reg[$ev]);
//_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists"));
return $ret;
}
}
diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php
index a6c5bcd..8d673ed 100644
--- a/core/jaxl_fsm.php
+++ b/core/jaxl_fsm.php
@@ -1,98 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
abstract class JAXLFsm
{
protected $state = null;
// abstract method
abstract public function handle_invalid_state($r);
public function __construct($state)
{
$this->state = $state;
}
// returned value from state callbacks can be:
// 1) array() <-- is_callable method
// 2) array([0] => 'new_state', [1] => 'return value for current callback') <-- is_not_callable method
// 3) array([0] => 'new_state')
// 4) 'new_state'
//
// for case 1) new state will be an array
// for other cases new state will be a string
public function __call($event, $args)
{
if ($this->state) {
// call state method
_debug(sprintf(
"calling state handler '%s' for incoming event '%s'",
is_array($this->state) ? $this->state[1] : $this->state,
$event
));
if (is_callable($this->state)) {
$call = $this->state;
} else {
$call = method_exists($this, $this->state) ? array(&$this, $this->state): $this->state;
}
$r = call_user_func($call, $event, $args);
// 4 cases of possible return value
if (is_callable($r)) {
$this->state = $r;
- } elseif (is_array($r) && sizeof($r) == 2) {
+ } elseif (is_array($r) && count($r) == 2) {
list($this->state, $ret) = $r;
- } elseif (is_array($r) && sizeof($r) == 1) {
+ } elseif (is_array($r) && count($r) == 1) {
$this->state = $r[0];
} elseif (is_string($r)) {
$this->state = $r;
} else {
$this->handle_invalid_state($r);
}
_debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'");
// return case
- if (!is_callable($r) && is_array($r) && sizeof($r) == 2) {
+ if (!is_callable($r) && is_array($r) && count($r) == 2) {
return $ret;
}
} else {
_debug("invalid state found, nothing called for event ".$event."");
}
}
}
diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php
index ebe367b..7f8d4cb 100644
--- a/core/jaxl_socket_client.php
+++ b/core/jaxl_socket_client.php
@@ -1,265 +1,265 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_loop.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLSocketClient
{
private $host = null;
private $port = null;
private $transport = null;
/** @var resource */
private $stream_context = null;
private $blocking = false;
public $fd = null;
public $errno = null;
public $errstr = null;
private $timeout = 10;
private $ibuffer = "";
private $obuffer = "";
private $compressed = false;
private $recv_bytes = 0;
private $send_bytes = 0;
/** @var callable */
private $recv_cb = null;
private $recv_chunk_size = 1024;
private $writing = false;
/**
* @param resource $stream_context Resource created with stream_context_create().
*/
public function __construct($stream_context = null)
{
$this->stream_context = $stream_context;
}
public function __destruct()
{
//_debug("cleaning up xmpp socket...");
$this->disconnect();
}
/**
* Emit on on_read_ready.
*
* @param callable $recv_cb
*/
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
/**
* @param string | resource $socket_path
*/
public function connect($socket_path)
{
if (gettype($socket_path) == "string") {
$path_parts = explode(":", $socket_path);
$this->transport = $path_parts[0];
$this->host = substr($path_parts[1], 2, strlen($path_parts[1]));
- if (sizeof($path_parts) == 3) {
+ if (count($path_parts) == 3) {
$this->port = $path_parts[2];
}
_info("trying ".$socket_path);
if ($this->stream_context) {
$this->fd = @stream_socket_client(
$socket_path,
$this->errno,
$this->errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
$this->stream_context
);
} else {
$this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout);
}
} elseif (is_resource($socket_path)) {
$this->fd = &$socket_path;
} else {
// Some error occurred.
}
if ($this->fd) {
_debug("connected to ".$socket_path."");
stream_set_blocking($this->fd, $this->blocking);
// watch descriptor for read/write events
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_read_ready')
));
return true;
} else {
_error(sprintf(
"unable to connect %s with error no: %s, error str: %s",
is_null($socket_path) ? 'NULL' : $socket_path,
is_null($this->errno) ? 'NULL' : $this->errno,
is_null($this->errstr) ? 'NULL' : $this->errstr
));
$this->disconnect();
return false;
}
}
public function disconnect()
{
JAXLLoop::unwatch($this->fd, array(
'read' => true,
'write' => true
));
if (is_resource($this->fd)) {
fclose($this->fd);
}
$this->fd = null;
}
public function compress()
{
$this->compressed = true;
//stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ);
//stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE);
}
public function crypt()
{
// set blocking (since tls negotiation fails if stream is non-blocking)
stream_set_blocking($this->fd, true);
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
}
}
}
// switch back to non-blocking
stream_set_blocking($this->fd, false);
return $ret;
}
/**
* @param string $data
*/
public function send($data)
{
$this->obuffer .= $data;
// add watch for write events
if ($this->writing) {
return;
}
JAXLLoop::watch($this->fd, array(
'write' => array(&$this, 'on_write_ready')
));
$this->writing = true;
}
public function on_read_ready($fd)
{
//_debug("on read ready called");
$raw = @fread($fd, $this->recv_chunk_size);
$bytes = strlen($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($fd);
if ($meta['eof'] === true) {
_warning("socket eof, disconnecting");
JAXLLoop::unwatch($fd, array(
'read' => true
));
$this->disconnect();
return;
}
}
$this->recv_bytes += $bytes;
$total = $this->ibuffer.$raw;
$this->ibuffer = "";
_debug("read ".$bytes."/".$this->recv_bytes." of data");
if ($bytes > 0) {
_debug($raw);
}
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $raw);
}
}
public function on_write_ready($fd)
{
//_debug("on write ready called");
$total = strlen($this->obuffer);
$bytes = @fwrite($fd, $this->obuffer);
$this->send_bytes += $bytes;
_debug("sent ".$bytes."/".$this->send_bytes." of data");
_debug(substr($this->obuffer, 0, $bytes));
$this->obuffer = substr($this->obuffer, $bytes, $total-$bytes);
// unwatch for write if obuffer is empty
if (strlen($this->obuffer) === 0) {
JAXLLoop::unwatch($fd, array(
'write' => true
));
$this->writing = false;
}
//_debug("current obuffer size: ".strlen($this->obuffer)."");
}
}
diff --git a/core/jaxl_util.php b/core/jaxl_util.php
index 4329e8f..73620fc 100644
--- a/core/jaxl_util.php
+++ b/core/jaxl_util.php
@@ -1,74 +1,74 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* @author abhinavsingh
*
*/
class JAXLUtil
{
public static function get_nonce($binary = true)
{
$nce = '';
mt_srand((double) microtime()*10000000);
for ($i = 0; $i<32; $i++) {
$nce .= chr(mt_rand(0, 255));
}
return $binary ? $nce : base64_encode($nce);
}
public static function get_dns_srv($domain)
{
$rec = dns_get_record("_xmpp-client._tcp.".$domain, DNS_SRV);
if (is_array($rec)) {
- if (sizeof($rec) == 0) {
+ if (count($rec) == 0) {
return array($domain, 5222);
}
- if (sizeof($rec) > 0) {
+ if (count($rec) > 0) {
return array($rec[0]['target'], $rec[0]['port']);
}
}
}
public static function pbkdf2($data, $secret, $iteration, $dkLen = 32, $algo = 'sha1')
{
return '';
}
}
diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php
index c800a1a..57c1cf4 100644
--- a/core/jaxl_xml.php
+++ b/core/jaxl_xml.php
@@ -1,282 +1,282 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/
* Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml
*
* @author abhinavsingh
*
*/
class JAXLXml
{
public $name;
public $ns = null;
public $attrs = array();
public $text = null;
/** @var JAXLXml[] */
public $childrens = array();
public $parent = null;
public $rover = null;
/**
* Accepts any of the following constructors:
*
* * JAXLXml($name, $ns, $attrs, $text)
* * JAXLXml($name, $ns, $attrs)
* * JAXLXml($name, $ns, $text)
* * JAXLXml($name, $attrs, $text)
* * JAXLXml($name, $attrs)
* * JAXLXml($name, $ns)
* * JAXLXml($name)
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
public function __construct()
{
$argv = func_get_args();
- $argc = sizeof($argv);
+ $argc = count($argv);
$this->name = $argv[0];
switch ($argc) {
case 4:
$this->ns = $argv[1];
$this->attrs = $argv[2];
$this->text = $argv[3];
break;
case 3:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
$this->text = $argv[2];
} else {
$this->ns = $argv[1];
if (is_array($argv[2])) {
$this->attrs = $argv[2];
} else {
$this->text = $argv[2];
}
}
break;
case 2:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
} else {
$this->ns = $argv[1];
}
break;
default:
break;
}
$this->rover = &$this;
}
public function __destruct()
{
}
/**
* @param array $attrs
* @return JAXLXml
*/
public function attrs(array $attrs)
{
$this->rover->attrs = array_merge($this->rover->attrs, $attrs);
return $this;
}
/**
* @param array $attrs
* @return bool
*/
public function match_attrs(array $attrs)
{
$matches = true;
foreach ($attrs as $k => $v) {
if ($this->attrs[$k] !== $v) {
$matches = false;
break;
}
}
return $matches;
}
/**
* Set or append text.
*
* @param string $text
* @param bool $append
* @return JAXLXml
*/
public function t($text, $append = false)
{
if (!$append) {
$this->rover->text = $text;
} else {
if ($this->rover->text === null) {
$this->rover->text = '';
}
$this->rover->text .= $text;
}
return $this;
}
/**
* Create child.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
* @return JAXLXml
*/
public function c($name, $ns = null, array $attrs = array(), $text = null)
{
$node = new JAXLXml($name, $ns, $attrs, $text);
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
/**
* Append child node.
*
* @param JAXLXml $node
* @return JAXLXml
*/
public function cnode($node)
{
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
public function up()
{
if ($this->rover->parent) {
$this->rover = &$this->rover->parent;
}
return $this;
}
public function top()
{
$this->rover = &$this;
return $this;
}
/**
* @param string $name
* @param string $ns
* @param array $attrs
* @return JAXLXml|bool
*/
public function exists($name, $ns = null, array $attrs = array())
{
foreach ($this->childrens as $child) {
if ($ns) {
if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) {
return $child;
}
} elseif ($child->name == $name && $child->match_attrs($attrs)) {
return $child;
}
}
return false;
}
/**
* Update child with name ``$name``.
*
* @param string $name
* @param string $ns
* @param array $attrs
* @param string $text
*/
public function update($name, $ns = null, array $attrs = array(), $text = null)
{
foreach ($this->childrens as $k => $child) {
if ($child->name == $name) {
$child->ns = $ns;
$child->attrs($attrs);
$child->text = $text;
$this->childrens[$k] = $child;
break;
}
}
}
/**
* @param string $parent_ns
* @return string
*/
public function to_string($parent_ns = null)
{
$xml = '';
$xml .= '<'.$this->name;
if ($this->ns && $this->ns != $parent_ns) {
$xml .= ' xmlns="'.$this->ns.'"';
}
foreach ($this->attrs as $k => $v) {
if (!is_null($v) && $v !== false) {
$xml .= ' '.$k.'="'.htmlspecialchars($v).'"';
}
}
$xml .= '>';
foreach ($this->childrens as $child) {
$xml .= $child->to_string($this->ns);
}
if ($this->text) {
$xml .= htmlspecialchars($this->text);
}
$xml .= '</'.$this->name.'>';
return $xml;
}
}
diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php
index 8ae9b05..d4dc97e 100644
--- a/core/jaxl_xml_stream.php
+++ b/core/jaxl_xml_stream.php
@@ -1,199 +1,199 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLXmlStream
{
private $delimiter = '\\';
private $ns;
private $parser;
private $stanza;
private $depth = -1;
private $start_cb;
private $stanza_cb;
private $end_cb;
public function __construct()
{
$this->init_parser();
}
private function init_parser()
{
$this->depth = -1;
$this->parser = xml_parser_create_ns("UTF-8", $this->delimiter);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
xml_set_character_data_handler($this->parser, array(&$this, "handle_character"));
xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag"));
}
public function __destruct()
{
//_debug("cleaning up xml parser...");
@xml_parser_free($this->parser);
}
public function reset_parser()
{
$this->parse_final(null);
@xml_parser_free($this->parser);
$this->parser = null;
$this->init_parser();
}
public function set_callback($start_cb, $end_cb, $stanza_cb)
{
$this->start_cb = $start_cb;
$this->end_cb = $end_cb;
$this->stanza_cb = $stanza_cb;
}
public function parse($str)
{
xml_parse($this->parser, $str, false);
}
public function parse_final($str)
{
xml_parse($this->parser, $str, true);
}
protected function handle_start_tag($parser, $name, array $attrs)
{
$name = $this->explode($name);
//echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL;
// replace ns with prefix
foreach ($attrs as $key => $v) {
$k = $this->explode($key);
// no ns specified
if ($k[0] == null) {
$attrs[$k[1]] = $v;
} elseif ($k[0] == NS_XML) {
// xml ns
unset($attrs[$key]);
$attrs['xml:'.$k[1]] = $v;
} else {
_error("==================> unhandled ns prefix on attribute");
// remove attribute else will cause error with bad stanza format
// report to developer if above error message is ever encountered
unset($attrs[$key]);
}
}
if ($this->depth <= 0) {
$this->depth = 0;
$this->ns = $name[1];
if ($this->start_cb) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
call_user_func($this->start_cb, $stanza);
}
} else {
if (!$this->stanza) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
$this->stanza = &$stanza;
} else {
$this->stanza->c($name[1], $name[0], $attrs);
}
}
++$this->depth;
}
protected function handle_end_tag($parser, $name)
{
$name = explode($this->delimiter, $name);
- $name = sizeof($name) == 1 ? array('', $name[0]) : $name;
+ $name = count($name) == 1 ? array('', $name[0]) : $name;
//echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL;
if ($this->depth == 1) {
if ($this->end_cb) {
$stanza = new JAXLXml($name[1], $this->ns);
call_user_func($this->end_cb, $stanza);
}
} elseif ($this->depth > 1) {
if ($this->stanza) {
$this->stanza->up();
}
if ($this->depth == 2) {
if ($this->stanza_cb) {
call_user_func($this->stanza_cb, $this->stanza);
$this->stanza = null;
}
}
}
--$this->depth;
}
protected function handle_character($parser, $data)
{
//echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL;
if ($this->stanza) {
$this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), true);
}
}
private function implode($data)
{
return implode($this->delimiter, $data);
}
private function explode($data)
{
$data = explode($this->delimiter, $data);
- $data = sizeof($data) == 1 ? array(null, $data[0]) : $data;
+ $data = count($data) == 1 ? array(null, $data[0]) : $data;
return $data;
}
}
diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php
index ef7d02f..166b2f9 100644
--- a/http/http_dispatcher.php
+++ b/http/http_dispatcher.php
@@ -1,135 +1,135 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
//
// (optionally) set an array of url dispatch rules
// each dispatch rule is defined by an array of size 4 like:
// array($callback, $pattern, $methods, $extra), where
// $callback the method which will be called if this rule matches
// $pattern regular expression to match request path
// $methods list of allowed methods for this rule
// pass boolean true to allow all http methods
// if omitted or an empty array() is passed (which actually doesnt make sense)
// by default 'GET' will be the method allowed on this rule
// $extra reserved for future (you can totally omit this as of now)
//
class HTTPDispatchRule
{
// match callback
public $cb = null;
// regexp to match on request path
public $pattern = null;
// methods to match upon
// add atleast 1 method for this rule to work
public $methods = null;
// other matching rules
public $extra = array();
public function __construct($cb, $pattern, array $methods = array('GET'), array $extra = array())
{
$this->cb = $cb;
$this->pattern = $pattern;
$this->methods = $methods;
$this->extra = $extra;
}
public function match($path, $method)
{
if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) {
if (in_array($method, $this->methods)) {
return $matches;
}
}
return false;
}
}
class HTTPDispatcher
{
protected $rules = array();
public function __construct()
{
$this->rules = array();
}
public function add_rule($rule)
{
- $s = sizeof($rule);
+ $s = count($rule);
if ($s > 4) {
_debug("invalid rule");
return;
}
// fill up defaults
if ($s == 3) {
$rule[] = array();
} elseif ($s == 2) {
$rule[] = array('GET');
$rule[] = array();
} else {
_debug("invalid rule");
return;
}
$this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]);
}
public function dispatch($request)
{
foreach ($this->rules as $rule) {
//_debug("matching $request->path with pattern $rule->pattern");
if (($matches = $rule->match($request->path, $request->method)) !== false) {
_debug("matching rule found, dispatching");
$params = array($request);
// TODO: a bad way to restrict on 'pk', fix me for generalization
if (isset($matches['pk'])) {
$params[] = $matches['pk'];
}
call_user_func_array($rule->cb, $params);
return true;
}
}
return false;
}
}
diff --git a/http/http_request.php b/http/http_request.php
index e3adc9e..f5f0171 100644
--- a/http/http_request.php
+++ b/http/http_request.php
@@ -1,512 +1,512 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/http/http_multipart.php';
//
// These methods are available only once
// $request FSM has reached 'headers_received' state
//
// following shortcuts are available
// on received $request object:
//
// $request->{status_code_name}($headers, $body)
// $request->{status_code_name}($body, $headers)
//
// $request->{status_code_name}($headers)
// $request->{status_code_name}($body)
//
// following specific methods are also available:
//
// $request->send_line($code)
// $request->send_header($key, $value)
// $request->send_headers($headers)
// $request->send_message($string)
//
// all the above methods can also be directly performed using:
//
// $request->send_response($code, $headers = array(), $body = null)
//
// Note: All the send_* methods do not manage connection close/keep-alive logic,
// it is upto you to do that, by default connection will usually be dropped
// on client disconnect if not handled by you.
//
class HTTPRequest extends JAXLFsm
{
// peer identifier
public $sock = null;
public $ip = null;
public $port = null;
// request line
public $version = null;
public $method = null;
public $resource = null;
public $path = null;
public $query = array();
// headers and body
public $headers = array();
public $body = null;
public $recvd_body_len = 0;
// is true if 'Expect: 100-Continue'
// request header has been seen
public $expect = false;
// set if there is Content-Type: multipart/form-data; boundary=...
// header already seen
public $multipart = null;
// callback for send/read/close actions on accepted sock
private $_send_cb = null;
private $_read_cb = null;
private $_close_cb = null;
private $shortcuts = array(
'ok' => 200, // 2xx
'redirect' => 302, 'not_modified' => 304, // 3xx
'not_found' => 404, 'bad_request' => 400, // 4xx
'internal_error' => 500, // 5xx
'recv_body' => true, 'close' => true // others
);
public function __construct($sock, $addr)
{
$this->sock = $sock;
$addr = explode(":", $addr);
$this->ip = $addr[0];
- if (sizeof($addr) == 2) {
+ if (count($addr) == 2) {
$this->port = $addr[1];
}
parent::__construct("setup");
}
public function __destruct()
{
_debug("http request going down in ".$this->state." state");
}
public function state()
{
return $this->state;
}
//
// abstract method implementation
//
public function handle_invalid_state($r)
{
_debug("handle invalid state called with");
var_dump($r);
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case 'set_sock_cb':
$this->_send_cb = $args[0];
$this->_read_cb = $args[1];
$this->_close_cb = $args[2];
return 'wait_for_request_line';
break;
default:
_warning("uncatched $event");
return 'setup';
}
}
public function wait_for_request_line($event, $args)
{
switch ($event) {
case 'line':
$this->_line($args[0], $args[1], $args[2]);
return 'wait_for_headers';
break;
default:
_warning("uncatched $event");
return 'wait_for_request_line';
}
}
public function wait_for_headers($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'maybe_headers_received';
default:
_warning("uncatched $event");
return 'wait_for_headers';
}
}
public function maybe_headers_received($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'headers_received';
break;
case 'body':
return $this->wait_for_body($event, $args);
break;
default:
_warning("uncatched $event");
return 'maybe_headers_received';
}
}
public function wait_for_body($event, $args)
{
switch ($event) {
case 'body':
$content_length = $this->headers['Content-Length'];
$rcvd = $args[0];
$rcvd_len = strlen($rcvd);
$this->recvd_body_len += $rcvd_len;
if ($this->body === null) {
$this->body = $rcvd;
} else {
$this->body .= $rcvd;
}
if ($this->multipart) {
// boundary start, content_disposition, form data, boundary start, ....., boundary end
// these define various states of a multipart/form-data
$form_data = explode("\r\n", $rcvd);
foreach ($form_data as $data) {
//_debug("passing $data to multipart fsm");
if (!$this->multipart->process($data)) {
_debug("multipart fsm returned false");
$this->_close();
return array('closed', false);
}
}
}
if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'set_header':
$content_length = $this->headers['Content-Length'];
$body = implode(":", $args);
$rcvd_len = strlen($body);
$this->recvd_body_len += $rcvd_len;
if (!$this->multipart->process($body)) {
_debug("multipart fsm returned false");
$this->_close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'empty_line':
$content_length = $this->headers['Content-Length'];
if (!$this->multipart->process('')) {
_debug("multipart fsm returned false");
$this->_close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
default:
_warning("uncatched $event");
return 'wait_for_body';
}
}
// headers and may be body received
public function headers_received($event, $args)
{
switch ($event) {
case 'empty_line':
return 'headers_received';
break;
default:
if (substr($event, 0, 5) == 'send_') {
$protected = '_'.$event;
if (method_exists($this, $protected)) {
call_user_func_array(array(&$this, $protected), $args);
return 'headers_received';
} else {
_debug("non-existant method $event called");
return 'headers_received';
}
} elseif (isset($this->shortcuts[$event])) {
return $this->handle_shortcut($event, $args);
} else {
_warning("uncatched $event ".$args[0]);
return 'headers_received';
}
}
}
public function closed($event, $args)
{
_warning("uncatched $event");
}
// sets input headers
// called internally for every header received
protected function set_header($k, $v)
{
$k = trim($k);
$v = ltrim($v);
// is expect header?
if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') {
$this->expect = true;
}
// is multipart form data?
if (strtolower($k) == 'content-type') {
$ctype = explode(';', $v);
- if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') {
+ if (count($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') {
$boundary = explode('=', trim($ctype[1]));
if (strtolower(trim($boundary[0])) == 'boundary') {
_debug("multipart with boundary $boundary[1] detected");
$this->multipart = new HTTPMultiPart(ltrim($boundary[1]));
}
}
}
$this->headers[trim($k)] = trim($v);
}
// shortcut handler
protected function handle_shortcut($event, $args)
{
_debug("executing shortcut '$event'");
switch ($event) {
// http status code shortcuts
case 'ok':
case 'redirect':
case 'not_modified':
case 'bad_request':
case 'not_found':
case 'internal_error':
list($headers, $body) = $this->parse_shortcut_args($args);
$code = $this->shortcuts[$event];
$this->_send_response($code, $headers, $body);
$this->_close();
return 'closed';
break;
// others
case 'recv_body':
// send expect header if required
if ($this->expect) {
$this->expect = false;
$this->_send_line(100);
}
// read data
$this->_read();
return 'wait_for_body';
break;
case 'close':
$this->_close();
return 'closed';
break;
}
}
private function parse_shortcut_args($args)
{
- if (sizeof($args) == 0) {
+ if (count($args) == 0) {
$body = null;
$headers = array();
}
- if (sizeof($args) == 1) {
+ if (count($args) == 1) {
// http headers or body only received
if (is_array($args[0])) {
// http headers only
$headers = $args[0];
$body = null;
} else {
// body only
$body = $args[0];
$headers = array();
}
- } elseif (sizeof($args) == 2) {
+ } elseif (count($args) == 2) {
// body and http headers both received
if (is_array($args[0])) {
// header first
$body = $args[1];
$headers = $args[0];
} else {
// body first
$body = $args[0];
$headers = $args[1];
}
}
return array($headers, $body);
}
//
// send methods
// available only on 'headers_received' state
//
protected function _send_line($code)
{
$raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF;
$this->_send($raw);
}
protected function _send_header($k, $v)
{
$raw = $k.': '.$v.HTTP_CRLF;
$this->_send($raw);
}
protected function _send_headers($code, $headers)
{
foreach ($headers as $k => $v) {
$this->_send_header($k, $v);
}
}
protected function _send_body($body)
{
$this->_send($body);
}
protected function _send_response($code, array $headers = array(), $body = null)
{
// send out response line
$this->_send_line($code);
// set content length of body exists and is not already set
if ($body && !isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($body);
}
// send out headers
$this->_send_headers($code, $headers);
// send body
// prefixed with an empty line
_debug("sending out HTTP_CRLF prefixed body");
if ($body) {
$this->_send_body(HTTP_CRLF.$body);
}
}
//
// internal methods
//
// initializes status line elements
private function _line($method, $resource, $version)
{
$this->method = $method;
$this->resource = $resource;
$resource = explode("?", $resource);
$this->path = $resource[0];
- if (sizeof($resource) == 2) {
+ if (count($resource) == 2) {
$query = $resource[1];
$query = explode("&", $query);
foreach ($query as $q) {
$q = explode("=", $q);
- if (sizeof($q) == 1) {
+ if (count($q) == 1) {
$q[1] = "";
}
$this->query[$q[0]] = $q[1];
}
}
$this->version = $version;
}
private function _send($raw)
{
call_user_func($this->_send_cb, $this->sock, $raw);
}
private function _read()
{
call_user_func($this->_read_cb, $this->sock);
}
private function _close()
{
call_user_func($this->_close_cb, $this->sock);
}
}
diff --git a/http/http_server.php b/http/http_server.php
index fb83db0..f0cf621 100644
--- a/http/http_server.php
+++ b/http/http_server.php
@@ -1,204 +1,204 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/http/http_dispatcher.php';
require_once JAXL_CWD.'/http/http_request.php';
// carriage return and line feed
define('HTTP_CRLF', "\r\n");
// 1xx informational
define('HTTP_100', "Continue");
define('HTTP_101', "Switching Protocols");
// 2xx success
define('HTTP_200', "OK");
// 3xx redirection
define('HTTP_301', 'Moved Permanently');
define('HTTP_304', 'Not Modified');
// 4xx client error
define('HTTP_400', 'Bad Request');
define('HTTP_403', 'Forbidden');
define('HTTP_404', 'Not Found');
define('HTTP_405', 'Method Not Allowed');
define('HTTP_499', 'Client Closed Request'); // Nginx
// 5xx server error
define('HTTP_500', 'Internal Server Error');
define('HTTP_503', 'Service Unavailable');
class HTTPServer
{
/** @var JAXLSocketServer */
private $server = null;
/** @var callable */
public $cb = null;
private $dispatcher = null;
private $requests = array();
public function __construct($port = 9699, $address = "127.0.0.1")
{
$path = 'tcp://'.$address.':'.$port;
$this->server = new JAXLSocketServer(
$path,
array(&$this, 'on_accept'),
array(&$this, 'on_request')
);
$this->dispatcher = new HTTPDispatcher();
}
public function __destruct()
{
$this->server = null;
}
public function dispatch($rules)
{
foreach ($rules as $rule) {
$this->dispatcher->add_rule($rule);
}
}
/**
* @param callable $cb
*/
public function start($cb = null)
{
$this->cb = $cb;
JAXLLoop::run();
}
public function on_accept($sock, $addr)
{
_debug("on_accept for client#$sock, addr:$addr");
// initialize new request obj
$request = new HTTPRequest($sock, $addr);
// setup sock cb
$request->set_sock_cb(
array(&$this->server, 'send'),
array(&$this->server, 'read'),
array(&$this->server, 'close')
);
// cache request object
$this->requests[$sock] = &$request;
// reactive client for further read
$this->server->read($sock);
}
public function on_request($sock, $raw)
{
_debug("on_request for client#$sock");
$request = $this->requests[$sock];
// 'wait_for_body' state is reached when ever
// application calls recv_body() method
// on received $request object
if ($request->state() == 'wait_for_body') {
$request->body($raw);
} else {
// break on crlf
$lines = explode(HTTP_CRLF, $raw);
// parse request line
if ($request->state() == 'wait_for_request_line') {
list($method, $resource, $version) = explode(" ", $lines[0]);
$request->line($method, $resource, $version);
unset($lines[0]);
_info($request->ip." ".$request->method." ".$request->resource." ".$request->version);
}
// parse headers
foreach ($lines as $line) {
$line_parts = explode(":", $line);
- if (sizeof($line_parts) > 1) {
+ if (count($line_parts) > 1) {
if (strlen($line_parts[0]) > 0) {
$k = $line_parts[0];
unset($line_parts[0]);
$v = implode(":", $line_parts);
$request->set_header($k, $v);
}
} elseif (strlen(trim($line_parts[0])) == 0) {
$request->empty_line();
} else {
// if exploded line array size is 1
// and there is something in $line_parts[0]
// must be request body
$request->body($line);
}
}
}
// if request has reached 'headers_received' state?
if ($request->state() == 'headers_received') {
// dispatch to any matching rule found
_debug("delegating to dispatcher for further routing");
$dispatched = $this->dispatcher->dispatch($request);
// if no dispatch rule matched call generic callback
if (!$dispatched && $this->cb) {
_debug("no dispatch rule matched, sending to generic callback");
call_user_func($this->cb, $request);
} elseif (!$dispatched) {
// elseif not dispatched and not generic callbacked
// send 404 not_found
// TODO: send 404 if no callback is registered for this request
_debug("dropping request since no matching dispatch rule or generic callback was specified");
$request->not_found('404 Not Found');
}
} else {
// if state is not 'headers_received'
// reactivate client socket for read event
$this->server->read($sock);
}
}
}
diff --git a/jaxl.php b/jaxl.php
index 45b1ed6..034b6c0 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,932 +1,932 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const version = '3.0.1';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
- while (sizeof($this->trans->chs) != 0) {
+ while (count($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
// signals callback handler
// not for public api consumption
public function signal_handler($sig)
{
$this->end_stream();
$this->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
if (isset($this->cfg['fb_access_token'])) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
/**
* @param string $reason
*/
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
diff --git a/jaxlctl b/jaxlctl
index e83ced8..ce5af32 100755
--- a/jaxlctl
+++ b/jaxlctl
@@ -1,200 +1,200 @@
#!/usr/bin/env php
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
error_reporting(E_ALL | E_STRICT);
date_default_timezone_set('UTC');
$params = $argv;
$exe = array_shift($params);
$command = array_shift($params);
require_once 'jaxl.php';
JAXLLogger::$level = JAXL_INFO;
// TODO: an abstract JAXLCtlCommand class
// with seperate class per command
// a mechanism to register new commands
class JAXLCtl
{
protected $ipc = null;
protected $buffer = '';
protected $buffer_cb = null;
protected $cli = null;
public $dots = "....... ";
protected $symbols = array();
public function __construct($command, $params)
{
global $exe;
if (method_exists($this, $command)) {
$r = call_user_func_array(array(&$this, $command), $params);
- if (sizeof($r) == 2) {
+ if (count($r) == 2) {
list($buffer_cb, $quit_cb) = $r;
$this->buffer_cb = $buffer_cb;
$this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb);
$this->run();
} else {
_colorize("oops! internal command error", JAXL_ERROR);
exit;
}
} else {
_colorize("error: invalid command '$command' received", JAXL_ERROR);
_colorize("type '$exe help' for list of available commands", JAXL_NOTICE);
exit;
}
}
public function run()
{
JAXLCli::prompt();
JAXLLoop::run();
}
public function on_terminal_input($raw)
{
$raw = trim($raw);
$last = substr($raw, -1, 1);
if ($last == ";") {
// dispatch to buffer callback
call_user_func($this->buffer_cb, $this->buffer.$raw);
$this->buffer = '';
} elseif ($last == '\\') {
$this->buffer .= substr($raw, 0, -1);
echo $this->dots;
} else {
// buffer command
$this->buffer .= $raw."; ";
echo $this->dots;
}
}
public static function print_help()
{
global $exe;
_colorize("Usage: $exe command [options...]\n", JAXL_INFO);
_colorize("Commands:", JAXL_NOTICE);
_colorize(" help This help text", JAXL_DEBUG);
_colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG);
_colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG);
echo "\n";
}
protected function help()
{
JAXLCtl::print_help();
exit;
}
//
// shell command
//
protected function shell()
{
return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit'));
}
private function _eval($raw, $symbols)
{
extract($symbols);
eval($raw);
$g = get_defined_vars();
unset($g['raw']);
unset($g['symbols']);
return $g;
}
public function on_shell_input($raw)
{
$this->symbols = $this->_eval($raw, $this->symbols);
JAXLCli::prompt();
}
public function on_shell_quit()
{
exit;
}
//
// debug command
//
protected function debug($sock_path)
{
$this->ipc = new JAXLSocketClient();
$this->ipc->set_callback(array(&$this, 'on_debug_response'));
$this->ipc->connect('unix://'.$sock_path);
return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit'));
}
public function on_debug_response($raw)
{
$ret = unserialize($raw);
print_r($ret);
echo "\n";
JAXLCli::prompt();
}
public function on_debug_input($raw)
{
$this->ipc->send($this->buffer.$raw);
}
public function on_debug_quit()
{
$this->ipc->disconnect();
exit;
}
}
// we atleast need a command argument
if ($argc < 2) {
JAXLCtl::print_help();
exit;
}
$ctl = new JAXLCtl($command, $params);
echo "done\n";
diff --git a/tests/test_jaxl_xml_stream.php b/tests/test_jaxl_xml_stream.php
index 170995c..1252843 100644
--- a/tests/test_jaxl_xml_stream.php
+++ b/tests/test_jaxl_xml_stream.php
@@ -1,77 +1,77 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
JAXL::dummy();
/**
*
* @author abhinavsingh
*
*/
class JAXLXmlStreamTest extends PHPUnit_Framework_TestCase
{
public function xml_start_cb($node)
{
$this->assertEquals('stream', $node->name);
$this->assertEquals(NS_XMPP, $node->ns);
}
public function xml_end_cb($node)
{
$this->assertEquals('stream', $node->name);
}
public function xml_stanza_cb($node)
{
$this->assertEquals('features', $node->name);
- $this->assertEquals(1, sizeof($node->childrens));
+ $this->assertEquals(1, count($node->childrens));
}
public function test_xml_stream_callbacks()
{
$xml = new JAXLXmlStream();
$xml->set_callback(array(&$this, "xml_start_cb"), array(&$this, "xml_end_cb"), array(&$this, "xml_stanza_cb"));
$xml->parse('<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">');
$xml->parse('<features>');
$xml->parse('<mechanisms>');
$xml->parse('</mechanisms>');
$xml->parse('</features>');
$xml->parse('</stream:stream>');
}
}
diff --git a/xmpp/xmpp_jid.php b/xmpp/xmpp_jid.php
index 087a0ff..a4b50d4 100644
--- a/xmpp/xmpp_jid.php
+++ b/xmpp/xmpp_jid.php
@@ -1,86 +1,86 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Xmpp Jid
*
* @author abhinavsingh
*
*/
class XMPPJid
{
public $node = null;
public $domain = null;
public $resource = null;
public $bare = null;
public function __construct($str)
{
$tmp = explode("@", $str, 2);
- if (sizeof($tmp) == 2) {
+ if (count($tmp) == 2) {
$this->node = $tmp[0];
$tmp = explode("/", $tmp[1], 2);
- if (sizeof($tmp) == 2) {
+ if (count($tmp) == 2) {
$this->domain = $tmp[0];
$this->resource = $tmp[1];
} else {
$this->domain = $tmp[0];
}
- } elseif (sizeof($tmp) == 1) {
+ } elseif (count($tmp) == 1) {
$this->domain = $tmp[0];
}
$this->bare = $this->node ? $this->node."@".$this->domain : $this->domain;
}
public function to_string()
{
$str = "";
if ($this->node) {
$str .= $this->node.'@'.$this->domain;
} elseif ($this->domain) {
$str .= $this->domain;
}
if ($this->resource) {
$str .= '/'.$this->resource;
}
return $str;
}
}
|
jaxl/JAXL | ec3ec68bfd760cd4013baa0429bfdbef06e2adad | More type hints | diff --git a/core/jaxl_event.php b/core/jaxl_event.php
index 8e8969d..57742a3 100644
--- a/core/jaxl_event.php
+++ b/core/jaxl_event.php
@@ -1,156 +1,156 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Following kind of events are possible:
* 1) hook i.e. if a callback for such an event is registered, calling function
* is responsible for the workflow from their on
* 2) filter i.e. calling function will manipulate passed arguments
* and modified arguments will be passed to next chain of filter
*
* As a rule of thumb, only 1 hook can be registered for an event, while more
* than 1 filter is allowed for an event hook and filter both cannot be applied
* on an event.
*
* @author abhinavsingh
*
*/
class JAXLEvent
{
protected $common = array();
public $reg = array();
public function __construct($common)
{
$this->common = $common;
}
public function __destruct()
{
}
/**
* Add callback on a event.
*
* Callback'd method must return `true` to be persistent, otherwise
* if returned `null` or `false`, callback will be removed automatically.
*
* @param string $ev
* @param callable $cb
* @param int $priority
* @return string Reference to be used while deleting callback.
*/
public function add($ev, $cb, $priority)
{
if (!isset($this->reg[$ev])) {
$this->reg[$ev] = array();
}
$ref = sizeof($this->reg[$ev]);
$this->reg[$ev][] = array($priority, $cb);
return $ev."-".$ref;
}
/**
* Emit event to notify registered callbacks.
*
* TODO: Is a pqueue required here for performance enhancement in case we
* have too many cbs on a specific event?
- *
+ *
* @param string $ev
* @param array $data
* @return array
*/
public function emit($ev, array $data = array())
{
$data = array_merge($this->common, $data);
$cbs = array();
if (!isset($this->reg[$ev])) {
return $data;
}
foreach ($this->reg[$ev] as $cb) {
if (!isset($cbs[$cb[0]])) {
$cbs[$cb[0]] = array();
}
$cbs[$cb[0]][] = $cb[1];
}
foreach ($cbs as $pri => $cb) {
foreach ($cb as $c) {
$ret = call_user_func_array($c, $data);
// This line is for fixing situation where callback function doesn't return an array type.
// In such cases next call of call_user_func_array will report error since $data is not
// an array type as expected.
// Things will change in future, atleast put the callback inside a try/catch block.
// Here we only check if there was a return, if yes we update $data with return value.
// This is bad design, need more thoughts, should work as of now.
if ($ret) {
$data = $ret;
}
}
}
unset($cbs);
return $data;
}
/**
* Remove previous registered callback.
*
* @param string $ref
*/
public function del($ref)
{
$ref = explode("-", $ref);
unset($this->reg[$ref[0]][$ref[1]]);
}
/**
* @param string $ev
* @return bool
*/
public function exists($ev)
{
$ret = isset($this->reg[$ev]);
//_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists"));
return $ret;
}
}
diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php
index 20c1358..447d358 100644
--- a/core/jaxl_loop.php
+++ b/core/jaxl_loop.php
@@ -1,168 +1,171 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_clock.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLLoop
{
+ /**
+ * @var JAXLClock
+ */
public static $clock = null;
private static $is_running = false;
private static $active_read_fds = 0;
private static $active_write_fds = 0;
private static $read_fds = array();
private static $read_cbs = array();
private static $write_fds = array();
private static $write_cbs = array();
private static $secs = 0;
private static $usecs = 30000;
private function __construct()
{
}
private function __clone()
{
}
public static function watch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
self::$read_fds[$fdid] = $fd;
self::$read_cbs[$fdid] = $opts['read'];
++self::$active_read_fds;
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
self::$write_fds[$fdid] = $fd;
self::$write_cbs[$fdid] = $opts['write'];
++self::$active_write_fds;
}
_debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function unwatch($fd, $opts)
{
if (isset($opts['read'])) {
$fdid = (int) $fd;
if (isset(self::$read_fds[$fdid])) {
unset(self::$read_fds[$fdid]);
unset(self::$read_cbs[$fdid]);
--self::$active_read_fds;
}
}
if (isset($opts['write'])) {
$fdid = (int) $fd;
if (isset(self::$write_fds[$fdid])) {
unset(self::$write_fds[$fdid]);
unset(self::$write_cbs[$fdid]);
--self::$active_write_fds;
}
}
_debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds);
}
public static function run()
{
if (!self::$is_running) {
self::$is_running = true;
self::$clock = new JAXLClock();
while ((self::$active_read_fds + self::$active_write_fds) > 0) {
self::select();
}
_debug("no more active fd's to select");
self::$is_running = false;
}
}
private static function select()
{
$read = self::$read_fds;
$write = self::$write_fds;
$except = null;
$changed = @stream_select($read, $write, $except, self::$secs, self::$usecs);
if ($changed === false) {
_error("error in the event loop, shutting down...");
/*foreach (self::$read_fds as $fd) {
if (is_resource($fd)) {
print_r(stream_get_meta_data($fd));
}
}*/
exit;
} elseif ($changed > 0) {
// read callback
foreach ($read as $r) {
$fdid = array_search($r, self::$read_fds);
if (isset(self::$read_fds[$fdid])) {
call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]);
}
}
// write callback
foreach ($write as $w) {
$fdid = array_search($w, self::$write_fds);
if (isset(self::$write_fds[$fdid])) {
call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]);
}
}
self::$clock->tick();
} elseif ($changed === 0) {
//_debug("nothing changed while selecting for read");
self::$clock->tick((self::$secs * pow(10, 6)) + self::$usecs);
}
}
}
diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php
index b3e1fbe..22b3c83 100644
--- a/core/jaxl_pipe.php
+++ b/core/jaxl_pipe.php
@@ -1,124 +1,136 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
/**
* bidirectional communication pipes for processes
*
* This is how this will be (when complete):
* $pipe = new JAXLPipe() will return an array of size 2
* $pipe[0] represents the read end of the pipe
* $pipe[1] represents the write end of the pipe
*
* Proposed functionality might even change (currently consider this as experimental)
*
* @author abhinavsingh
*
*/
class JAXLPipe
{
protected $perm = 0600;
+ /** @var callable */
protected $recv_cb = null;
protected $fd = null;
+ /** @var JAXLSocketClient */
protected $client = null;
+ /** @var string */
public $name = null;
+ /**
+ * @param string $name
+ * @param callable $read_cb TODO: Currently not used
+ */
public function __construct($name, $read_cb = null)
{
$pipes_folder = JAXL_CWD.'/.jaxl/pipes';
if (!is_dir($pipes_folder)) {
mkdir($pipes_folder);
}
$this->ev = new JAXLEvent();
$this->name = $name;
+ // TODO: If someone's need the read callback and extends the JAXLPipe
+ // to obtain it, one can't because this property is private.
$this->read_cb = $read_cb;
$pipe_path = $this->get_pipe_file_path();
if (!file_exists($pipe_path)) {
posix_mkfifo($pipe_path, $this->perm);
$this->fd = fopen($pipe_path, 'r+');
if (!$this->fd) {
_error("unable to open pipe");
} else {
_debug("pipe opened using path $pipe_path");
_notice("Usage: $ echo 'Hello World!' > $pipe_path");
$this->client = new JAXLSocketClient();
$this->client->connect($this->fd);
$this->client->set_callback(array(&$this, 'on_data'));
}
} else {
_error("pipe with name $name already exists");
}
}
public function __destruct()
{
if (is_resource($this->fd)) {
fclose($this->fd);
}
if (file_exists($this->get_pipe_file_path())) {
unlink($this->get_pipe_file_path());
}
_debug("unlinking pipe file");
}
public function get_pipe_file_path()
{
return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe';
}
+ /**
+ * @param callable $recv_cb
+ */
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function on_data($data)
{
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $data);
}
}
}
diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php
index 1468551..de0fd15 100644
--- a/core/jaxl_sock5.php
+++ b/core/jaxl_sock5.php
@@ -1,131 +1,142 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class JAXLSock5
{
-
+ /** @var JAXLSocketClient */
private $client = null;
+ /** @var string */
protected $transport = null;
+ /** @var string */
protected $ip = null;
+ /** @var string|int */
protected $port = null;
+ /**
+ * @param string $transport
+ */
public function __construct($transport = 'tcp')
{
$this->transport = $transport;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function __destruct()
{
}
+ /**
+ * @param string $ip
+ * @param int $port
+ * @return bool
+ */
public function connect($ip, $port = 1080)
{
$this->ip = $ip;
$this->port = $port;
$sock_path = $this->_sock_path();
if ($this->client->connect($sock_path)) {
_debug("established connection to $sock_path");
return true;
} else {
_error("unable to connect $sock_path");
return false;
}
}
//
// Three phases of SOCK5
//
// Negotiation pkt consists of 3 part:
// 0x05 => Sock protocol version
// 0x01 => Number of method identifier octet
//
// Following auth methods are defined:
// 0x00 => No authentication required
// 0x01 => GSSAPI
// 0x02 => USERNAME/PASSWORD
// 0x03 to 0x7F => IANA ASSIGNED
// 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS
// 0xFF => NO ACCEPTABLE METHODS
public function negotiate()
{
$pkt = pack("C3", 0x05, 0x01, 0x00);
$this->client->send($pkt);
// enter sub-negotiation state
}
public function relay_request()
{
// enter wait for reply state
}
public function send_data()
{
}
//
// Socket client callback
//
public function on_response($raw)
{
_debug($raw);
}
//
// Private
//
protected function _sock_path()
{
return $this->transport.'://'.$this->ip.':'.$this->port;
}
}
diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php
index bba616a..ebe367b 100644
--- a/core/jaxl_socket_client.php
+++ b/core/jaxl_socket_client.php
@@ -1,256 +1,265 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_loop.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLSocketClient
{
private $host = null;
private $port = null;
private $transport = null;
/** @var resource */
private $stream_context = null;
private $blocking = false;
public $fd = null;
public $errno = null;
public $errstr = null;
private $timeout = 10;
private $ibuffer = "";
private $obuffer = "";
private $compressed = false;
private $recv_bytes = 0;
private $send_bytes = 0;
+ /** @var callable */
private $recv_cb = null;
private $recv_chunk_size = 1024;
private $writing = false;
/**
* @param resource $stream_context Resource created with stream_context_create().
*/
public function __construct($stream_context = null)
{
$this->stream_context = $stream_context;
}
public function __destruct()
{
//_debug("cleaning up xmpp socket...");
$this->disconnect();
}
+ /**
+ * Emit on on_read_ready.
+ *
+ * @param callable $recv_cb
+ */
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
/**
* @param string | resource $socket_path
*/
public function connect($socket_path)
{
if (gettype($socket_path) == "string") {
$path_parts = explode(":", $socket_path);
$this->transport = $path_parts[0];
$this->host = substr($path_parts[1], 2, strlen($path_parts[1]));
if (sizeof($path_parts) == 3) {
$this->port = $path_parts[2];
}
_info("trying ".$socket_path);
if ($this->stream_context) {
$this->fd = @stream_socket_client(
$socket_path,
$this->errno,
$this->errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
$this->stream_context
);
} else {
$this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout);
}
} elseif (is_resource($socket_path)) {
$this->fd = &$socket_path;
} else {
// Some error occurred.
}
if ($this->fd) {
_debug("connected to ".$socket_path."");
stream_set_blocking($this->fd, $this->blocking);
// watch descriptor for read/write events
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_read_ready')
));
return true;
} else {
_error(sprintf(
"unable to connect %s with error no: %s, error str: %s",
is_null($socket_path) ? 'NULL' : $socket_path,
is_null($this->errno) ? 'NULL' : $this->errno,
is_null($this->errstr) ? 'NULL' : $this->errstr
));
$this->disconnect();
return false;
}
}
public function disconnect()
{
JAXLLoop::unwatch($this->fd, array(
'read' => true,
'write' => true
));
if (is_resource($this->fd)) {
fclose($this->fd);
}
$this->fd = null;
}
public function compress()
{
$this->compressed = true;
//stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ);
//stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE);
}
public function crypt()
{
// set blocking (since tls negotiation fails if stream is non-blocking)
stream_set_blocking($this->fd, true);
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
}
}
}
// switch back to non-blocking
stream_set_blocking($this->fd, false);
return $ret;
}
+ /**
+ * @param string $data
+ */
public function send($data)
{
$this->obuffer .= $data;
// add watch for write events
if ($this->writing) {
return;
}
JAXLLoop::watch($this->fd, array(
'write' => array(&$this, 'on_write_ready')
));
$this->writing = true;
}
public function on_read_ready($fd)
{
//_debug("on read ready called");
$raw = @fread($fd, $this->recv_chunk_size);
$bytes = strlen($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($fd);
if ($meta['eof'] === true) {
_warning("socket eof, disconnecting");
JAXLLoop::unwatch($fd, array(
'read' => true
));
$this->disconnect();
return;
}
}
$this->recv_bytes += $bytes;
$total = $this->ibuffer.$raw;
$this->ibuffer = "";
_debug("read ".$bytes."/".$this->recv_bytes." of data");
if ($bytes > 0) {
_debug($raw);
}
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $raw);
}
}
public function on_write_ready($fd)
{
//_debug("on write ready called");
$total = strlen($this->obuffer);
$bytes = @fwrite($fd, $this->obuffer);
$this->send_bytes += $bytes;
_debug("sent ".$bytes."/".$this->send_bytes." of data");
_debug(substr($this->obuffer, 0, $bytes));
$this->obuffer = substr($this->obuffer, $bytes, $total-$bytes);
// unwatch for write if obuffer is empty
if (strlen($this->obuffer) === 0) {
JAXLLoop::unwatch($fd, array(
'write' => true
));
$this->writing = false;
}
//_debug("current obuffer size: ".strlen($this->obuffer)."");
}
}
diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php
index 2bb4154..f5c70bd 100644
--- a/core/jaxl_socket_server.php
+++ b/core/jaxl_socket_server.php
@@ -1,274 +1,278 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_loop.php';
class JAXLSocketServer
{
public $fd = null;
private $clients = array();
private $recv_chunk_size = 1024;
private $send_chunk_size = 8092;
private $accept_cb = null;
private $request_cb = null;
private $blocking = false;
private $backlog = 200;
public function __construct($path, $accept_cb, $request_cb)
{
$this->accept_cb = $accept_cb;
$this->request_cb = $request_cb;
$ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog)));
$this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx);
if ($this->fd !== false) {
if (@stream_set_blocking($this->fd, $this->blocking)) {
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_server_accept_ready')
));
_info("socket ready to accept on path ".$path);
} else {
_error("unable to set non block flag");
}
} else {
_error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr);
}
}
public function __destruct()
{
_info("shutting down socket server");
}
public function read($client_id)
{
//_debug("reactivating read on client sock");
$this->add_read_cb($client_id);
}
+ /**
+ * @param int $client_id
+ * @param string $data
+ */
public function send($client_id, $data)
{
$this->clients[$client_id]['obuffer'] .= $data;
$this->add_write_cb($client_id);
}
public function close($client_id)
{
$this->clients[$client_id]['close'] = true;
$this->add_write_cb($client_id);
}
public function on_server_accept_ready($server)
{
//_debug("got server accept");
$client = @stream_socket_accept($server, 0, $addr);
if (!$client) {
_error("unable to accept new client conn");
return;
}
if (@stream_set_blocking($client, $this->blocking)) {
$client_id = (int) $client;
$this->clients[$client_id] = array(
'fd' => $client,
'ibuffer' => '',
'obuffer' => '',
'addr' => trim($addr),
'close' => false,
'closed' => false,
'reading' => false,
'writing' => false
);
_debug("accepted connection from client#".$client_id.", addr:".$addr);
// if accept callback is registered
// callback and let user land take further control of what to do
if ($this->accept_cb) {
call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']);
} else {
// if no accept callback is registered
// close the accepted connection
if (is_resource($client)) {
fclose($client);
}
$this->clients[$client_id]['closed'] = true;
unset($this->clients[$client_id]);
}
} else {
_error("unable to set non block flag");
}
}
public function on_client_read_ready($client)
{
// deactive socket for read
$client_id = (int) $client;
//_debug("client#$client_id is read ready");
$this->del_read_cb($client_id);
$raw = fread($client, $this->recv_chunk_size);
$bytes = strlen($raw);
_debug("recv $bytes bytes from client#$client_id");
//_debug($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($client);
if ($meta['eof'] === true) {
_debug("socket eof client#".$client_id.", closing");
$this->del_read_cb($client_id);
if (is_resource($client)) {
fclose($client);
}
unset($this->clients[$client_id]);
return;
}
}
$total = $this->clients[$client_id]['ibuffer'] . $raw;
if ($this->request_cb) {
call_user_func($this->request_cb, $client_id, $total);
}
$this->clients[$client_id]['ibuffer'] = '';
}
public function on_client_write_ready($client)
{
$client_id = (int) $client;
_debug("client#$client_id is write ready");
try {
// send in chunks
$total = $this->clients[$client_id]['obuffer'];
$written = @fwrite($client, substr($total, 0, $this->send_chunk_size));
if ($written === false) {
// fwrite failed
_warning("====> fwrite failed");
$this->clients[$client_id]['obuffer'] = $total;
} elseif ($written == strlen($total) || $written == $this->send_chunk_size) {
// full chunk written
//_debug("full chunk written");
$this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size);
} else {
// partial chunk written
//_debug("partial chunk $written written");
$this->clients[$client_id]['obuffer'] = substr($total, $written);
}
// if no more stuff to write, remove write handler
if (strlen($this->clients[$client_id]['obuffer']) === 0) {
$this->del_write_cb($client_id);
// if scheduled for close and not closed do it and clean up
if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) {
if (is_resource($client)) {
fclose($client);
}
$this->clients[$client_id]['closed'] = true;
unset($this->clients[$client_id]);
_debug("closed client#".$client_id);
}
}
} catch (JAXLException $e) {
_debug("====> got fwrite exception");
}
}
//
// client sock event register utils
//
protected function add_read_cb($client_id)
{
if ($this->clients[$client_id]['reading']) {
return;
}
JAXLLoop::watch($this->clients[$client_id]['fd'], array(
'read' => array(&$this, 'on_client_read_ready')
));
$this->clients[$client_id]['reading'] = true;
}
protected function add_write_cb($client_id)
{
if ($this->clients[$client_id]['writing']) {
return;
}
JAXLLoop::watch($this->clients[$client_id]['fd'], array(
'write' => array(&$this, 'on_client_write_ready')
));
$this->clients[$client_id]['writing'] = true;
}
protected function del_read_cb($client_id)
{
if (!$this->clients[$client_id]['reading']) {
return;
}
JAXLLoop::unwatch($this->clients[$client_id]['fd'], array(
'read' => true
));
$this->clients[$client_id]['reading'] = false;
}
protected function del_write_cb($client_id)
{
if (!$this->clients[$client_id]['writing']) {
return;
}
JAXLLoop::unwatch($this->clients[$client_id]['fd'], array(
'write' => true
));
$this->clients[$client_id]['writing'] = false;
}
}
diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php
index e8fc7b9..c800a1a 100644
--- a/core/jaxl_xml.php
+++ b/core/jaxl_xml.php
@@ -1,224 +1,282 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/
* Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml
*
* @author abhinavsingh
*
*/
class JAXLXml
{
public $name;
public $ns = null;
public $attrs = array();
public $text = null;
/** @var JAXLXml[] */
public $childrens = array();
public $parent = null;
public $rover = null;
+ /**
+ * Accepts any of the following constructors:
+ *
+ * * JAXLXml($name, $ns, $attrs, $text)
+ * * JAXLXml($name, $ns, $attrs)
+ * * JAXLXml($name, $ns, $text)
+ * * JAXLXml($name, $attrs, $text)
+ * * JAXLXml($name, $attrs)
+ * * JAXLXml($name, $ns)
+ * * JAXLXml($name)
+ *
+ * @param string $name
+ * @param string $ns
+ * @param array $attrs
+ * @param string $text
+ */
public function __construct()
{
$argv = func_get_args();
$argc = sizeof($argv);
$this->name = $argv[0];
switch ($argc) {
case 4:
$this->ns = $argv[1];
$this->attrs = $argv[2];
$this->text = $argv[3];
break;
case 3:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
$this->text = $argv[2];
} else {
$this->ns = $argv[1];
if (is_array($argv[2])) {
$this->attrs = $argv[2];
} else {
$this->text = $argv[2];
}
}
break;
case 2:
if (is_array($argv[1])) {
$this->attrs = $argv[1];
} else {
$this->ns = $argv[1];
}
break;
default:
break;
}
$this->rover = &$this;
}
public function __destruct()
{
}
- public function attrs($attrs)
+ /**
+ * @param array $attrs
+ * @return JAXLXml
+ */
+ public function attrs(array $attrs)
{
$this->rover->attrs = array_merge($this->rover->attrs, $attrs);
return $this;
}
- public function match_attrs($attrs)
+ /**
+ * @param array $attrs
+ * @return bool
+ */
+ public function match_attrs(array $attrs)
{
$matches = true;
foreach ($attrs as $k => $v) {
if ($this->attrs[$k] !== $v) {
$matches = false;
break;
}
}
return $matches;
}
+ /**
+ * Set or append text.
+ *
+ * @param string $text
+ * @param bool $append
+ * @return JAXLXml
+ */
public function t($text, $append = false)
{
if (!$append) {
$this->rover->text = $text;
} else {
if ($this->rover->text === null) {
$this->rover->text = '';
}
$this->rover->text .= $text;
}
return $this;
}
- public function c($name, $ns = null, $attrs = array(), $text = null)
+ /**
+ * Create child.
+ *
+ * @param string $name
+ * @param string $ns
+ * @param array $attrs
+ * @param string $text
+ * @return JAXLXml
+ */
+ public function c($name, $ns = null, array $attrs = array(), $text = null)
{
$node = new JAXLXml($name, $ns, $attrs, $text);
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
+ /**
+ * Append child node.
+ *
+ * @param JAXLXml $node
+ * @return JAXLXml
+ */
public function cnode($node)
{
$node->parent = &$this->rover;
$this->rover->childrens[] = &$node;
$this->rover = &$node;
return $this;
}
public function up()
{
if ($this->rover->parent) {
$this->rover = &$this->rover->parent;
}
return $this;
}
public function top()
{
$this->rover = &$this;
return $this;
}
/**
* @param string $name
* @param string $ns
* @param array $attrs
* @return JAXLXml|bool
*/
- public function exists($name, $ns = null, $attrs = array())
+ public function exists($name, $ns = null, array $attrs = array())
{
foreach ($this->childrens as $child) {
if ($ns) {
if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) {
return $child;
}
} elseif ($child->name == $name && $child->match_attrs($attrs)) {
return $child;
}
}
return false;
}
- public function update($name, $ns = null, $attrs = array(), $text = null)
+ /**
+ * Update child with name ``$name``.
+ *
+ * @param string $name
+ * @param string $ns
+ * @param array $attrs
+ * @param string $text
+ */
+ public function update($name, $ns = null, array $attrs = array(), $text = null)
{
foreach ($this->childrens as $k => $child) {
if ($child->name == $name) {
$child->ns = $ns;
$child->attrs($attrs);
$child->text = $text;
$this->childrens[$k] = $child;
break;
}
}
}
+ /**
+ * @param string $parent_ns
+ * @return string
+ */
public function to_string($parent_ns = null)
{
$xml = '';
$xml .= '<'.$this->name;
if ($this->ns && $this->ns != $parent_ns) {
$xml .= ' xmlns="'.$this->ns.'"';
}
foreach ($this->attrs as $k => $v) {
if (!is_null($v) && $v !== false) {
$xml .= ' '.$k.'="'.htmlspecialchars($v).'"';
}
}
$xml .= '>';
foreach ($this->childrens as $child) {
$xml .= $child->to_string($this->ns);
}
if ($this->text) {
$xml .= htmlspecialchars($this->text);
}
$xml .= '</'.$this->name.'>';
return $xml;
}
}
diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php
index ea93e2d..8ae9b05 100644
--- a/core/jaxl_xml_stream.php
+++ b/core/jaxl_xml_stream.php
@@ -1,199 +1,199 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLXmlStream
{
private $delimiter = '\\';
private $ns;
private $parser;
private $stanza;
private $depth = -1;
private $start_cb;
private $stanza_cb;
private $end_cb;
public function __construct()
{
$this->init_parser();
}
private function init_parser()
{
$this->depth = -1;
$this->parser = xml_parser_create_ns("UTF-8", $this->delimiter);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
xml_set_character_data_handler($this->parser, array(&$this, "handle_character"));
xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag"));
}
public function __destruct()
{
//_debug("cleaning up xml parser...");
@xml_parser_free($this->parser);
}
public function reset_parser()
{
$this->parse_final(null);
@xml_parser_free($this->parser);
$this->parser = null;
$this->init_parser();
}
public function set_callback($start_cb, $end_cb, $stanza_cb)
{
$this->start_cb = $start_cb;
$this->end_cb = $end_cb;
$this->stanza_cb = $stanza_cb;
}
public function parse($str)
{
xml_parse($this->parser, $str, false);
}
public function parse_final($str)
{
xml_parse($this->parser, $str, true);
}
- protected function handle_start_tag($parser, $name, $attrs)
+ protected function handle_start_tag($parser, $name, array $attrs)
{
$name = $this->explode($name);
//echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL;
// replace ns with prefix
foreach ($attrs as $key => $v) {
$k = $this->explode($key);
// no ns specified
if ($k[0] == null) {
$attrs[$k[1]] = $v;
} elseif ($k[0] == NS_XML) {
// xml ns
unset($attrs[$key]);
$attrs['xml:'.$k[1]] = $v;
} else {
_error("==================> unhandled ns prefix on attribute");
// remove attribute else will cause error with bad stanza format
// report to developer if above error message is ever encountered
unset($attrs[$key]);
}
}
if ($this->depth <= 0) {
$this->depth = 0;
$this->ns = $name[1];
if ($this->start_cb) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
call_user_func($this->start_cb, $stanza);
}
} else {
if (!$this->stanza) {
$stanza = new JAXLXml($name[1], $name[0], $attrs);
$this->stanza = &$stanza;
} else {
$this->stanza->c($name[1], $name[0], $attrs);
}
}
++$this->depth;
}
protected function handle_end_tag($parser, $name)
{
$name = explode($this->delimiter, $name);
$name = sizeof($name) == 1 ? array('', $name[0]) : $name;
//echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL;
if ($this->depth == 1) {
if ($this->end_cb) {
$stanza = new JAXLXml($name[1], $this->ns);
call_user_func($this->end_cb, $stanza);
}
} elseif ($this->depth > 1) {
if ($this->stanza) {
$this->stanza->up();
}
if ($this->depth == 2) {
if ($this->stanza_cb) {
call_user_func($this->stanza_cb, $this->stanza);
$this->stanza = null;
}
}
}
--$this->depth;
}
protected function handle_character($parser, $data)
{
//echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL;
if ($this->stanza) {
$this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), true);
}
}
private function implode($data)
{
return implode($this->delimiter, $data);
}
private function explode($data)
{
$data = explode($this->delimiter, $data);
$data = sizeof($data) == 1 ? array(null, $data[0]) : $data;
return $data;
}
}
diff --git a/http/http_client.php b/http/http_client.php
index 1506799..f4dcdae 100644
--- a/http/http_client.php
+++ b/http/http_client.php
@@ -1,150 +1,157 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class HTTPClient
{
+ /** @var string */
private $url = null;
private $parts = array();
private $headers = array();
private $data = null;
public $method = null;
+ /** @var JAXLSocketClient */
private $client = null;
- public function __construct($url, $headers = array(), $data = null)
+ /**
+ * @param string $url
+ * @param array $headers TODO: Currently not used.
+ * @param unknown $data TODO: Currently not used.
+ */
+ public function __construct($url, array $headers = array(), $data = null)
{
$this->url = $url;
$this->headers = $headers;
$this->data = $data;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function start($method = 'GET')
{
$this->method = $method;
$this->parts = parse_url($this->url);
$transport = $this->_transport();
$ip = $this->_ip();
$port = $this->_port();
$socket_path = $transport.'://'.$ip.':'.$port;
if ($this->client->connect($socket_path)) {
_debug("connection to $this->url established");
// send request data
$this->send_request();
// start main loop
JAXLLoop::run();
} else {
_debug("unable to open $this->url");
}
}
public function on_response($raw)
{
_info("got http response");
}
protected function send_request()
{
$this->client->send($this->_line()."\r\n");
$this->client->send($this->_ua()."\r\n");
$this->client->send($this->_host()."\r\n");
$this->client->send("\r\n");
}
//
// private methods on uri parts
//
private function _line()
{
return $this->method.' '.$this->_uri().' HTTP/1.1';
}
private function _ua()
{
return 'User-Agent: jaxl_http_client/3.x';
}
private function _host()
{
return 'Host: '.$this->parts['host'].':'.$this->_port();
}
private function _transport()
{
return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl');
}
private function _ip()
{
return gethostbyname($this->parts['host']);
}
private function _port()
{
return isset($this->parts['port']) ? $this->parts['port'] : 80;
}
private function _uri()
{
$uri = $this->parts['path'];
if (isset($this->parts['query'])) {
$uri .= '?'.$this->parts['query'];
}
if (isset($this->parts['fragment'])) {
$uri .= '#'.$this->parts['fragment'];
}
return $uri;
}
}
diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php
index 368327e..ef7d02f 100644
--- a/http/http_dispatcher.php
+++ b/http/http_dispatcher.php
@@ -1,135 +1,135 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
//
// (optionally) set an array of url dispatch rules
// each dispatch rule is defined by an array of size 4 like:
// array($callback, $pattern, $methods, $extra), where
// $callback the method which will be called if this rule matches
// $pattern regular expression to match request path
// $methods list of allowed methods for this rule
// pass boolean true to allow all http methods
// if omitted or an empty array() is passed (which actually doesnt make sense)
// by default 'GET' will be the method allowed on this rule
// $extra reserved for future (you can totally omit this as of now)
//
class HTTPDispatchRule
{
// match callback
public $cb = null;
// regexp to match on request path
public $pattern = null;
// methods to match upon
// add atleast 1 method for this rule to work
public $methods = null;
// other matching rules
public $extra = array();
- public function __construct($cb, $pattern, $methods = array('GET'), $extra = array())
+ public function __construct($cb, $pattern, array $methods = array('GET'), array $extra = array())
{
$this->cb = $cb;
$this->pattern = $pattern;
$this->methods = $methods;
$this->extra = $extra;
}
public function match($path, $method)
{
if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) {
if (in_array($method, $this->methods)) {
return $matches;
}
}
return false;
}
}
class HTTPDispatcher
{
protected $rules = array();
public function __construct()
{
$this->rules = array();
}
public function add_rule($rule)
{
$s = sizeof($rule);
if ($s > 4) {
_debug("invalid rule");
return;
}
// fill up defaults
if ($s == 3) {
$rule[] = array();
} elseif ($s == 2) {
$rule[] = array('GET');
$rule[] = array();
} else {
_debug("invalid rule");
return;
}
$this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]);
}
public function dispatch($request)
{
foreach ($this->rules as $rule) {
//_debug("matching $request->path with pattern $rule->pattern");
if (($matches = $rule->match($request->path, $request->method)) !== false) {
_debug("matching rule found, dispatching");
$params = array($request);
// TODO: a bad way to restrict on 'pk', fix me for generalization
if (isset($matches['pk'])) {
$params[] = $matches['pk'];
}
call_user_func_array($rule->cb, $params);
return true;
}
}
return false;
}
}
diff --git a/http/http_request.php b/http/http_request.php
index f4a2ee4..e3adc9e 100644
--- a/http/http_request.php
+++ b/http/http_request.php
@@ -1,512 +1,512 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/http/http_multipart.php';
//
// These methods are available only once
// $request FSM has reached 'headers_received' state
//
// following shortcuts are available
// on received $request object:
//
// $request->{status_code_name}($headers, $body)
// $request->{status_code_name}($body, $headers)
//
// $request->{status_code_name}($headers)
// $request->{status_code_name}($body)
//
// following specific methods are also available:
//
// $request->send_line($code)
// $request->send_header($key, $value)
// $request->send_headers($headers)
// $request->send_message($string)
//
// all the above methods can also be directly performed using:
//
// $request->send_response($code, $headers = array(), $body = null)
//
// Note: All the send_* methods do not manage connection close/keep-alive logic,
// it is upto you to do that, by default connection will usually be dropped
// on client disconnect if not handled by you.
//
class HTTPRequest extends JAXLFsm
{
// peer identifier
public $sock = null;
public $ip = null;
public $port = null;
// request line
public $version = null;
public $method = null;
public $resource = null;
public $path = null;
public $query = array();
// headers and body
public $headers = array();
public $body = null;
public $recvd_body_len = 0;
// is true if 'Expect: 100-Continue'
// request header has been seen
public $expect = false;
// set if there is Content-Type: multipart/form-data; boundary=...
// header already seen
public $multipart = null;
// callback for send/read/close actions on accepted sock
private $_send_cb = null;
private $_read_cb = null;
private $_close_cb = null;
private $shortcuts = array(
'ok' => 200, // 2xx
'redirect' => 302, 'not_modified' => 304, // 3xx
'not_found' => 404, 'bad_request' => 400, // 4xx
'internal_error' => 500, // 5xx
'recv_body' => true, 'close' => true // others
);
public function __construct($sock, $addr)
{
$this->sock = $sock;
$addr = explode(":", $addr);
$this->ip = $addr[0];
if (sizeof($addr) == 2) {
$this->port = $addr[1];
}
parent::__construct("setup");
}
public function __destruct()
{
_debug("http request going down in ".$this->state." state");
}
public function state()
{
return $this->state;
}
//
// abstract method implementation
//
public function handle_invalid_state($r)
{
_debug("handle invalid state called with");
var_dump($r);
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case 'set_sock_cb':
$this->_send_cb = $args[0];
$this->_read_cb = $args[1];
$this->_close_cb = $args[2];
return 'wait_for_request_line';
break;
default:
_warning("uncatched $event");
return 'setup';
}
}
public function wait_for_request_line($event, $args)
{
switch ($event) {
case 'line':
$this->_line($args[0], $args[1], $args[2]);
return 'wait_for_headers';
break;
default:
_warning("uncatched $event");
return 'wait_for_request_line';
}
}
public function wait_for_headers($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'maybe_headers_received';
default:
_warning("uncatched $event");
return 'wait_for_headers';
}
}
public function maybe_headers_received($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'headers_received';
break;
case 'body':
return $this->wait_for_body($event, $args);
break;
default:
_warning("uncatched $event");
return 'maybe_headers_received';
}
}
public function wait_for_body($event, $args)
{
switch ($event) {
case 'body':
$content_length = $this->headers['Content-Length'];
$rcvd = $args[0];
$rcvd_len = strlen($rcvd);
$this->recvd_body_len += $rcvd_len;
if ($this->body === null) {
$this->body = $rcvd;
} else {
$this->body .= $rcvd;
}
if ($this->multipart) {
// boundary start, content_disposition, form data, boundary start, ....., boundary end
// these define various states of a multipart/form-data
$form_data = explode("\r\n", $rcvd);
foreach ($form_data as $data) {
//_debug("passing $data to multipart fsm");
if (!$this->multipart->process($data)) {
_debug("multipart fsm returned false");
$this->_close();
return array('closed', false);
}
}
}
if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'set_header':
$content_length = $this->headers['Content-Length'];
$body = implode(":", $args);
$rcvd_len = strlen($body);
$this->recvd_body_len += $rcvd_len;
if (!$this->multipart->process($body)) {
_debug("multipart fsm returned false");
$this->_close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'empty_line':
$content_length = $this->headers['Content-Length'];
if (!$this->multipart->process('')) {
_debug("multipart fsm returned false");
$this->_close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
default:
_warning("uncatched $event");
return 'wait_for_body';
}
}
// headers and may be body received
public function headers_received($event, $args)
{
switch ($event) {
case 'empty_line':
return 'headers_received';
break;
default:
if (substr($event, 0, 5) == 'send_') {
$protected = '_'.$event;
if (method_exists($this, $protected)) {
call_user_func_array(array(&$this, $protected), $args);
return 'headers_received';
} else {
_debug("non-existant method $event called");
return 'headers_received';
}
} elseif (isset($this->shortcuts[$event])) {
return $this->handle_shortcut($event, $args);
} else {
_warning("uncatched $event ".$args[0]);
return 'headers_received';
}
}
}
public function closed($event, $args)
{
_warning("uncatched $event");
}
// sets input headers
// called internally for every header received
protected function set_header($k, $v)
{
$k = trim($k);
$v = ltrim($v);
// is expect header?
if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') {
$this->expect = true;
}
// is multipart form data?
if (strtolower($k) == 'content-type') {
$ctype = explode(';', $v);
if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') {
$boundary = explode('=', trim($ctype[1]));
if (strtolower(trim($boundary[0])) == 'boundary') {
_debug("multipart with boundary $boundary[1] detected");
$this->multipart = new HTTPMultiPart(ltrim($boundary[1]));
}
}
}
$this->headers[trim($k)] = trim($v);
}
// shortcut handler
protected function handle_shortcut($event, $args)
{
_debug("executing shortcut '$event'");
switch ($event) {
// http status code shortcuts
case 'ok':
case 'redirect':
case 'not_modified':
case 'bad_request':
case 'not_found':
case 'internal_error':
list($headers, $body) = $this->parse_shortcut_args($args);
$code = $this->shortcuts[$event];
$this->_send_response($code, $headers, $body);
$this->_close();
return 'closed';
break;
// others
case 'recv_body':
// send expect header if required
if ($this->expect) {
$this->expect = false;
$this->_send_line(100);
}
// read data
$this->_read();
return 'wait_for_body';
break;
case 'close':
$this->_close();
return 'closed';
break;
}
}
private function parse_shortcut_args($args)
{
if (sizeof($args) == 0) {
$body = null;
$headers = array();
}
if (sizeof($args) == 1) {
// http headers or body only received
if (is_array($args[0])) {
// http headers only
$headers = $args[0];
$body = null;
} else {
// body only
$body = $args[0];
$headers = array();
}
} elseif (sizeof($args) == 2) {
// body and http headers both received
if (is_array($args[0])) {
// header first
$body = $args[1];
$headers = $args[0];
} else {
// body first
$body = $args[0];
$headers = $args[1];
}
}
return array($headers, $body);
}
//
// send methods
// available only on 'headers_received' state
//
protected function _send_line($code)
{
$raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF;
$this->_send($raw);
}
protected function _send_header($k, $v)
{
$raw = $k.': '.$v.HTTP_CRLF;
$this->_send($raw);
}
protected function _send_headers($code, $headers)
{
foreach ($headers as $k => $v) {
$this->_send_header($k, $v);
}
}
protected function _send_body($body)
{
$this->_send($body);
}
- protected function _send_response($code, $headers = array(), $body = null)
+ protected function _send_response($code, array $headers = array(), $body = null)
{
// send out response line
$this->_send_line($code);
// set content length of body exists and is not already set
if ($body && !isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($body);
}
// send out headers
$this->_send_headers($code, $headers);
// send body
// prefixed with an empty line
_debug("sending out HTTP_CRLF prefixed body");
if ($body) {
$this->_send_body(HTTP_CRLF.$body);
}
}
//
// internal methods
//
// initializes status line elements
private function _line($method, $resource, $version)
{
$this->method = $method;
$this->resource = $resource;
$resource = explode("?", $resource);
$this->path = $resource[0];
if (sizeof($resource) == 2) {
$query = $resource[1];
$query = explode("&", $query);
foreach ($query as $q) {
$q = explode("=", $q);
if (sizeof($q) == 1) {
$q[1] = "";
}
$this->query[$q[0]] = $q[1];
}
}
$this->version = $version;
}
private function _send($raw)
{
call_user_func($this->_send_cb, $this->sock, $raw);
}
private function _read()
{
call_user_func($this->_read_cb, $this->sock);
}
private function _close()
{
call_user_func($this->_close_cb, $this->sock);
}
}
diff --git a/http/http_server.php b/http/http_server.php
index 939b64c..fb83db0 100644
--- a/http/http_server.php
+++ b/http/http_server.php
@@ -1,199 +1,204 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/http/http_dispatcher.php';
require_once JAXL_CWD.'/http/http_request.php';
// carriage return and line feed
define('HTTP_CRLF', "\r\n");
// 1xx informational
define('HTTP_100', "Continue");
define('HTTP_101', "Switching Protocols");
// 2xx success
define('HTTP_200', "OK");
// 3xx redirection
define('HTTP_301', 'Moved Permanently');
define('HTTP_304', 'Not Modified');
// 4xx client error
define('HTTP_400', 'Bad Request');
define('HTTP_403', 'Forbidden');
define('HTTP_404', 'Not Found');
define('HTTP_405', 'Method Not Allowed');
define('HTTP_499', 'Client Closed Request'); // Nginx
// 5xx server error
define('HTTP_500', 'Internal Server Error');
define('HTTP_503', 'Service Unavailable');
class HTTPServer
{
+ /** @var JAXLSocketServer */
private $server = null;
+ /** @var callable */
public $cb = null;
private $dispatcher = null;
private $requests = array();
public function __construct($port = 9699, $address = "127.0.0.1")
{
$path = 'tcp://'.$address.':'.$port;
$this->server = new JAXLSocketServer(
$path,
array(&$this, 'on_accept'),
array(&$this, 'on_request')
);
$this->dispatcher = new HTTPDispatcher();
}
public function __destruct()
{
$this->server = null;
}
public function dispatch($rules)
{
foreach ($rules as $rule) {
$this->dispatcher->add_rule($rule);
}
}
+ /**
+ * @param callable $cb
+ */
public function start($cb = null)
{
$this->cb = $cb;
JAXLLoop::run();
}
public function on_accept($sock, $addr)
{
_debug("on_accept for client#$sock, addr:$addr");
// initialize new request obj
$request = new HTTPRequest($sock, $addr);
// setup sock cb
$request->set_sock_cb(
array(&$this->server, 'send'),
array(&$this->server, 'read'),
array(&$this->server, 'close')
);
// cache request object
$this->requests[$sock] = &$request;
// reactive client for further read
$this->server->read($sock);
}
public function on_request($sock, $raw)
{
_debug("on_request for client#$sock");
$request = $this->requests[$sock];
// 'wait_for_body' state is reached when ever
// application calls recv_body() method
// on received $request object
if ($request->state() == 'wait_for_body') {
$request->body($raw);
} else {
// break on crlf
$lines = explode(HTTP_CRLF, $raw);
// parse request line
if ($request->state() == 'wait_for_request_line') {
list($method, $resource, $version) = explode(" ", $lines[0]);
$request->line($method, $resource, $version);
unset($lines[0]);
_info($request->ip." ".$request->method." ".$request->resource." ".$request->version);
}
// parse headers
foreach ($lines as $line) {
$line_parts = explode(":", $line);
if (sizeof($line_parts) > 1) {
if (strlen($line_parts[0]) > 0) {
$k = $line_parts[0];
unset($line_parts[0]);
$v = implode(":", $line_parts);
$request->set_header($k, $v);
}
} elseif (strlen(trim($line_parts[0])) == 0) {
$request->empty_line();
} else {
// if exploded line array size is 1
// and there is something in $line_parts[0]
// must be request body
$request->body($line);
}
}
}
// if request has reached 'headers_received' state?
if ($request->state() == 'headers_received') {
// dispatch to any matching rule found
_debug("delegating to dispatcher for further routing");
$dispatched = $this->dispatcher->dispatch($request);
// if no dispatch rule matched call generic callback
if (!$dispatched && $this->cb) {
_debug("no dispatch rule matched, sending to generic callback");
call_user_func($this->cb, $request);
} elseif (!$dispatched) {
// elseif not dispatched and not generic callbacked
// send 404 not_found
// TODO: send 404 if no callback is registered for this request
_debug("dropping request since no matching dispatch rule or generic callback was specified");
$request->not_found('404 Not Found');
}
} else {
// if state is not 'headers_received'
// reactivate client socket for read event
$this->server->read($sock);
}
}
}
diff --git a/jaxl.php b/jaxl.php
index 9ed5fd1..45b1ed6 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,931 +1,932 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const version = '3.0.1';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable $cb
* @param int $priority
* @return string
*/
public function add_cb($ev, $cb, $priority = 1)
{
return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
-
- public function start($opts = array())
+
+ public function start(array $opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (sizeof($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
// signals callback handler
// not for public api consumption
public function signal_handler($sig)
{
$this->end_stream();
$this->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
if (isset($this->cfg['fb_access_token'])) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
+ /**
+ * @param string $reason
+ */
public function handle_auth_failure($reason)
{
- $this->ev->emit('on_auth_failure', array(
- $reason
- ));
+ $this->ev->emit('on_auth_failure', array($reason));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
diff --git a/xep/xep_0045.php b/xep/xep_0045.php
index 325428e..08b8115 100644
--- a/xep/xep_0045.php
+++ b/xep/xep_0045.php
@@ -1,124 +1,124 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
define('NS_MUC', 'http://jabber.org/protocol/muc');
class XEP_0045 extends XMPPXep
{
//
// abstract method
//
public function init()
{
return array();
}
public function send_groupchat($room_jid, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'groupchat',
'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid),
'from'=>$this->jaxl->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->jaxl->send($msg);
}
//
// api methods (occupant use case)
//
// room_full_jid simply means room jid with nick name as resource
- public function get_join_room_pkt($room_full_jid, $options)
+ public function get_join_room_pkt($room_full_jid, array $options)
{
$pkt = $this->jaxl->get_pres_pkt(
array(
'from'=>$this->jaxl->full_jid->to_string(),
'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid),
'id' => (isset($options['id'])) ? $options['id'] : uniqid()
)
);
$x = $pkt->c('x', NS_MUC);
if (isset($options['no_history'])) {
$x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0))->up();
}
if (isset($options['password'])) {
$x->c('password')->t($options['password'])->up();
}
return $x;
}
- public function join_room($room_full_jid, $options = array())
+ public function join_room($room_full_jid, array $options = array())
{
$pkt = $this->get_join_room_pkt($room_full_jid, $options);
$this->jaxl->send($pkt);
}
public function get_leave_room_pkt($room_full_jid)
{
return $this->jaxl->get_pres_pkt(array(
'type' => 'unavailable',
'from' => $this->jaxl->full_jid->to_string(),
'to' => ($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid
));
}
public function leave_room($room_full_jid)
{
$pkt = $this->get_leave_room_pkt($room_full_jid);
$this->jaxl->send($pkt);
}
//
// api methods (moderator use case)
//
//
// event callbacks
//
}
diff --git a/xep/xep_0077.php b/xep/xep_0077.php
index 748b88e..66b5f24 100644
--- a/xep/xep_0077.php
+++ b/xep/xep_0077.php
@@ -1,87 +1,87 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
define('NS_FEATURE_REGISTER', 'http://jabber.org/features/iq-register');
define('NS_INBAND_REGISTER', 'jabber:iq:register');
class XEP_0077 extends XMPPXep
{
//
// abstract method
//
public function init()
{
return array(
);
}
//
// api methods
//
public function get_form_pkt($domain)
{
return $this->jaxl->get_iq_pkt(
array('to' => $domain, 'type' => 'get'),
new JAXLXml('query', NS_INBAND_REGISTER)
);
}
public function get_form($domain)
{
$this->jaxl->send($this->get_form_pkt($domain));
}
- public function set_form($domain, $form)
+ public function set_form($domain, array $form)
{
$query = new JAXLXml('query', NS_INBAND_REGISTER);
foreach ($form as $k => $v) {
$query->c($k, null, array(), $v)->up();
}
$pkt = $this->jaxl->get_iq_pkt(
array('to' => $domain, 'type' => 'set'),
$query
);
$this->jaxl->send($pkt);
}
}
diff --git a/xep/xep_0206.php b/xep/xep_0206.php
index 332a4d5..7fa3f09 100644
--- a/xep/xep_0206.php
+++ b/xep/xep_0206.php
@@ -1,267 +1,270 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind');
define('NS_BOSH', 'urn:xmpp:xbosh');
class XEP_0206 extends XMPPXep
{
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
//
// event callbacks
//
+ /**
+ * @param JAXLXml|XMPPStanza|string $body
+ */
public function send($body)
{
if (is_object($body)) {
$body = $body->to_string();
} else {
if (substr($body, 0, 15) == '<stream:stream ') {
$this->restarted = true;
$body = new JAXLXml('body', NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
'xmlns:xmpp' => NS_BOSH
));
$body = $body->to_string();
} elseif (substr($body, 0, 16) == '</stream:stream>') {
$body = new JAXLXml('body', NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
$body = $body->to_string();
} else {
$body = $this->wrap($body);
}
}
_debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
_debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
_debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
_debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
_error("no ch found");
exit;
}
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
$this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
$this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
$this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
'to' => (($this->jaxl && $this->jaxl->jid)
? $this->jaxl->jid->domain
: $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
'xmlns:xmpp' => NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
if (isset($this->jaxl->cfg['jid'])) {
$attrs['from'] = $this->jaxl->cfg['jid'];
}
$body = new JAXLXml('body', NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
$body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
_debug("disconnecting");
}
}
diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php
index 804c064..b07e831 100644
--- a/xmpp/xmpp_stanza.php
+++ b/xmpp/xmpp_stanza.php
@@ -1,193 +1,198 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
/**
* Generic xmpp stanza object which provide convinient access pattern over xml objects
* Also to be able to convert an existing xml object into stanza object (to get access patterns going)
* this class doesn't extend xml, but infact works on a reference of xml object
* If not provided during constructor, new xml object is created and saved as reference
*
* @author abhinavsingh
*
*/
class XMPPStanza
{
/**
* @var JAXLXml
*/
private $xml;
- public function __construct($name, $attrs = array(), $ns = NS_JABBER_CLIENT)
+ /**
+ * @param JAXLXml|string $name
+ * @param array $attrs
+ * @param string $ns
+ */
+ public function __construct($name, array $attrs = array(), $ns = NS_JABBER_CLIENT)
{
if ($name instanceof JAXLXml) {
$this->xml = $name;
} else {
$this->xml = new JAXLXml($name, $ns, $attrs);
}
}
public function __call($method, $args)
{
return call_user_func_array(array($this->xml, $method), $args);
}
public function __get($prop)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
return isset($this->xml->attrs[$prop]) ? $this->xml->attrs[$prop] : null;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val) {
return null;
}
$val = new XMPPJid($val);
return $val->$key;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val = $this->xml->exists($prop);
if (!$val) {
return null;
}
return $val->text;
break;
default:
return null;
break;
}
}
public function __set($prop, $val)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop = $val;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
$this->xml->attrs[$prop] = $val;
return true;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val1 = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val1) {
$val1 = '';
}
$val1 = new XMPPJid($val1);
$val1->$key = $val;
$this->xml->attrs[$attr] = $val1->to_string();
return true;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val1 = $this->xml->exists($prop);
if (!$val1) {
$this->xml->c($prop)->t($val)->up();
} else {
$this->xml->update($prop, $val1->ns, $val1->attrs, $val);
}
return true;
break;
default:
return null;
break;
}
}
}
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php
index 9948334..b366fdb 100644
--- a/xmpp/xmpp_stream.php
+++ b/xmpp/xmpp_stream.php
@@ -1,661 +1,667 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
require_once JAXL_CWD.'/core/jaxl_xml_stream.php';
require_once JAXL_CWD.'/core/jaxl_util.php';
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/xmpp/xmpp_msg.php';
require_once JAXL_CWD.'/xmpp/xmpp_pres.php';
require_once JAXL_CWD.'/xmpp/xmpp_iq.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
* @var JAXLSocketClient|XEP_0206
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
* @param string $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
$jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//_debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
_error("got invalid return value from state handler '".$this->state."', sending end stream...");
$this->send_end_stream();
$this->state = "logged_out";
_notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers");
}
+ /**
+ * @param JAXLXml|XMPPStanza $stanza
+ */
public function send($stanza)
{
$this->trans->send($stanza->to_string());
}
+ /**
+ * @param string $data
+ */
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
_debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//_debug("stream started");
return "wait_for_stream_features";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', NS_BIND) ? true : false;
$sess = $stanza->exists('session', NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
_debug("no catch");
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) {
$this->xml->reset_parser();
$this->trans->compress();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_compression_result", 0);
break;
}
}
public function wait_for_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) {
$reason = $stanza->childrens[0]->name;
//_debug("sasl failed with reason ".$reason."");
$this->handle_auth_failure($reason);
return "logged_out";
} elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_challenge_response($challenge);
return "wait_for_sasl_response";
} elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
_debug("got unhandled sasl response");
}
return "wait_for_sasl_response";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_sasl_response", 0);
break;
}
}
public function wait_for_bind_response($event, $args)
{
|
jaxl/JAXL | e9d5d2ca8018e6de17ac55abf6fcef34bcd3221d | Add type hints | diff --git a/core/jaxl_event.php b/core/jaxl_event.php
index a62b38b..8e8969d 100644
--- a/core/jaxl_event.php
+++ b/core/jaxl_event.php
@@ -1,134 +1,156 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Following kind of events are possible:
* 1) hook i.e. if a callback for such an event is registered, calling function
* is responsible for the workflow from their on
* 2) filter i.e. calling function will manipulate passed arguments
* and modified arguments will be passed to next chain of filter
*
* As a rule of thumb, only 1 hook can be registered for an event, while more
* than 1 filter is allowed for an event hook and filter both cannot be applied
* on an event.
*
* @author abhinavsingh
*
*/
class JAXLEvent
{
protected $common = array();
public $reg = array();
public function __construct($common)
{
$this->common = $common;
}
public function __destruct()
{
}
- // add callback on a event
- // returns a reference to be used while deleting callback
- // callback'd method must return TRUE to be persistent
- // if none returned or FALSE, callback will be removed automatically
- public function add($ev, $cb, $pri)
+ /**
+ * Add callback on a event.
+ *
+ * Callback'd method must return `true` to be persistent, otherwise
+ * if returned `null` or `false`, callback will be removed automatically.
+ *
+ * @param string $ev
+ * @param callable $cb
+ * @param int $priority
+ * @return string Reference to be used while deleting callback.
+ */
+ public function add($ev, $cb, $priority)
{
if (!isset($this->reg[$ev])) {
$this->reg[$ev] = array();
}
$ref = sizeof($this->reg[$ev]);
- $this->reg[$ev][] = array($pri, $cb);
+ $this->reg[$ev][] = array($priority, $cb);
return $ev."-".$ref;
}
- // emit event to notify registered callbacks
- // is a pqueue required here for performance enhancement
- // in case we have too many cbs on a specific event?
- public function emit($ev, $data = array())
+ /**
+ * Emit event to notify registered callbacks.
+ *
+ * TODO: Is a pqueue required here for performance enhancement in case we
+ * have too many cbs on a specific event?
+ *
+ * @param string $ev
+ * @param array $data
+ * @return array
+ */
+ public function emit($ev, array $data = array())
{
$data = array_merge($this->common, $data);
$cbs = array();
if (!isset($this->reg[$ev])) {
return $data;
}
foreach ($this->reg[$ev] as $cb) {
if (!isset($cbs[$cb[0]])) {
$cbs[$cb[0]] = array();
}
$cbs[$cb[0]][] = $cb[1];
}
foreach ($cbs as $pri => $cb) {
foreach ($cb as $c) {
$ret = call_user_func_array($c, $data);
// This line is for fixing situation where callback function doesn't return an array type.
// In such cases next call of call_user_func_array will report error since $data is not
// an array type as expected.
// Things will change in future, atleast put the callback inside a try/catch block.
// Here we only check if there was a return, if yes we update $data with return value.
// This is bad design, need more thoughts, should work as of now.
if ($ret) {
$data = $ret;
}
}
}
unset($cbs);
return $data;
}
- // remove previous registered callback
+ /**
+ * Remove previous registered callback.
+ *
+ * @param string $ref
+ */
public function del($ref)
{
$ref = explode("-", $ref);
unset($this->reg[$ref[0]][$ref[1]]);
}
+ /**
+ * @param string $ev
+ * @return bool
+ */
public function exists($ev)
{
$ret = isset($this->reg[$ev]);
//_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists"));
return $ret;
}
}
diff --git a/docs/users/jaxl_instance.rst b/docs/users/jaxl_instance.rst
index d10398c..501db1e 100644
--- a/docs/users/jaxl_instance.rst
+++ b/docs/users/jaxl_instance.rst
@@ -1,166 +1,166 @@
.. _jaxl-instance:
JAXL Instance
=============
``JAXL`` instance configure/manage other :ref:`sub-packages <jaxl-instance>`.
It provides an event based callback methodology on various underlying object. Whenever required
``JAXL`` instance will itself perform the configured defaults.
Constructor options
-------------------
#. ``jid``
#. ``pass``
#. ``resource``
If not passed Jaxl will use a random resource value
#. ``auth_type``
DIGEST-MD5, PLAIN (default), CRAM-MD5, ANONYMOUS, X-FACEBOOK-PLATFORM
#. ``host``
#. ``port``
#. ``bosh_url``
#. ``log_path``
#. ``log_level``
``JAXL_ERROR``, ``JAXL_WARNING``, ``JAXL_NOTICE``, ``JAXL_INFO`` (default), ``JAXL_DEBUG``
#. ``fb_access_token``
required when using X-FACEBOOK-PLATFORM auth mechanism
#. ``fb_app_key``
required when using X-FACEBOOK-PLATFORM auth mechanism
#. ``force_tls``
#. ``stream_context``
#. ``priv_dir``
Jaxl creates 4 directories names ``log``, ``tmp``, ``run`` and ``sock`` inside a private directory
which defaults to ``JAXL_CWD.'/.jaxl'``. If this option is passed, it will overwrite default private
directory.
.. note::
Jaxl currently doesn't check upon the permissions of passed ``priv_dir``. Make sure Jaxl library
have sufficient permissions to create above mentioned directories.
Available Event Callbacks
-------------------------
Following ``$ev`` are available on ``JAXL`` lifecycle for registering callbacks:
#. ``on_connect``
``JAXL`` instance has connected successfully
#. ``on_connect_error``
``JAXL`` instance failed to connect
#. ``on_stream_start``
``JAXL`` instance has successfully initiated XMPP stream with the jabber server
#. ``on_stream_features``
``JAXL`` instance has received supported stream features
#. ``on_auth_success``
authentication successful
#. ``on_auth_failure``
authentication failed
#. ``on_presence_stanza``
``JAXL`` instance has received a presence stanza
#. ``on_{$type}_message``
``JAXL`` instance has received a message stanza. ``$type`` can be ``chat``, ``groupchat``, ``headline``, ``normal``, ``error``
#. ``on_stanza_id_{$id}``
Useful when dealing with iq stanza. This event is fired when ``JAXL`` instance has received response to a particular
xmpp stanza id
#. ``on_{$name}_stanza``
Useful when dealing with custom xmpp stanza
#. ``on_disconnect``
``JAXL`` instance has disconnected from the jabber server
Available Methods
-----------------
Following methods are available on initialized ``JAXL`` instance object:
#. ``get_pid_file_path()``
returns path of ``JAXL`` instance pid file
#. ``get_sock_file_path()``
returns path to ``JAXL`` ipc unix socket domain
#. ``require_xep($xeps = array())``
autoload and initialize passed XEP's
- #. ``add_cb($ev, $cb, $pri = 1)``
+ #. ``add_cb($ev, $cb, $priority = 1)``
add a callback to function ``$cb`` on event ``$ev``, returns a reference of added callback
#. ``del_cb($ref)``
delete previously registered event callback
#. ``set_status($status, $show, $priority)``
send a presence status stanza
#. ``send_chat_msg($to, $body, $thread = null, $subject = null)``
send a message stanza of type chat
#. ``get_vcard($jid = null, $cb = null)``
fetch vcard for bare ``$jid``, passed ``$cb`` will be called with received vcard stanza
#. ``get_roster($cb = null)``
fetch roster list of connected jabber client, passed ``$cb`` will be called with received roster stanza
#. ``start($opts = array())``
start configured ``JAXL`` instance, optionally accepts two options specified below:
#. ``--with-debug-shell``
start ``JAXL`` instance and enter an interactive console
#. ``--with-unix-sock``
start ``JAXL`` instance with support for IPC and remote debugging
#. ``send($stanza)``
send an instance of JAXLXml packet over connected socket
#. ``send_raw($data)``
send raw payload over connected socket
#. ``get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)``
#. ``get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)``
#. ``get_iq_pkt($attrs, $payload)``
\ No newline at end of file
diff --git a/jaxl.php b/jaxl.php
index 897878b..9ed5fd1 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,827 +1,827 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const version = '3.0.1';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
- * @param callable? $cb
- * @param number $pri
+ * @param callable $cb
+ * @param int $priority
* @return string
*/
- public function add_cb($ev, $cb, $pri = 1)
+ public function add_cb($ev, $cb, $priority = 1)
{
- return $this->ev->add($ev, $cb, $pri);
+ return $this->ev->add($ev, $cb, $priority);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start($opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (sizeof($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
// signals callback handler
// not for public api consumption
public function signal_handler($sig)
{
$this->end_stream();
$this->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
if (isset($this->cfg['fb_access_token'])) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array(
$reason
));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
|
jaxl/JAXL | 4fada400aedbd1b575567ea7d6f140b393a99786 | Fix arguments check | diff --git a/jaxl.php b/jaxl.php
index 9e25918..897878b 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,931 +1,931 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const version = '3.0.1';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable? $cb
* @param number $pri
* @return string
*/
public function add_cb($ev, $cb, $pri = 1)
{
return $this->ev->add($ev, $cb, $pri);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start($opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (sizeof($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
- if (isset($opts['--with-debug-shell'])) {
+ if (isset($opts['--with-debug-shell']) && $opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
- if (isset($opts['--with-unix-sock'])) {
+ if (isset($opts['--with-unix-sock']) && $opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
// signals callback handler
// not for public api consumption
public function signal_handler($sig)
{
$this->end_stream();
$this->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
if (isset($this->cfg['fb_access_token'])) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt(
$mech,
isset($this->jid) ? $this->jid->to_string() : null,
$this->pass
);
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!isset($this->xeps['0114'])) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array(
$reason
));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity '.
// 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
// ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item '.
// 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
// ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
// ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
|
jaxl/JAXL | 82d80b0d1732198357c85189f9184ba9e5556843 | Revert "Fix examples to conform to requirements for PHP 5.2.4" | diff --git a/docs/users/xmpp_examples.rst b/docs/users/xmpp_examples.rst
index 7808d0c..e92d3c3 100644
--- a/docs/users/xmpp_examples.rst
+++ b/docs/users/xmpp_examples.rst
@@ -1,126 +1,120 @@
XMPP Examples
=============
Echo Bot Client
---------------
include ``jaxl.php`` and initialize a new ``JAXL`` instance:
.. code-block:: ruby
require 'jaxl.php';
$client = new JAXL(array(
'jid' => '[email protected]',
'pass' => 'password'
));
We just initialized a new ``JAXL`` instance by passing our jabber client ``jid`` and ``pass``.
View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor.
Next we need to register callbacks on events of interest using ``JAXL::add_cb/2`` method as shown below:
.. code-block:: ruby
- function on_auth_success_callback()
- {
+ $client->add_cb('on_auth_success', function () {
global $client;
$client->set_status("available!"); // set your status
$client->get_vcard(); // fetch your vcard
$client->get_roster(); // fetch your roster list
- }
- $client->add_cb('on_auth_success', 'on_auth_success_callback');
+ });
- function on_chat_message_callback($stanza)
- {
+ $client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
- }
- $client->add_cb('on_chat_message', 'on_chat_message_callback');
+ });
- function on_disconnect_callback()
- {
+ $client->add_cb('on_disconnect', function () {
_debug("got on_disconnect cb");
- }
- $client->add_cb('on_disconnect', 'on_disconnect_callback');
+ });
We just registered callbacks on ``on_auth_success``, ``on_chat_message`` and ``on_disconnect`` events
that will occur inside our configured ``JAXL`` instance lifecycle.
We also passed a method that will be called (with parameters if any) when the event has been detected.
See list of :ref:`available event callbacks <jaxl-instance>` that we can hook to inside ``JAXL`` instance lifecycle.
Received ``$msg`` parameter with ``on_chat_message`` event callback above, will be an instance of ``XMPPMsg`` which
extends ``XMPPStanza`` class, that allows us easy to use access patterns to common XMPP stanza attributes like
``to``, ``from``, ``type``, ``id`` to name a few.
We were also able to access our xmpp client full jabber id by calling ``$client->full_jid``. This attribute of
``JAXL`` instance is available from ``on_auth_success`` event. ``full_jid`` attribute is an instance of ``XMPPJid``.
To send our echo back ``$msg`` packet we called ``JAXL::send/1`` which accepts a single parameter which MUST be
an instance of ``JAXLXml``. Since ``XMPPStanza`` is a wrapper upon ``JAXLXml`` we can very well pass our modified
``$msg`` object to the send method.
Read more about various :ref:`XML Objects <xml-objects>` and how they make writing XMPP applications fun and easy.
You can also :ref:`add custom access patterns <xml-objects>` upon received ``XMPPStanza`` objects. Since all access
patterns are evaluated upon first access and cached for later usage, adding hundreds of custom access patterns that
retrieves information from 100th child of received XML packet will not be an issue.
We will finally start our xmpp client by calling:
.. code-block:: ruby
$client->start();
See list of :ref:`available options <jaxl-instance>` that can be passed to the ``JAXL::start/2`` method.
These options are particularly useful for debugging and monitoring.
Echo Bot BOSH Client
--------------------
Everything goes same for a cli BOSH client. To run above echo bot client example as a bosh client simply
pass additional parameters to ``JAXL`` constructor:
.. code-block:: ruby
require 'jaxl.php';
$client = new JAXL(array(
'jid' => '[email protected]',
'pass' => 'password',
'bosh_url' => 'http://localhost:5280/http-bind'
));
You can even pass custom values for ``hold``, ``wait`` and other attributes.
View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor.
Echo Bot External Component
---------------------------
Again almost everything goes same for an external component except a few custom ``JAXL`` constructor
parameter as shown below:
.. code-block:: ruby
require_once 'jaxl.php';
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required) destination socket
'host' => $argv[3],
'port' => $argv[4]
));
We will also need to include ``XEP0114`` which implements Jabber Component XMPP Extension.
.. code-block:: ruby
// (required)
$comp->require_xep(array(
'0114' // jabber component protocol
));
``JAXL::require_xep/1`` accepts an array of XEP numbers passed as strings.
diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php
index 2580e25..445a9c5 100644
--- a/examples/echo_bosh_bot.php
+++ b/examples/echo_bosh_bot.php
@@ -1,114 +1,106 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'bosh_url' => 'http://localhost:5280/http-bind',
// (optional) srv lookup is done if not provided
// for bosh client 'host' value is used for 'route' attribute
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
// for bosh client 'port' value is used for 'route' attribute
//'port' => 5222,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXL_INFO
));
//
// add necessary event callbacks here
//
-function on_auth_success_callback()
-{
+$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
+});
-function on_auth_failure_callback($reason)
-{
+$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
-}
-$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
+});
-function on_chat_message_callback($stanza)
-{
+$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
-}
-$client->add_cb('on_chat_message', 'on_chat_message_callback');
+});
-function on_disconnect_callback()
-{
+$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
-}
-$client->add_cb('on_disconnect', 'on_disconnect_callback');
+});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/echo_bot.php b/examples/echo_bot.php
index 68d1037..ad2377d 100644
--- a/examples/echo_bot.php
+++ b/examples/echo_bot.php
@@ -1,159 +1,147 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// Run as:
// php examples/echo_bot.php root@localhost password
// php examples/echo_bot.php root@localhost password DIGEST-MD5
// php examples/echo_bot.php localhost "" ANONYMOUS
if ($argc < 3) {
echo "Usage: $argv[0] jid pass auth_type\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (optional) srv lookup is done if not provided
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
//'port' => 5222,
// (optional) defaults to false
//'force_tls' => true,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXL_INFO
));
//
// required XEP's
//
$client->require_xep(array(
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
-function on_auth_success_callback()
-{
+$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
+});
// by default JAXL instance catches incoming roster list results and updates
// roster list is parsed/cached and an event 'on_roster_update' is emitted
-function on_roster_update_callback()
-{
+$client->add_cb('on_roster_update', function () {
//global $client;
//print_r($client->roster);
-}
-$client->add_cb('on_roster_update', 'on_roster_update_callback');
+});
-function on_auth_failure_callback($reason)
-{
+$client->add_cb('on_auth_failure', function ($reason) {
global $client;
- $client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
-}
-$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
+ $client->send_end_stream();
+});
-function on_chat_message_callback($stanza)
-{
+$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
-}
-$client->add_cb('on_chat_message', 'on_chat_message_callback');
+});
-function on_presence_stanza_callback($stanza)
-{
+$client->add_cb('on_presence_stanza', function ($stanza) {
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
_info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
-}
-$client->add_cb('on_presence_stanza', 'on_presence_stanza_callback');
+});
-function on_disconnect_callback()
-{
+$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
-}
-$client->add_cb('on_disconnect', 'on_disconnect_callback');
+});
//
// finally start configured xmpp stream
//
$client->start(array(
'--with-debug-shell' => true,
'--with-unix-sock' => true
));
echo "done\n";
diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php
index 0f82d4f..2e55019 100644
--- a/examples/echo_component_bot.php
+++ b/examples/echo_component_bot.php
@@ -1,106 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc != 5) {
echo "Usage: $argv[0] jid pass host port\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'host' => $argv[3],
'port' => $argv[4],
'log_level' => JAXL_INFO
));
//
// XEP's required (required)
//
$comp->require_xep(array(
'0114' // jabber component protocol
));
//
// add necessary event callbacks here
//
-function on_auth_success_callback()
-{
+$comp->add_cb('on_auth_success', function () {
_info("got on_auth_success cb");
-}
-$comp->add_cb('on_auth_success', 'on_auth_success_callback');
+});
-function on_auth_failure_callback($reason)
-{
+$comp->add_cb('on_auth_failure', function ($reason) {
global $comp;
$comp->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
-}
-$comp->add_cb('on_auth_failure', 'on_auth_failure_callback');
+});
-function on_chat_message_callback($stanza)
-{
+$comp->add_cb('on_chat_message', function ($stanza) {
global $comp;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $comp->jid->to_string();
$comp->send($stanza);
-}
-$comp->add_cb('on_chat_message', 'on_chat_message_callback');
+});
-function on_disconnect_callback()
-{
+$comp->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
-}
-$comp->add_cb('on_disconnect', 'on_disconnect_callback');
+});
//
// finally start configured xmpp stream
//
$comp->start();
echo "done\n";
diff --git a/examples/http_bind.php b/examples/http_bind.php
index 2a4d258..0ae7c87 100644
--- a/examples/http_bind.php
+++ b/examples/http_bind.php
@@ -1,66 +1,64 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if (!isset($_GET['jid']) || !isset($_GET['pass'])) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
require_once '../jaxl.php';
$client = new JAXL(array(
'jid' => $_GET['jid'],
'pass' => $_GET['pass'],
'bosh_url' => 'http://localhost:5280/http-bind',
'log_level' => JAXL_DEBUG
));
-function on_auth_success_callback()
-{
+$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
+});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php
index 527b441..d3a1faa 100644
--- a/examples/http_pre_bind.php
+++ b/examples/http_pre_bind.php
@@ -1,103 +1,99 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// http pre bind php script
$body = file_get_contents("php://input");
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
if (!isset($attrs['to']) &&
!isset($attrs['rid']) &&
!isset($attrs['wait']) &&
!isset($attrs['hold'])
) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
require_once '../jaxl.php';
$to = (string)$attrs['to'];
$rid = (int)$attrs['rid'];
$wait = (int)$attrs['wait'];
$hold = (int)$attrs['hold'];
list($host, $port) = JAXLUtil::get_dns_srv($to);
$client = new JAXL(array(
'domain' => $to,
'host' => $host,
'port' => $port,
'bosh_url' => 'http://localhost:5280/http-bind',
'bosh_rid' => $rid,
'bosh_wait' => $wait,
'bosh_hold' => $hold,
'auth_type' => 'ANONYMOUS',
'log_level' => JAXL_INFO
));
-function on_auth_success_callback()
-{
+$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
echo sprintf(
'<body xmlns="%s" sid="%s" rid="%s" jid="%s"/>',
NS_HTTP_BIND,
$client->xeps['0206']->sid,
$client->xeps['0206']->rid,
$client->full_jid->to_string()
);
exit;
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
+});
-function on_auth_failure_callback($reason)
-{
+$client->add_cb('on_auth_failure', function ($reason) {
global $client;
- $client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
-}
-$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
+ $client->send_end_stream();
+});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php
index c0e5a83..19bd013 100644
--- a/examples/muc_log_bot.php
+++ b/examples/muc_log_bot.php
@@ -1,156 +1,146 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 5) {
echo "Usage: $argv[0] host jid pass [email protected] nickname\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[2],
'pass' => $argv[3],
'host' => $argv[1],
'log_level' => JAXL_INFO
));
$client->require_xep(array(
'0045', // MUC
'0203', // Delayed Delivery
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$_room_full_jid = $argv[4]."/".$argv[5];
$room_full_jid = new XMPPJid($_room_full_jid);
-function on_auth_success_callback()
-{
+$client->add_cb('on_auth_success', function () {
global $client, $room_full_jid;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// join muc room
$client->xeps['0045']->join_room($room_full_jid);
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
+});
-function on_auth_failure_callback($reason)
-{
+$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
-}
-$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
+});
-function on_groupchat_message_callback($stanza)
-{
+$client->add_cb('on_groupchat_message', function ($stanza) {
global $client;
$from = new XMPPJid($stanza->from);
$delay = $stanza->exists('delay', NS_DELAYED_DELIVERY);
if ($from->resource) {
echo sprintf(
"message stanza rcvd from %s saying... %s, %s".PHP_EOL,
$from->resource,
$stanza->body,
$delay ? "delay timestamp ".$delay->attrs['stamp'] : "timestamp ".gmdate("Y-m-dTH:i:sZ")
);
} else {
$subject = $stanza->exists('subject');
if ($subject) {
echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".
$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL;
}
}
-}
-$client->add_cb('on_groupchat_message', 'on_chat_message_callback');
+});
-function on_presence_stanza_callback($stanza)
-{
+$client->add_cb('on_presence_stanza', function ($stanza) {
global $client, $room_full_jid;
$from = new XMPPJid($stanza->from);
// self-stanza received, we now have complete room roster
if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) {
if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) {
if (($status = $x->exists('status', null, array('code' => '110'))) !== false) {
$item = $x->exists('item');
_info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].
", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']);
} else {
_info("xmlns #user have no x child element");
}
} else {
_warning("=======> odd case 1");
}
} elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) {
// stanza from other users received
if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) {
$item = $x->exists('item');
echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".
$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL;
} else {
_warning("=======> odd case 2");
}
} else {
_warning("=======> odd case 3");
}
-}
-$client->add_cb('on_presence_stanza', 'on_presence_stanza_callback');
+});
-function on_disconnect_callback()
-{
+$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
-}
-$client->add_cb('on_disconnect', 'on_disconnect_callback');
+});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/pipes.php b/examples/pipes.php
index c332a48..1f7a1a8 100644
--- a/examples/pipes.php
+++ b/examples/pipes.php
@@ -1,59 +1,57 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// include and configure logger
require_once 'jaxl.php';
JAXLLogger::$level = JAXL_INFO;
// include jaxl pipes
require_once JAXL_CWD.'/core/jaxl_pipe.php';
// initialize
$pipe_name = getmypid();
$pipe = new JAXLPipe($pipe_name);
// add read event callback
-function read_event_callback($data)
-{
+$pipe->set_callback(function ($data) {
global $pipe;
_info("read ".trim($data)." from pipe");
-}
-$pipe->set_callback('read_event_callback');
+});
JAXLLoop::run();
echo "done\n";
diff --git a/examples/publisher.php b/examples/publisher.php
index 6b22756..51730e1 100644
--- a/examples/publisher.php
+++ b/examples/publisher.php
@@ -1,107 +1,101 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXL_INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
-function on_auth_success_callback()
-{
+$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// publish
$item = new JAXLXml('item', null, array('id' => time()));
$item->c('entry', 'http://www.w3.org/2005/Atom');
$item->c('title')->t('Soliloquy')->up();
$item->c('summary')->t('To be, or not to be: that is the question')->up();
$item->c(
'link',
null,
array('rel' => 'alternate', 'type' => 'text/html', 'href' => 'http://denmark.lit/2003/12/13/atom03')
)->up();
$item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up();
$item->c('published')->t('2003-12-13T18:30:02Z')->up();
$item->c('updated')->t('2003-12-13T18:30:02Z')->up();
$client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item);
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
+});
-function on_auth_failure_callback($reason)
-{
+$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
-}
-$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
+});
-function on_disconnect_callback()
-{
+$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
-}
-$client->add_cb('on_disconnect', 'on_disconnect_callback');
+});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/register_user.php b/examples/register_user.php
index 9f6f863..77bf93b 100644
--- a/examples/register_user.php
+++ b/examples/register_user.php
@@ -1,173 +1,167 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 2) {
echo "Usage: $argv[0] domain\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'log_level' => JAXL_DEBUG
));
$client->require_xep(array(
'0077' // InBand Registration
));
//
// below are two states which become part of
// our client's xmpp_stream lifecycle
// consider as if these methods are directly
// inside xmpp_stream state machine
//
// Note: $stanza = $args[0] is an instance of
// JAXLXml in xmpp_stream state methods,
// it is yet not ready for easy access
// patterns available on XMPPStanza instances
//
$form = array();
function wait_for_register_response($event, $args)
{
global $client, $form;
if ($event == 'stanza_cb') {
$stanza = $args[0];
if ($stanza->name == 'iq') {
$form['type'] = $stanza->attrs['type'];
if ($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
} elseif ($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo sprintf(
"registration failed with error code: %s and type: %s".PHP_EOL,
$error->attrs['code'],
$error->attrs['type']
);
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$client->send_end_stream();
return "logged_out";
}
}
} else {
_notice("unhandled event $event rcvd");
}
}
function wait_for_register_form($event, $args)
{
global $client, $form;
$stanza = $args[0];
$query = $stanza->exists('query', NS_INBAND_REGISTER);
if ($query) {
$instructions = $query->exists('instructions');
if ($instructions) {
echo $instructions->text.PHP_EOL;
}
foreach ($query->childrens as $k => $child) {
if ($child->name != 'instructions') {
$form[$child->name] = readline($child->name.":");
}
}
$client->xeps['0077']->set_form($stanza->attrs['from'], $form);
return "wait_for_register_response";
} else {
$client->end_stream();
return "logged_out";
}
}
//
// add necessary event callbacks here
//
-function on_stream_features_callback($stanza)
-{
+$client->add_cb('on_stream_features', function ($stanza) {
global $client, $argv;
$client->xeps['0077']->get_form($argv[1]);
return "wait_for_register_form";
-}
-$client->add_cb('on_stream_features', 'on_stream_features_callback');
+});
-function on_disconnect_callback()
-{
+$client->add_cb('on_disconnect', function () {
global $form;
_info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed'));
-}
-$client->add_cb('on_disconnect', 'on_disconnect_callback');
+});
//
// finally start configured xmpp stream
//
$client->start();
//
// if registration was successful
// try to connect with newly registered account
//
if ($form['type'] == 'result') {
_info("connecting newly registered user account");
$client = new JAXL(array(
'jid' => $form['username'].'@'.$argv[1],
'pass' => $form['password'],
'log_level' => JAXL_DEBUG
));
- function on_auth_success_callback()
- {
+ $client->add_cb('on_auth_success', function () {
global $client;
$client->set_status('Available');
- }
- $client->add_cb('on_auth_success', 'on_auth_success_callback');
+ });
$client->start();
}
echo "done\n";
diff --git a/examples/subscriber.php b/examples/subscriber.php
index 6018bb5..62da19f 100644
--- a/examples/subscriber.php
+++ b/examples/subscriber.php
@@ -1,104 +1,96 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXL_INFO
));
$client->require_xep(array(
'0060' // Publish-Subscribe
));
//
// add necessary event callbacks here
//
-function on_auth_success_callback()
-{
+$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// create node
//$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node');
// subscribe
$client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node');
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
+});
-function on_auth_failure_callback($reason)
-{
+$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
-}
-$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
+});
-function on_headline_message_callback($stanza)
-{
+$client->add_cb('on_headline_message', function ($stanza) {
global $client;
if (($event = $stanza->exists('event', NS_PUBSUB.'#event'))) {
_info("got pubsub event");
} else {
_warning("unknown headline message rcvd");
}
-}
-$client->add_cb('on_headline_message', 'on_headline_message_callback');
+});
-function on_disconnect_callback()
-{
+$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
-}
-$client->add_cb('on_disconnect', 'on_disconnect_callback');
+});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/xfacebook_platform_client.php b/examples/xfacebook_platform_client.php
index 7e3bc9f..6eca5af 100644
--- a/examples/xfacebook_platform_client.php
+++ b/examples/xfacebook_platform_client.php
@@ -1,106 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc != 4) {
echo "Usage: $argv[0] fb_user_id_or_username fb_app_key fb_access_token\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1].'@chat.facebook.com',
'fb_app_key' => $argv[2],
'fb_access_token' => $argv[3],
// force tls (facebook require this now)
'force_tls' => true,
// (required) force facebook oauth
'auth_type' => 'X-FACEBOOK-PLATFORM',
// (optional)
//'resource' => 'resource',
'log_level' => JAXL_INFO
));
//
// add necessary event callbacks here
//
-function on_auth_success_callback()
-{
+$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
+});
-function on_auth_failure_callback($reason)
-{
+$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
-}
-$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
+});
-function on_chat_message_callback($stanza)
-{
+$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
-}
-$client->add_cb('on_chat_message', 'on_chat_message_callback');
+});
-function on_disconnect_callback()
-{
+$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
-}
-$client->add_cb('on_disconnect', 'on_disconnect_callback');
+});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php
index 9670ea0..ec04b96 100644
--- a/examples/xmpp_rest.php
+++ b/examples/xmpp_rest.php
@@ -1,79 +1,75 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// View explanation for this example here:
// https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
// initialize xmpp client
require_once 'jaxl.php';
$xmpp = new JAXL(array(
'jid' => $argv[1],
'pass' => $argv[2],
'log_level' => JAXL_INFO
));
// register callbacks on required xmpp events
-function on_auth_success_callback()
-{
+$xmpp->add_cb('on_auth_success', function () {
global $xmpp;
_info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string());
-}
-$xmpp->add_cb('on_auth_success', 'on_auth_success_callback');
+});
// initialize http server
require_once JAXL_CWD.'/http/http_server.php';
$http = new HTTPServer();
// add generic callback
// you can also dispatch REST style callback
// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules
-function generic_callback($request)
-{
+$http->cb = function ($request) {
// For demo purposes we simply return xmpp client full jid
global $xmpp;
$request->ok($xmpp->full_jid->to_string());
-}
-$http->cb = 'generic_callback';
+};
// This will start main JAXLLoop,
// hence we don't need to call $http->start() explicitly
$xmpp->start();
diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php
index e4eacbc..0d3acc7 100644
--- a/examples/xoauth2_gtalk_client.php
+++ b/examples/xoauth2_gtalk_client.php
@@ -1,105 +1,97 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc != 3) {
echo "Usage: $argv[0] jid access_token\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// force tls
'force_tls' => true,
// (required) perform X-OAUTH2
'auth_type' => 'X-OAUTH2',
// (optional)
//'resource' => 'resource',
'log_level' => JAXL_DEBUG
));
//
// add necessary event callbacks here
//
-function on_auth_success_callback()
-{
+$client->add_cb('on_auth_success', function () {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
-}
-$client->add_cb('on_auth_success', 'on_auth_success_callback');
+});
-function on_auth_failure_callback($reason)
-{
+$client->add_cb('on_auth_failure', function ($reason) {
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
-}
-$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
+});
-function on_chat_message_callback($stanza)
-{
+$client->add_cb('on_chat_message', function ($stanza) {
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
-}
-$client->add_cb('on_chat_message', 'on_chat_message_callback');
+});
-function on_disconnect_callback()
-{
+$client->add_cb('on_disconnect', function () {
_info("got on_disconnect cb");
-}
-$client->add_cb('on_disconnect', 'on_disconnect_callback');
+});
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
|
jaxl/JAXL | 606e27178bf4e1cb47c80e8d4034dc0ac0e18557 | Rename methods in jaxlctl | diff --git a/jaxlctl b/jaxlctl
index c81b4db..d7a01ef 100755
--- a/jaxlctl
+++ b/jaxlctl
@@ -1,200 +1,200 @@
#!/usr/bin/env php
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
error_reporting(E_ALL | E_STRICT);
date_default_timezone_set('UTC');
$params = $argv;
$exe = array_shift($params);
$command = array_shift($params);
require_once 'jaxl.php';
JAXLLogger::$level = JAXL_INFO;
// TODO: an abstract JAXLCtlCommand class
// with seperate class per command
// a mechanism to register new commands
class JAXLCtl
{
protected $ipc = null;
protected $buffer = '';
protected $buffer_cb = null;
protected $cli = null;
public $dots = "....... ";
protected $symbols = array();
public function __construct($command, $params)
{
global $exe;
if (method_exists($this, $command)) {
$r = call_user_func_array(array(&$this, $command), $params);
if (sizeof($r) == 2) {
list($buffer_cb, $quit_cb) = $r;
$this->buffer_cb = $buffer_cb;
- $this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb);
+ $this->cli = new JAXLCli(array(&$this, 'onTerminalInput'), $quit_cb);
$this->run();
} else {
_colorize("oops! internal command error", JAXL_ERROR);
exit;
}
} else {
_colorize("error: invalid command '$command' received", JAXL_ERROR);
_colorize("type '$exe help' for list of available commands", JAXL_NOTICE);
exit;
}
}
public function run()
{
JAXLCli::prompt();
JAXLLoop::run();
}
- public function on_terminal_input($raw)
+ public function onTerminalInput($raw)
{
$raw = trim($raw);
$last = substr($raw, -1, 1);
if ($last == ";") {
// dispatch to buffer callback
call_user_func($this->buffer_cb, $this->buffer.$raw);
$this->buffer = '';
} elseif ($last == '\\') {
$this->buffer .= substr($raw, 0, -1);
echo $this->dots;
} else {
// buffer command
$this->buffer .= $raw."; ";
echo $this->dots;
}
}
- public static function print_help()
+ public static function printHelp()
{
global $exe;
_colorize("Usage: $exe command [options...]\n", JAXL_INFO);
_colorize("Commands:", JAXL_NOTICE);
_colorize(" help This help text", JAXL_DEBUG);
_colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG);
_colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG);
echo "\n";
}
protected function help()
{
- JAXLCtl::print_help();
+ JAXLCtl::printHelp();
exit;
}
//
// shell command
//
protected function shell()
{
- return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit'));
+ return array(array(&$this, 'onShellInput'), array(&$this, 'onShellQuit'));
}
private function eval_($raw, $symbols)
{
extract($symbols);
eval($raw);
$g = get_defined_vars();
unset($g['raw']);
unset($g['symbols']);
return $g;
}
- public function on_shell_input($raw)
+ public function onShellInput($raw)
{
$this->symbols = $this->eval_($raw, $this->symbols);
JAXLCli::prompt();
}
- public function on_shell_quit()
+ public function onShellQuit()
{
exit;
}
//
// debug command
//
protected function debug($sock_path)
{
$this->ipc = new JAXLSocketClient();
- $this->ipc->set_callback(array(&$this, 'on_debug_response'));
+ $this->ipc->set_callback(array(&$this, 'onDebugResponse'));
$this->ipc->connect('unix://'.$sock_path);
- return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit'));
+ return array(array(&$this, 'onDebugInput'), array(&$this, 'onDebugQuit'));
}
- public function on_debug_response($raw)
+ public function onDebugResponse($raw)
{
$ret = unserialize($raw);
print_r($ret);
echo "\n";
JAXLCli::prompt();
}
- public function on_debug_input($raw)
+ public function onDebugInput($raw)
{
$this->ipc->send($this->buffer.$raw);
}
- public function on_debug_quit()
+ public function onDebugQuit()
{
$this->ipc->disconnect();
exit;
}
}
// we atleast need a command argument
if ($argc < 2) {
- JAXLCtl::print_help();
+ JAXLCtl::printHelp();
exit;
}
$ctl = new JAXLCtl($command, $params);
echo "done\n";
|
jaxl/JAXL | a4469c792ee8a804b1b0450f472590d325fc96c6 | Rename tests | diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index 4ef33a8..92f8f0e 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,18 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
>
<testsuites>
- <testsuite name="JAXL">
- <directory suffix=".php">tests/</directory>
+ <testsuite>
+ <directory suffix="Test.php">tests/</directory>
</testsuite>
</testsuites>
</phpunit>
diff --git a/tests/test_jaxl_event.php b/tests/JAXLEventTest.php
similarity index 100%
rename from tests/test_jaxl_event.php
rename to tests/JAXLEventTest.php
diff --git a/tests/test_jaxl_socket_client.php b/tests/JAXLSocketClientTest.php
similarity index 100%
rename from tests/test_jaxl_socket_client.php
rename to tests/JAXLSocketClientTest.php
diff --git a/tests/tests.php b/tests/JAXLTest.php
similarity index 100%
rename from tests/tests.php
rename to tests/JAXLTest.php
diff --git a/tests/test_jaxl_xml_stream.php b/tests/JAXLXmlStreamTest.php
similarity index 100%
rename from tests/test_jaxl_xml_stream.php
rename to tests/JAXLXmlStreamTest.php
diff --git a/tests/test_xmpp_jid.php b/tests/XMPPJidTest.php
similarity index 100%
rename from tests/test_xmpp_jid.php
rename to tests/XMPPJidTest.php
diff --git a/tests/test_xmpp_msg.php b/tests/XMPPMsgTest.php
similarity index 100%
rename from tests/test_xmpp_msg.php
rename to tests/XMPPMsgTest.php
diff --git a/tests/test_xmpp_stanza.php b/tests/XMPPStanzaTest.php
similarity index 100%
rename from tests/test_xmpp_stanza.php
rename to tests/XMPPStanzaTest.php
diff --git a/tests/test_xmpp_stream.php b/tests/XMPPStreamTest.php
similarity index 100%
rename from tests/test_xmpp_stream.php
rename to tests/XMPPStreamTest.php
|
jaxl/JAXL | be8e2fbdbe591d92431bf7deebc1fb0a0438ba5d | Fix PSR: _ prefix | diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php
index 1468551..544fea5 100644
--- a/core/jaxl_sock5.php
+++ b/core/jaxl_sock5.php
@@ -1,131 +1,131 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class JAXLSock5
{
private $client = null;
protected $transport = null;
protected $ip = null;
protected $port = null;
public function __construct($transport = 'tcp')
{
$this->transport = $transport;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function __destruct()
{
}
public function connect($ip, $port = 1080)
{
$this->ip = $ip;
$this->port = $port;
- $sock_path = $this->_sock_path();
+ $sock_path = $this->sock_path();
if ($this->client->connect($sock_path)) {
_debug("established connection to $sock_path");
return true;
} else {
_error("unable to connect $sock_path");
return false;
}
}
//
// Three phases of SOCK5
//
// Negotiation pkt consists of 3 part:
// 0x05 => Sock protocol version
// 0x01 => Number of method identifier octet
//
// Following auth methods are defined:
// 0x00 => No authentication required
// 0x01 => GSSAPI
// 0x02 => USERNAME/PASSWORD
// 0x03 to 0x7F => IANA ASSIGNED
// 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS
// 0xFF => NO ACCEPTABLE METHODS
public function negotiate()
{
$pkt = pack("C3", 0x05, 0x01, 0x00);
$this->client->send($pkt);
// enter sub-negotiation state
}
public function relay_request()
{
// enter wait for reply state
}
public function send_data()
{
}
//
// Socket client callback
//
public function on_response($raw)
{
_debug($raw);
}
//
// Private
//
- protected function _sock_path()
+ protected function sock_path()
{
return $this->transport.'://'.$this->ip.':'.$this->port;
}
}
diff --git a/http/http_client.php b/http/http_client.php
index 1506799..4cfd80b 100644
--- a/http/http_client.php
+++ b/http/http_client.php
@@ -1,150 +1,150 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class HTTPClient
{
private $url = null;
private $parts = array();
private $headers = array();
private $data = null;
public $method = null;
private $client = null;
public function __construct($url, $headers = array(), $data = null)
{
$this->url = $url;
$this->headers = $headers;
$this->data = $data;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function start($method = 'GET')
{
$this->method = $method;
$this->parts = parse_url($this->url);
- $transport = $this->_transport();
- $ip = $this->_ip();
- $port = $this->_port();
+ $transport = $this->transport();
+ $ip = $this->ip();
+ $port = $this->port();
$socket_path = $transport.'://'.$ip.':'.$port;
if ($this->client->connect($socket_path)) {
_debug("connection to $this->url established");
// send request data
$this->send_request();
// start main loop
JAXLLoop::run();
} else {
_debug("unable to open $this->url");
}
}
public function on_response($raw)
{
_info("got http response");
}
protected function send_request()
{
- $this->client->send($this->_line()."\r\n");
- $this->client->send($this->_ua()."\r\n");
- $this->client->send($this->_host()."\r\n");
+ $this->client->send($this->line()."\r\n");
+ $this->client->send($this->ua()."\r\n");
+ $this->client->send($this->host()."\r\n");
$this->client->send("\r\n");
}
//
// private methods on uri parts
//
- private function _line()
+ private function line()
{
- return $this->method.' '.$this->_uri().' HTTP/1.1';
+ return $this->method.' '.$this->uri().' HTTP/1.1';
}
- private function _ua()
+ private function ua()
{
return 'User-Agent: jaxl_http_client/3.x';
}
- private function _host()
+ private function host()
{
- return 'Host: '.$this->parts['host'].':'.$this->_port();
+ return 'Host: '.$this->parts['host'].':'.$this->port();
}
- private function _transport()
+ private function transport()
{
return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl');
}
- private function _ip()
+ private function ip()
{
return gethostbyname($this->parts['host']);
}
- private function _port()
+ private function port()
{
return isset($this->parts['port']) ? $this->parts['port'] : 80;
}
- private function _uri()
+ private function uri()
{
$uri = $this->parts['path'];
if (isset($this->parts['query'])) {
$uri .= '?'.$this->parts['query'];
}
if (isset($this->parts['fragment'])) {
$uri .= '#'.$this->parts['fragment'];
}
return $uri;
}
}
diff --git a/http/http_request.php b/http/http_request.php
index f4a2ee4..a616575 100644
--- a/http/http_request.php
+++ b/http/http_request.php
@@ -1,512 +1,512 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/http/http_multipart.php';
//
// These methods are available only once
// $request FSM has reached 'headers_received' state
//
// following shortcuts are available
// on received $request object:
//
// $request->{status_code_name}($headers, $body)
// $request->{status_code_name}($body, $headers)
//
// $request->{status_code_name}($headers)
// $request->{status_code_name}($body)
//
// following specific methods are also available:
//
// $request->send_line($code)
// $request->send_header($key, $value)
// $request->send_headers($headers)
// $request->send_message($string)
//
// all the above methods can also be directly performed using:
//
// $request->send_response($code, $headers = array(), $body = null)
//
// Note: All the send_* methods do not manage connection close/keep-alive logic,
// it is upto you to do that, by default connection will usually be dropped
// on client disconnect if not handled by you.
//
class HTTPRequest extends JAXLFsm
{
// peer identifier
public $sock = null;
public $ip = null;
public $port = null;
// request line
public $version = null;
public $method = null;
public $resource = null;
public $path = null;
public $query = array();
// headers and body
public $headers = array();
public $body = null;
public $recvd_body_len = 0;
// is true if 'Expect: 100-Continue'
// request header has been seen
public $expect = false;
// set if there is Content-Type: multipart/form-data; boundary=...
// header already seen
public $multipart = null;
// callback for send/read/close actions on accepted sock
- private $_send_cb = null;
- private $_read_cb = null;
- private $_close_cb = null;
+ private $send_cb = null;
+ private $read_cb = null;
+ private $close_cb = null;
private $shortcuts = array(
'ok' => 200, // 2xx
'redirect' => 302, 'not_modified' => 304, // 3xx
'not_found' => 404, 'bad_request' => 400, // 4xx
'internal_error' => 500, // 5xx
'recv_body' => true, 'close' => true // others
);
public function __construct($sock, $addr)
{
$this->sock = $sock;
$addr = explode(":", $addr);
$this->ip = $addr[0];
if (sizeof($addr) == 2) {
$this->port = $addr[1];
}
parent::__construct("setup");
}
public function __destruct()
{
_debug("http request going down in ".$this->state." state");
}
public function state()
{
return $this->state;
}
//
// abstract method implementation
//
public function handle_invalid_state($r)
{
_debug("handle invalid state called with");
var_dump($r);
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case 'set_sock_cb':
- $this->_send_cb = $args[0];
- $this->_read_cb = $args[1];
- $this->_close_cb = $args[2];
+ $this->send_cb = $args[0];
+ $this->read_cb = $args[1];
+ $this->close_cb = $args[2];
return 'wait_for_request_line';
break;
default:
_warning("uncatched $event");
return 'setup';
}
}
public function wait_for_request_line($event, $args)
{
switch ($event) {
case 'line':
- $this->_line($args[0], $args[1], $args[2]);
+ $this->line($args[0], $args[1], $args[2]);
return 'wait_for_headers';
break;
default:
_warning("uncatched $event");
return 'wait_for_request_line';
}
}
public function wait_for_headers($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'maybe_headers_received';
default:
_warning("uncatched $event");
return 'wait_for_headers';
}
}
public function maybe_headers_received($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'headers_received';
break;
case 'body':
return $this->wait_for_body($event, $args);
break;
default:
_warning("uncatched $event");
return 'maybe_headers_received';
}
}
public function wait_for_body($event, $args)
{
switch ($event) {
case 'body':
$content_length = $this->headers['Content-Length'];
$rcvd = $args[0];
$rcvd_len = strlen($rcvd);
$this->recvd_body_len += $rcvd_len;
if ($this->body === null) {
$this->body = $rcvd;
} else {
$this->body .= $rcvd;
}
if ($this->multipart) {
// boundary start, content_disposition, form data, boundary start, ....., boundary end
// these define various states of a multipart/form-data
$form_data = explode("\r\n", $rcvd);
foreach ($form_data as $data) {
//_debug("passing $data to multipart fsm");
if (!$this->multipart->process($data)) {
_debug("multipart fsm returned false");
- $this->_close();
+ $this->close();
return array('closed', false);
}
}
}
if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'set_header':
$content_length = $this->headers['Content-Length'];
$body = implode(":", $args);
$rcvd_len = strlen($body);
$this->recvd_body_len += $rcvd_len;
if (!$this->multipart->process($body)) {
_debug("multipart fsm returned false");
- $this->_close();
+ $this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'empty_line':
$content_length = $this->headers['Content-Length'];
if (!$this->multipart->process('')) {
_debug("multipart fsm returned false");
- $this->_close();
+ $this->close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
default:
_warning("uncatched $event");
return 'wait_for_body';
}
}
// headers and may be body received
public function headers_received($event, $args)
{
switch ($event) {
case 'empty_line':
return 'headers_received';
break;
default:
if (substr($event, 0, 5) == 'send_') {
$protected = '_'.$event;
if (method_exists($this, $protected)) {
call_user_func_array(array(&$this, $protected), $args);
return 'headers_received';
} else {
_debug("non-existant method $event called");
return 'headers_received';
}
} elseif (isset($this->shortcuts[$event])) {
return $this->handle_shortcut($event, $args);
} else {
_warning("uncatched $event ".$args[0]);
return 'headers_received';
}
}
}
public function closed($event, $args)
{
_warning("uncatched $event");
}
// sets input headers
// called internally for every header received
protected function set_header($k, $v)
{
$k = trim($k);
$v = ltrim($v);
// is expect header?
if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') {
$this->expect = true;
}
// is multipart form data?
if (strtolower($k) == 'content-type') {
$ctype = explode(';', $v);
if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') {
$boundary = explode('=', trim($ctype[1]));
if (strtolower(trim($boundary[0])) == 'boundary') {
_debug("multipart with boundary $boundary[1] detected");
$this->multipart = new HTTPMultiPart(ltrim($boundary[1]));
}
}
}
$this->headers[trim($k)] = trim($v);
}
// shortcut handler
protected function handle_shortcut($event, $args)
{
_debug("executing shortcut '$event'");
switch ($event) {
// http status code shortcuts
case 'ok':
case 'redirect':
case 'not_modified':
case 'bad_request':
case 'not_found':
case 'internal_error':
list($headers, $body) = $this->parse_shortcut_args($args);
$code = $this->shortcuts[$event];
- $this->_send_response($code, $headers, $body);
+ $this->send_response($code, $headers, $body);
- $this->_close();
+ $this->close();
return 'closed';
break;
// others
case 'recv_body':
// send expect header if required
if ($this->expect) {
$this->expect = false;
- $this->_send_line(100);
+ $this->send_line(100);
}
// read data
- $this->_read();
+ $this->read();
return 'wait_for_body';
break;
case 'close':
- $this->_close();
+ $this->close();
return 'closed';
break;
}
}
private function parse_shortcut_args($args)
{
if (sizeof($args) == 0) {
$body = null;
$headers = array();
}
if (sizeof($args) == 1) {
// http headers or body only received
if (is_array($args[0])) {
// http headers only
$headers = $args[0];
$body = null;
} else {
// body only
$body = $args[0];
$headers = array();
}
} elseif (sizeof($args) == 2) {
// body and http headers both received
if (is_array($args[0])) {
// header first
$body = $args[1];
$headers = $args[0];
} else {
// body first
$body = $args[0];
$headers = $args[1];
}
}
return array($headers, $body);
}
//
// send methods
// available only on 'headers_received' state
//
- protected function _send_line($code)
+ protected function send_line($code)
{
$raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF;
- $this->_send($raw);
+ $this->send($raw);
}
- protected function _send_header($k, $v)
+ protected function send_header($k, $v)
{
$raw = $k.': '.$v.HTTP_CRLF;
- $this->_send($raw);
+ $this->send($raw);
}
- protected function _send_headers($code, $headers)
+ protected function send_headers($code, $headers)
{
foreach ($headers as $k => $v) {
- $this->_send_header($k, $v);
+ $this->send_header($k, $v);
}
}
- protected function _send_body($body)
+ protected function send_body($body)
{
- $this->_send($body);
+ $this->send($body);
}
- protected function _send_response($code, $headers = array(), $body = null)
+ protected function send_response($code, $headers = array(), $body = null)
{
// send out response line
- $this->_send_line($code);
+ $this->send_line($code);
// set content length of body exists and is not already set
if ($body && !isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($body);
}
// send out headers
- $this->_send_headers($code, $headers);
+ $this->send_headers($code, $headers);
// send body
// prefixed with an empty line
_debug("sending out HTTP_CRLF prefixed body");
if ($body) {
- $this->_send_body(HTTP_CRLF.$body);
+ $this->send_body(HTTP_CRLF.$body);
}
}
//
// internal methods
//
// initializes status line elements
- private function _line($method, $resource, $version)
+ private function line($method, $resource, $version)
{
$this->method = $method;
$this->resource = $resource;
$resource = explode("?", $resource);
$this->path = $resource[0];
if (sizeof($resource) == 2) {
$query = $resource[1];
$query = explode("&", $query);
foreach ($query as $q) {
$q = explode("=", $q);
if (sizeof($q) == 1) {
$q[1] = "";
}
$this->query[$q[0]] = $q[1];
}
}
$this->version = $version;
}
- private function _send($raw)
+ private function send($raw)
{
- call_user_func($this->_send_cb, $this->sock, $raw);
+ call_user_func($this->send_cb, $this->sock, $raw);
}
- private function _read()
+ private function read()
{
- call_user_func($this->_read_cb, $this->sock);
+ call_user_func($this->read_cb, $this->sock);
}
- private function _close()
+ private function close()
{
- call_user_func($this->_close_cb, $this->sock);
+ call_user_func($this->close_cb, $this->sock);
}
}
diff --git a/jaxlctl b/jaxlctl
index e83ced8..c81b4db 100755
--- a/jaxlctl
+++ b/jaxlctl
@@ -1,200 +1,200 @@
#!/usr/bin/env php
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
error_reporting(E_ALL | E_STRICT);
date_default_timezone_set('UTC');
$params = $argv;
$exe = array_shift($params);
$command = array_shift($params);
require_once 'jaxl.php';
JAXLLogger::$level = JAXL_INFO;
// TODO: an abstract JAXLCtlCommand class
// with seperate class per command
// a mechanism to register new commands
class JAXLCtl
{
protected $ipc = null;
protected $buffer = '';
protected $buffer_cb = null;
protected $cli = null;
public $dots = "....... ";
protected $symbols = array();
public function __construct($command, $params)
{
global $exe;
if (method_exists($this, $command)) {
$r = call_user_func_array(array(&$this, $command), $params);
if (sizeof($r) == 2) {
list($buffer_cb, $quit_cb) = $r;
$this->buffer_cb = $buffer_cb;
$this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb);
$this->run();
} else {
_colorize("oops! internal command error", JAXL_ERROR);
exit;
}
} else {
_colorize("error: invalid command '$command' received", JAXL_ERROR);
_colorize("type '$exe help' for list of available commands", JAXL_NOTICE);
exit;
}
}
public function run()
{
JAXLCli::prompt();
JAXLLoop::run();
}
public function on_terminal_input($raw)
{
$raw = trim($raw);
$last = substr($raw, -1, 1);
if ($last == ";") {
// dispatch to buffer callback
call_user_func($this->buffer_cb, $this->buffer.$raw);
$this->buffer = '';
} elseif ($last == '\\') {
$this->buffer .= substr($raw, 0, -1);
echo $this->dots;
} else {
// buffer command
$this->buffer .= $raw."; ";
echo $this->dots;
}
}
public static function print_help()
{
global $exe;
_colorize("Usage: $exe command [options...]\n", JAXL_INFO);
_colorize("Commands:", JAXL_NOTICE);
_colorize(" help This help text", JAXL_DEBUG);
_colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG);
_colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG);
echo "\n";
}
protected function help()
{
JAXLCtl::print_help();
exit;
}
//
// shell command
//
protected function shell()
{
return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit'));
}
- private function _eval($raw, $symbols)
+ private function eval_($raw, $symbols)
{
extract($symbols);
eval($raw);
$g = get_defined_vars();
unset($g['raw']);
unset($g['symbols']);
return $g;
}
public function on_shell_input($raw)
{
- $this->symbols = $this->_eval($raw, $this->symbols);
+ $this->symbols = $this->eval_($raw, $this->symbols);
JAXLCli::prompt();
}
public function on_shell_quit()
{
exit;
}
//
// debug command
//
protected function debug($sock_path)
{
$this->ipc = new JAXLSocketClient();
$this->ipc->set_callback(array(&$this, 'on_debug_response'));
$this->ipc->connect('unix://'.$sock_path);
return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit'));
}
public function on_debug_response($raw)
{
$ret = unserialize($raw);
print_r($ret);
echo "\n";
JAXLCli::prompt();
}
public function on_debug_input($raw)
{
$this->ipc->send($this->buffer.$raw);
}
public function on_debug_quit()
{
$this->ipc->disconnect();
exit;
}
}
// we atleast need a command argument
if ($argc < 2) {
JAXLCtl::print_help();
exit;
}
$ctl = new JAXLCtl($command, $params);
echo "done\n";
|
jaxl/JAXL | 809e4ba66d52a6f5576b2319bf4c977182563c8d | Fix PSR: Class constants must be uppercase | diff --git a/jaxl.php b/jaxl.php
index 9e25918..380dd0c 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,580 +1,580 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
- const version = '3.0.1';
- const name = 'JAXL :: Jabber XMPP Library';
+ const VERSION = '3.0.1';
+ const NAME = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
$port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
$this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
if (file_exists($this->get_pid_file_path())) {
unlink($this->get_pid_file_path());
}
if (file_exists($this->get_sock_file_path())) {
unlink($this->get_sock_file_path());
}
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable? $cb
* @param number $pri
* @return string
*/
public function add_cb($ev, $cb, $pri = 1)
{
return $this->ev->add($ev, $cb, $pri);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start($opts = array())
{
// is bosh bot?
if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (sizeof($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (isset($opts['--with-debug-shell'])) {
$this->enable_debug_shell();
}
if (isset($opts['--with-unix-sock'])) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
// signals callback handler
// not for public api consumption
public function signal_handler($sig)
{
$this->end_stream();
$this->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
|
jaxl/JAXL | e90cefaa7366775b8fe70831a4184bf29dbe1628 | Fix PSR: Constants must be uppercase | diff --git a/xmpp/xmpp_nss.php b/xmpp/xmpp_nss.php
index 7a0cad0..233db6c 100644
--- a/xmpp/xmpp_nss.php
+++ b/xmpp/xmpp_nss.php
@@ -1,60 +1,60 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// XML
-define('NS_XML_pfx', "xml");
+define('NS_XML_PFX', "xml");
define('NS_XML', 'http://www.w3.org/XML/1998/namespace');
// XMPP Core (RFC 3920)
-define('NS_XMPP_pfx', "stream");
+define('NS_XMPP_PFX', "stream");
define('NS_XMPP', 'http://etherx.jabber.org/streams');
define('NS_STREAM_ERRORS', 'urn:ietf:params:xml:ns:xmpp-streams');
define('NS_TLS', 'urn:ietf:params:xml:ns:xmpp-tls');
define('NS_SASL', 'urn:ietf:params:xml:ns:xmpp-sasl');
define('NS_BIND', 'urn:ietf:params:xml:ns:xmpp-bind');
define('NS_STANZA_ERRORS', 'urn:ietf:params:xml:ns:xmpp-stanzas');
// XMPP-IM (RFC 3921)
define('NS_JABBER_CLIENT', 'jabber:client');
define('NS_JABBER_SERVER', 'jabber:server');
define('NS_SESSION', 'urn:ietf:params:xml:ns:xmpp-session');
define('NS_ROSTER', 'jabber:iq:roster');
// Stream Compression (XEP-0138)
define('NS_COMPRESSION_FEATURE', 'http://jabber.org/features/compress');
define('NS_COMPRESSION_PROTOCOL', 'http://jabber.org/protocol/compress');
|
jaxl/JAXL | e68820ae9b31a083767e6d856b011e343514403f | Avoid to use error control operator (@) | diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php
index 3e04736..b3e1fbe 100644
--- a/core/jaxl_pipe.php
+++ b/core/jaxl_pipe.php
@@ -1,122 +1,124 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
/**
* bidirectional communication pipes for processes
*
* This is how this will be (when complete):
* $pipe = new JAXLPipe() will return an array of size 2
* $pipe[0] represents the read end of the pipe
* $pipe[1] represents the write end of the pipe
*
* Proposed functionality might even change (currently consider this as experimental)
*
* @author abhinavsingh
*
*/
class JAXLPipe
{
protected $perm = 0600;
protected $recv_cb = null;
protected $fd = null;
protected $client = null;
public $name = null;
public function __construct($name, $read_cb = null)
{
$pipes_folder = JAXL_CWD.'/.jaxl/pipes';
if (!is_dir($pipes_folder)) {
mkdir($pipes_folder);
}
$this->ev = new JAXLEvent();
$this->name = $name;
$this->read_cb = $read_cb;
$pipe_path = $this->get_pipe_file_path();
if (!file_exists($pipe_path)) {
posix_mkfifo($pipe_path, $this->perm);
$this->fd = fopen($pipe_path, 'r+');
if (!$this->fd) {
_error("unable to open pipe");
} else {
_debug("pipe opened using path $pipe_path");
_notice("Usage: $ echo 'Hello World!' > $pipe_path");
$this->client = new JAXLSocketClient();
$this->client->connect($this->fd);
$this->client->set_callback(array(&$this, 'on_data'));
}
} else {
_error("pipe with name $name already exists");
}
}
public function __destruct()
{
if (is_resource($this->fd)) {
fclose($this->fd);
}
- @unlink($this->get_pipe_file_path());
+ if (file_exists($this->get_pipe_file_path())) {
+ unlink($this->get_pipe_file_path());
+ }
_debug("unlinking pipe file");
}
public function get_pipe_file_path()
{
return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe';
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function on_data($data)
{
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $data);
}
}
}
diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php
index 86900f3..2580e25 100644
--- a/examples/echo_bosh_bot.php
+++ b/examples/echo_bosh_bot.php
@@ -1,114 +1,114 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 3) {
echo "Usage: $argv[0] jid pass\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
'bosh_url' => 'http://localhost:5280/http-bind',
// (optional) srv lookup is done if not provided
// for bosh client 'host' value is used for 'route' attribute
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
// for bosh client 'port' value is used for 'route' attribute
//'port' => 5222,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
- 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN',
+ 'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXL_INFO
));
//
// add necessary event callbacks here
//
function on_auth_success_callback()
{
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
}
$client->add_cb('on_auth_success', 'on_auth_success_callback');
function on_auth_failure_callback($reason)
{
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
}
$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
function on_chat_message_callback($stanza)
{
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
}
$client->add_cb('on_chat_message', 'on_chat_message_callback');
function on_disconnect_callback()
{
_info("got on_disconnect cb");
}
$client->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/examples/echo_bot.php b/examples/echo_bot.php
index dd7b353..68d1037 100644
--- a/examples/echo_bot.php
+++ b/examples/echo_bot.php
@@ -1,159 +1,159 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// Run as:
// php examples/echo_bot.php root@localhost password
// php examples/echo_bot.php root@localhost password DIGEST-MD5
// php examples/echo_bot.php localhost "" ANONYMOUS
if ($argc < 3) {
echo "Usage: $argv[0] jid pass auth_type\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$client = new JAXL(array(
// (required) credentials
'jid' => $argv[1],
'pass' => $argv[2],
// (optional) srv lookup is done if not provided
//'host' => 'xmpp.domain.tld',
// (optional) result from srv lookup used by default
//'port' => 5222,
// (optional) defaults to false
//'force_tls' => true,
// (optional)
//'resource' => 'resource',
// (optional) defaults to PLAIN if supported, else other methods will be automatically tried
- 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN',
+ 'auth_type' => isset($argv[3]) ? $argv[3] : 'PLAIN',
'log_level' => JAXL_INFO
));
//
// required XEP's
//
$client->require_xep(array(
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
function on_auth_success_callback()
{
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
}
$client->add_cb('on_auth_success', 'on_auth_success_callback');
// by default JAXL instance catches incoming roster list results and updates
// roster list is parsed/cached and an event 'on_roster_update' is emitted
function on_roster_update_callback()
{
//global $client;
//print_r($client->roster);
}
$client->add_cb('on_roster_update', 'on_roster_update_callback');
function on_auth_failure_callback($reason)
{
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
}
$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
function on_chat_message_callback($stanza)
{
global $client;
// echo back incoming chat message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
}
$client->add_cb('on_chat_message', 'on_chat_message_callback');
function on_presence_stanza_callback($stanza)
{
global $client;
$type = ($stanza->type ? $stanza->type : "available");
$show = ($stanza->show ? $stanza->show : "???");
_info($stanza->from." is now ".$type." ($show)");
if ($type == "available") {
// fetch vcard
$client->get_vcard($stanza->from);
}
}
$client->add_cb('on_presence_stanza', 'on_presence_stanza_callback');
function on_disconnect_callback()
{
_info("got on_disconnect cb");
}
$client->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$client->start(array(
'--with-debug-shell' => true,
'--with-unix-sock' => true
));
echo "done\n";
diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php
index c795236..0f82d4f 100644
--- a/examples/echo_component_bot.php
+++ b/examples/echo_component_bot.php
@@ -1,106 +1,106 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc != 5) {
echo "Usage: $argv[0] jid pass host port\n";
exit;
}
//
// initialize JAXL object with initial config
//
require_once 'jaxl.php';
$comp = new JAXL(array(
// (required) component host and secret
'jid' => $argv[1],
'pass' => $argv[2],
// (required)
- 'host' => @$argv[3],
+ 'host' => $argv[3],
'port' => $argv[4],
'log_level' => JAXL_INFO
));
//
// XEP's required (required)
//
$comp->require_xep(array(
'0114' // jabber component protocol
));
//
// add necessary event callbacks here
//
function on_auth_success_callback()
{
_info("got on_auth_success cb");
}
$comp->add_cb('on_auth_success', 'on_auth_success_callback');
function on_auth_failure_callback($reason)
{
global $comp;
$comp->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
}
$comp->add_cb('on_auth_failure', 'on_auth_failure_callback');
function on_chat_message_callback($stanza)
{
global $comp;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $comp->jid->to_string();
$comp->send($stanza);
}
$comp->add_cb('on_chat_message', 'on_chat_message_callback');
function on_disconnect_callback()
{
_info("got on_disconnect cb");
}
$comp->add_cb('on_disconnect', 'on_disconnect_callback');
//
// finally start configured xmpp stream
//
$comp->start();
echo "done\n";
diff --git a/examples/echo_unix_sock_server.php b/examples/echo_unix_sock_server.php
index 98b1074..7e7421b 100644
--- a/examples/echo_unix_sock_server.php
+++ b/examples/echo_unix_sock_server.php
@@ -1,60 +1,62 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
if ($argc < 2) {
echo "Usage: $argv[0] /path/to/server.sock\n";
exit;
}
require_once 'jaxl.php';
JAXLLogger::$level = JAXL_INFO;
$server = null;
function on_request($client, $raw)
{
global $server;
$server->send($client, $raw);
_info("got client callback ".$raw);
}
-@unlink($argv[1]);
+if (file_exists($argv[1])) {
+ unlink($argv[1]);
+}
$server = new JAXLSocketServer('unix://'.$argv[1], null, 'on_request');
JAXLLoop::run();
echo "done\n";
diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php
index 539168f..527b441 100644
--- a/examples/http_pre_bind.php
+++ b/examples/http_pre_bind.php
@@ -1,99 +1,103 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// http pre bind php script
$body = file_get_contents("php://input");
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
-if (!@$attrs['to'] && !@$attrs['rid'] && !@$attrs['wait'] && !@$attrs['hold']) {
+if (!isset($attrs['to']) &&
+ !isset($attrs['rid']) &&
+ !isset($attrs['wait']) &&
+ !isset($attrs['hold'])
+) {
echo "invalid input";
exit;
}
//
// initialize JAXL object with initial config
//
require_once '../jaxl.php';
$to = (string)$attrs['to'];
$rid = (int)$attrs['rid'];
$wait = (int)$attrs['wait'];
$hold = (int)$attrs['hold'];
list($host, $port) = JAXLUtil::get_dns_srv($to);
$client = new JAXL(array(
'domain' => $to,
'host' => $host,
'port' => $port,
'bosh_url' => 'http://localhost:5280/http-bind',
'bosh_rid' => $rid,
'bosh_wait' => $wait,
'bosh_hold' => $hold,
'auth_type' => 'ANONYMOUS',
'log_level' => JAXL_INFO
));
function on_auth_success_callback()
{
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
echo sprintf(
'<body xmlns="%s" sid="%s" rid="%s" jid="%s"/>',
NS_HTTP_BIND,
$client->xeps['0206']->sid,
$client->xeps['0206']->rid,
$client->full_jid->to_string()
);
exit;
}
$client->add_cb('on_auth_success', 'on_auth_success_callback');
function on_auth_failure_callback($reason)
{
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
}
$client->add_cb('on_auth_failure', 'on_auth_failure_callback');
//
// finally start configured xmpp stream
//
$client->start();
echo "done\n";
diff --git a/http/http_client.php b/http/http_client.php
index 67ea1b3..1506799 100644
--- a/http/http_client.php
+++ b/http/http_client.php
@@ -1,150 +1,150 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
/**
* TODO: convert into a finite state machine
*
* @author abhinavsingh
*
*/
class HTTPClient
{
private $url = null;
private $parts = array();
private $headers = array();
private $data = null;
public $method = null;
private $client = null;
public function __construct($url, $headers = array(), $data = null)
{
$this->url = $url;
$this->headers = $headers;
$this->data = $data;
$this->client = new JAXLSocketClient();
$this->client->set_callback(array(&$this, 'on_response'));
}
public function start($method = 'GET')
{
$this->method = $method;
$this->parts = parse_url($this->url);
$transport = $this->_transport();
$ip = $this->_ip();
$port = $this->_port();
$socket_path = $transport.'://'.$ip.':'.$port;
if ($this->client->connect($socket_path)) {
_debug("connection to $this->url established");
// send request data
$this->send_request();
// start main loop
JAXLLoop::run();
} else {
_debug("unable to open $this->url");
}
}
public function on_response($raw)
{
_info("got http response");
}
protected function send_request()
{
$this->client->send($this->_line()."\r\n");
$this->client->send($this->_ua()."\r\n");
$this->client->send($this->_host()."\r\n");
$this->client->send("\r\n");
}
//
// private methods on uri parts
//
private function _line()
{
return $this->method.' '.$this->_uri().' HTTP/1.1';
}
private function _ua()
{
return 'User-Agent: jaxl_http_client/3.x';
}
private function _host()
{
return 'Host: '.$this->parts['host'].':'.$this->_port();
}
private function _transport()
{
return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl');
}
private function _ip()
{
return gethostbyname($this->parts['host']);
}
private function _port()
{
- return @$this->parts['port'] ? $this->parts['port'] : 80;
+ return isset($this->parts['port']) ? $this->parts['port'] : 80;
}
private function _uri()
{
$uri = $this->parts['path'];
- if (@$this->parts['query']) {
+ if (isset($this->parts['query'])) {
$uri .= '?'.$this->parts['query'];
}
- if (@$this->parts['fragment']) {
+ if (isset($this->parts['fragment'])) {
$uri .= '#'.$this->parts['fragment'];
}
return $uri;
}
}
diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php
index 6d679ad..368327e 100644
--- a/http/http_dispatcher.php
+++ b/http/http_dispatcher.php
@@ -1,135 +1,135 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
//
// (optionally) set an array of url dispatch rules
// each dispatch rule is defined by an array of size 4 like:
// array($callback, $pattern, $methods, $extra), where
// $callback the method which will be called if this rule matches
// $pattern regular expression to match request path
// $methods list of allowed methods for this rule
// pass boolean true to allow all http methods
// if omitted or an empty array() is passed (which actually doesnt make sense)
// by default 'GET' will be the method allowed on this rule
// $extra reserved for future (you can totally omit this as of now)
//
class HTTPDispatchRule
{
// match callback
public $cb = null;
// regexp to match on request path
public $pattern = null;
// methods to match upon
// add atleast 1 method for this rule to work
public $methods = null;
// other matching rules
public $extra = array();
public function __construct($cb, $pattern, $methods = array('GET'), $extra = array())
{
$this->cb = $cb;
$this->pattern = $pattern;
$this->methods = $methods;
$this->extra = $extra;
}
public function match($path, $method)
{
if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) {
if (in_array($method, $this->methods)) {
return $matches;
}
}
return false;
}
}
class HTTPDispatcher
{
protected $rules = array();
public function __construct()
{
$this->rules = array();
}
public function add_rule($rule)
{
$s = sizeof($rule);
if ($s > 4) {
_debug("invalid rule");
return;
}
// fill up defaults
if ($s == 3) {
$rule[] = array();
} elseif ($s == 2) {
$rule[] = array('GET');
$rule[] = array();
} else {
_debug("invalid rule");
return;
}
$this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]);
}
public function dispatch($request)
{
foreach ($this->rules as $rule) {
//_debug("matching $request->path with pattern $rule->pattern");
if (($matches = $rule->match($request->path, $request->method)) !== false) {
_debug("matching rule found, dispatching");
$params = array($request);
// TODO: a bad way to restrict on 'pk', fix me for generalization
- if (@isset($matches['pk'])) {
+ if (isset($matches['pk'])) {
$params[] = $matches['pk'];
}
call_user_func_array($rule->cb, $params);
return true;
}
}
return false;
}
}
diff --git a/http/http_request.php b/http/http_request.php
index 67e8a2b..f4a2ee4 100644
--- a/http/http_request.php
+++ b/http/http_request.php
@@ -1,512 +1,512 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/http/http_multipart.php';
//
// These methods are available only once
// $request FSM has reached 'headers_received' state
//
// following shortcuts are available
// on received $request object:
//
// $request->{status_code_name}($headers, $body)
// $request->{status_code_name}($body, $headers)
//
// $request->{status_code_name}($headers)
// $request->{status_code_name}($body)
//
// following specific methods are also available:
//
// $request->send_line($code)
// $request->send_header($key, $value)
// $request->send_headers($headers)
// $request->send_message($string)
//
// all the above methods can also be directly performed using:
//
// $request->send_response($code, $headers = array(), $body = null)
//
// Note: All the send_* methods do not manage connection close/keep-alive logic,
// it is upto you to do that, by default connection will usually be dropped
// on client disconnect if not handled by you.
//
class HTTPRequest extends JAXLFsm
{
// peer identifier
public $sock = null;
public $ip = null;
public $port = null;
// request line
public $version = null;
public $method = null;
public $resource = null;
public $path = null;
public $query = array();
// headers and body
public $headers = array();
public $body = null;
public $recvd_body_len = 0;
// is true if 'Expect: 100-Continue'
// request header has been seen
public $expect = false;
// set if there is Content-Type: multipart/form-data; boundary=...
// header already seen
public $multipart = null;
// callback for send/read/close actions on accepted sock
private $_send_cb = null;
private $_read_cb = null;
private $_close_cb = null;
private $shortcuts = array(
'ok' => 200, // 2xx
'redirect' => 302, 'not_modified' => 304, // 3xx
'not_found' => 404, 'bad_request' => 400, // 4xx
'internal_error' => 500, // 5xx
'recv_body' => true, 'close' => true // others
);
public function __construct($sock, $addr)
{
$this->sock = $sock;
$addr = explode(":", $addr);
$this->ip = $addr[0];
if (sizeof($addr) == 2) {
$this->port = $addr[1];
}
parent::__construct("setup");
}
public function __destruct()
{
_debug("http request going down in ".$this->state." state");
}
public function state()
{
return $this->state;
}
//
// abstract method implementation
//
public function handle_invalid_state($r)
{
_debug("handle invalid state called with");
var_dump($r);
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case 'set_sock_cb':
$this->_send_cb = $args[0];
$this->_read_cb = $args[1];
$this->_close_cb = $args[2];
return 'wait_for_request_line';
break;
default:
_warning("uncatched $event");
return 'setup';
}
}
public function wait_for_request_line($event, $args)
{
switch ($event) {
case 'line':
$this->_line($args[0], $args[1], $args[2]);
return 'wait_for_headers';
break;
default:
_warning("uncatched $event");
return 'wait_for_request_line';
}
}
public function wait_for_headers($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'maybe_headers_received';
default:
_warning("uncatched $event");
return 'wait_for_headers';
}
}
public function maybe_headers_received($event, $args)
{
switch ($event) {
case 'set_header':
$this->set_header($args[0], $args[1]);
return 'wait_for_headers';
break;
case 'empty_line':
return 'headers_received';
break;
case 'body':
return $this->wait_for_body($event, $args);
break;
default:
_warning("uncatched $event");
return 'maybe_headers_received';
}
}
public function wait_for_body($event, $args)
{
switch ($event) {
case 'body':
$content_length = $this->headers['Content-Length'];
$rcvd = $args[0];
$rcvd_len = strlen($rcvd);
$this->recvd_body_len += $rcvd_len;
if ($this->body === null) {
$this->body = $rcvd;
} else {
$this->body .= $rcvd;
}
if ($this->multipart) {
// boundary start, content_disposition, form data, boundary start, ....., boundary end
// these define various states of a multipart/form-data
$form_data = explode("\r\n", $rcvd);
foreach ($form_data as $data) {
//_debug("passing $data to multipart fsm");
if (!$this->multipart->process($data)) {
_debug("multipart fsm returned false");
$this->_close();
return array('closed', false);
}
}
}
if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'set_header':
$content_length = $this->headers['Content-Length'];
$body = implode(":", $args);
$rcvd_len = strlen($body);
$this->recvd_body_len += $rcvd_len;
if (!$this->multipart->process($body)) {
_debug("multipart fsm returned false");
$this->_close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
case 'empty_line':
$content_length = $this->headers['Content-Length'];
if (!$this->multipart->process('')) {
_debug("multipart fsm returned false");
$this->_close();
return array('closed', false);
}
if ($this->recvd_body_len < $content_length) {
_debug("rcvd body len: $this->recvd_body_len/$content_length");
return 'wait_for_body';
} else {
_debug("all data received, switching state for dispatch");
return 'headers_received';
}
break;
default:
_warning("uncatched $event");
return 'wait_for_body';
}
}
// headers and may be body received
public function headers_received($event, $args)
{
switch ($event) {
case 'empty_line':
return 'headers_received';
break;
default:
if (substr($event, 0, 5) == 'send_') {
$protected = '_'.$event;
if (method_exists($this, $protected)) {
call_user_func_array(array(&$this, $protected), $args);
return 'headers_received';
} else {
_debug("non-existant method $event called");
return 'headers_received';
}
- } elseif (@isset($this->shortcuts[$event])) {
+ } elseif (isset($this->shortcuts[$event])) {
return $this->handle_shortcut($event, $args);
} else {
_warning("uncatched $event ".$args[0]);
return 'headers_received';
}
}
}
public function closed($event, $args)
{
_warning("uncatched $event");
}
// sets input headers
// called internally for every header received
protected function set_header($k, $v)
{
$k = trim($k);
$v = ltrim($v);
// is expect header?
if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') {
$this->expect = true;
}
// is multipart form data?
if (strtolower($k) == 'content-type') {
$ctype = explode(';', $v);
if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') {
$boundary = explode('=', trim($ctype[1]));
if (strtolower(trim($boundary[0])) == 'boundary') {
_debug("multipart with boundary $boundary[1] detected");
$this->multipart = new HTTPMultiPart(ltrim($boundary[1]));
}
}
}
$this->headers[trim($k)] = trim($v);
}
// shortcut handler
protected function handle_shortcut($event, $args)
{
_debug("executing shortcut '$event'");
switch ($event) {
// http status code shortcuts
case 'ok':
case 'redirect':
case 'not_modified':
case 'bad_request':
case 'not_found':
case 'internal_error':
list($headers, $body) = $this->parse_shortcut_args($args);
$code = $this->shortcuts[$event];
$this->_send_response($code, $headers, $body);
$this->_close();
return 'closed';
break;
// others
case 'recv_body':
// send expect header if required
if ($this->expect) {
$this->expect = false;
$this->_send_line(100);
}
// read data
$this->_read();
return 'wait_for_body';
break;
case 'close':
$this->_close();
return 'closed';
break;
}
}
private function parse_shortcut_args($args)
{
if (sizeof($args) == 0) {
$body = null;
$headers = array();
}
if (sizeof($args) == 1) {
// http headers or body only received
if (is_array($args[0])) {
// http headers only
$headers = $args[0];
$body = null;
} else {
// body only
$body = $args[0];
$headers = array();
}
} elseif (sizeof($args) == 2) {
// body and http headers both received
if (is_array($args[0])) {
// header first
$body = $args[1];
$headers = $args[0];
} else {
// body first
$body = $args[0];
$headers = $args[1];
}
}
return array($headers, $body);
}
//
// send methods
// available only on 'headers_received' state
//
protected function _send_line($code)
{
$raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF;
$this->_send($raw);
}
protected function _send_header($k, $v)
{
$raw = $k.': '.$v.HTTP_CRLF;
$this->_send($raw);
}
protected function _send_headers($code, $headers)
{
foreach ($headers as $k => $v) {
$this->_send_header($k, $v);
}
}
protected function _send_body($body)
{
$this->_send($body);
}
protected function _send_response($code, $headers = array(), $body = null)
{
// send out response line
$this->_send_line($code);
// set content length of body exists and is not already set
if ($body && !isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($body);
}
// send out headers
$this->_send_headers($code, $headers);
// send body
// prefixed with an empty line
_debug("sending out HTTP_CRLF prefixed body");
if ($body) {
$this->_send_body(HTTP_CRLF.$body);
}
}
//
// internal methods
//
// initializes status line elements
private function _line($method, $resource, $version)
{
$this->method = $method;
$this->resource = $resource;
$resource = explode("?", $resource);
$this->path = $resource[0];
if (sizeof($resource) == 2) {
$query = $resource[1];
$query = explode("&", $query);
foreach ($query as $q) {
$q = explode("=", $q);
if (sizeof($q) == 1) {
$q[1] = "";
}
$this->query[$q[0]] = $q[1];
}
}
$this->version = $version;
}
private function _send($raw)
{
call_user_func($this->_send_cb, $this->sock, $raw);
}
private function _read()
{
call_user_func($this->_read_cb, $this->sock);
}
private function _close()
{
call_user_func($this->_close_cb, $this->sock);
}
}
diff --git a/jaxl.php b/jaxl.php
index e87dbf2..9e25918 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,919 +1,931 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const version = '3.0.1';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
/**
* Local cache of roster list.
* @var XMPPRosterItem[]
*/
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
- $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null;
+ $jid = isset($this->cfg['jid']) ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
- $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
+ $this->priv_dir = isset($this->cfg['priv_dir']) ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
- $host = @$this->cfg['host'];
- $port = @$this->cfg['port'];
+ $host = isset($this->cfg['host']) ? $this->cfg['host'] : null;
+ $port = isset($this->cfg['port']) ? $this->cfg['port'] : null;
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
- $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host;
- $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port;
+ $this->cfg['host'] = isset($this->cfg['host']) ? $this->cfg['host'] : $host;
+ $this->cfg['port'] = isset($this->cfg['port']) ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
- if (@$this->cfg['bosh_url']) {
+ if (isset($this->cfg['bosh_url'])) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
- $stream_context = @$this->cfg['stream_context'];
+ $stream_context = isset($this->cfg['stream_context']) ? $this->cfg['stream_context'] : null;
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
- @$this->cfg['pass'],
- @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
- @$this->cfg['force_tls']
+ isset($this->cfg['pass']) ? $this->cfg['pass'] : false,
+ isset($this->cfg['resource']) ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
+ isset($this->cfg['force_tls']) ? $this->cfg['force_tls'] : false
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
- @unlink($this->get_pid_file_path());
- @unlink($this->get_sock_file_path());
+ if (file_exists($this->get_pid_file_path())) {
+ unlink($this->get_pid_file_path());
+ }
+ if (file_exists($this->get_sock_file_path())) {
+ unlink($this->get_sock_file_path());
+ }
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable? $cb
* @param number $pri
* @return string
*/
public function add_cb($ev, $cb, $pri = 1)
{
return $this->ev->add($ev, $cb, $pri);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start($opts = array())
{
// is bosh bot?
- if (@$this->cfg['bosh_url']) {
+ if (isset($this->cfg['bosh_url'])) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (sizeof($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
- if (@$opts['--with-debug-shell']) {
+ if (isset($opts['--with-debug-shell'])) {
$this->enable_debug_shell();
}
- if (@$opts['--with-unix-sock']) {
+ if (isset($opts['--with-unix-sock'])) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
// signals callback handler
// not for public api consumption
public function signal_handler($sig)
{
$this->end_stream();
$this->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
- $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN';
+ $pref_auth = isset($this->cfg['auth_type']) ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
- if (@$this->cfg['fb_access_token']) {
+ if (isset($this->cfg['fb_access_token'])) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
- $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass);
+ $this->send_auth_pkt(
+ $mech,
+ isset($this->jid) ? $this->jid->to_string() : null,
+ $this->pass
+ );
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
- /*if(!@$this->xeps['0114']) {
- $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
- $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
- }*/
+ /*if(!isset($this->xeps['0114'])) {
+ $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
+ $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
+ }*/
$this->ev->emit('on_auth_success');
}
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array(
$reason
));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
- return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1);
+ return array(isset($this->cfg['bosh_url']) ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
- if (@$this->roster[$stanza->from]) {
+ if (isset($this->roster[$stanza->from])) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
- if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) {
+ if (isset($this->roster[$jid->bare]) && isset($this->roster[$jid->bare]->resources[$jid->resource])) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
- $stanza->type = (@$stanza->type ? $stanza->type : 'normal');
+ $stanza->type = ($stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
- $stanza = @$args[0];
+ $stanza = isset($args[0]) ? $args[0] : null;
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
- //echo 'identity category:'.@$child->attrs['category'].', type:'.
- // @$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL;
+ //echo 'identity '.
+ // 'category:' . (isset($child->attrs['category']) ? $child->attrs['category'] : 'NULL').
+ // ', type:'.(isset($child->attrs['type']) ? $child->attrs['type'] : 'NULL').
+ // ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
- //echo 'item jid:'.@$child->attrs['jid'].', name:'.
- // @$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL;
+ //echo 'item '.
+ // 'jid:'.(isset($child->attrs['jid']) ? $child->attrs['jid'] : 'NULL').
+ // ', name:'.(isset($child->attrs['name']) ? $child->attrs['name'] : 'NULL').
+ // ', node:'.(isset($child->attrs['node']) ? $child->attrs['node'] : 'NULL').PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
diff --git a/xep/xep_0206.php b/xep/xep_0206.php
index ccc64ef..332a4d5 100644
--- a/xep/xep_0206.php
+++ b/xep/xep_0206.php
@@ -1,263 +1,267 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_xep.php';
define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind');
define('NS_BOSH', 'urn:xmpp:xbosh');
class XEP_0206 extends XMPPXep
{
private $mch = null;
public $chs = array();
private $recv_cb = null;
public $rid = null;
public $sid = null;
private $hold = 1;
private $wait = 30;
private $restarted = false;
public $headers = array(
'Accept-Encoding: gzip, deflate',
'Content-Type: text/xml; charset=utf-8'
);
//
// abstract method
//
public function init()
{
$this->mch = curl_multi_init();
return array(
);
}
//
// event callbacks
//
public function send($body)
{
if (is_object($body)) {
$body = $body->to_string();
} else {
if (substr($body, 0, 15) == '<stream:stream ') {
$this->restarted = true;
$body = new JAXLXml('body', NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
- 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'],
+ 'to' => (($this->jaxl && $this->jaxl->jid)
+ ? $this->jaxl->jid->domain
+ : $this->jaxl->cfg['domain']),
'xmpp:restart' => 'true',
'xmlns:xmpp' => NS_BOSH
));
$body = $body->to_string();
} elseif (substr($body, 0, 16) == '</stream:stream>') {
$body = new JAXLXml('body', NS_HTTP_BIND, array(
'sid' => $this->sid,
'rid' => ++$this->rid,
'type' => 'terminate'
));
$body = $body->to_string();
} else {
$body = $this->wrap($body);
}
}
_debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body);
$this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']);
curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false);
curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1);
curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body);
curl_multi_add_handle($this->mch, $this->chs[$this->rid]);
}
public function recv()
{
if ($this->restarted) {
$this->restarted = false;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
}
_debug("recving for $this->rid");
do {
$mrc = curl_multi_exec($this->mch, $running);
_debug("mrc=$mrc running=$running");
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
$ms = curl_multi_select($this->mch, 0.1);
if ($ms != -1) {
do {
$mrc = curl_multi_exec($this->mch, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
- $ch = @$this->chs[$this->rid];
+ $ch = isset($this->chs[$this->rid]) ? $this->chs[$this->rid] : false;
if ($ch) {
$data = curl_multi_getcontent($ch);
curl_multi_remove_handle($this->mch, $ch);
unset($this->chs[$this->rid]);
_debug("recvd for $this->rid ".$data);
list($body, $stanza) = $this->unwrap($data);
$body = new SimpleXMLElement($body);
$attrs = $body->attributes();
- if (@$attrs['type'] == 'terminate') {
+ if (isset($attrs['type']) && $attrs['type'] == 'terminate') {
// fool me again
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_end_stream());
}
} else {
if (!$this->sid) {
$this->sid = $attrs['sid'];
}
if ($this->recv_cb) {
call_user_func($this->recv_cb, $stanza);
}
}
} else {
_error("no ch found");
exit;
}
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
public function wrap($stanza)
{
return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>';
}
public function unwrap($body)
{
// a dirty way but it works efficiently
if (substr($body, -2, 2) == "/>") {
preg_match_all('/<body (.*?)\/>/smi', $body, $m);
} else {
preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m);
}
if (isset($m[1][0])) {
$envelop = "<body ".$m[1][0]."/>";
} else {
$envelop = "<body/>";
}
if (isset($m[2][0])) {
$payload = $m[2][0];
} else {
$payload = '';
}
return array($envelop, $payload);
}
public function session_start()
{
- $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
- $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
- $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
+ $this->rid = isset($this->jaxl->cfg['bosh_rid']) ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000);
+ $this->hold = isset($this->jaxl->cfg['bosh_hold']) ? $this->jaxl->cfg['bosh_hold'] : $this->hold;
+ $this->wait = isset($this->jaxl->cfg['bosh_wait']) ? $this->jaxl->cfg['bosh_wait'] : $this->wait;
// fool xmpp_stream state machine with stream start packet
// and make transition to wait_for_stream_features state
if ($this->recv_cb) {
call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl")));
}
$attrs = array(
'content' => 'text/xml; charset=utf-8',
- 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'],
+ 'to' => (($this->jaxl && $this->jaxl->jid)
+ ? $this->jaxl->jid->domain
+ : $this->jaxl->cfg['domain']),
'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'],
'secure' => 'true',
'xml:lang' => 'en',
'xmpp:version' => '1.0',
'xmlns:xmpp' => NS_BOSH,
'hold' => $this->hold,
'wait' => $this->wait,
'rid' => $this->rid,
'ver' => '1.10'
);
- if (@$this->jaxl->cfg['jid']) {
- $attrs['from'] = @$this->jaxl->cfg['jid'];
+ if (isset($this->jaxl->cfg['jid'])) {
+ $attrs['from'] = $this->jaxl->cfg['jid'];
}
$body = new JAXLXml('body', NS_HTTP_BIND, $attrs);
$this->send($body);
}
public function ping()
{
$body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid));
$this->send($body);
}
public function session_end()
{
$this->disconnect();
}
public function disconnect()
{
_debug("disconnecting");
}
}
diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php
index 6247332..804c064 100644
--- a/xmpp/xmpp_stanza.php
+++ b/xmpp/xmpp_stanza.php
@@ -1,193 +1,193 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
/**
* Generic xmpp stanza object which provide convinient access pattern over xml objects
* Also to be able to convert an existing xml object into stanza object (to get access patterns going)
* this class doesn't extend xml, but infact works on a reference of xml object
* If not provided during constructor, new xml object is created and saved as reference
*
* @author abhinavsingh
*
*/
class XMPPStanza
{
/**
* @var JAXLXml
*/
private $xml;
public function __construct($name, $attrs = array(), $ns = NS_JABBER_CLIENT)
{
if ($name instanceof JAXLXml) {
$this->xml = $name;
} else {
$this->xml = new JAXLXml($name, $ns, $attrs);
}
}
public function __call($method, $args)
{
return call_user_func_array(array($this->xml, $method), $args);
}
public function __get($prop)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
- return @$this->xml->attrs[$prop] ? $this->xml->attrs[$prop] : null;
+ return isset($this->xml->attrs[$prop]) ? $this->xml->attrs[$prop] : null;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
- $val = @$this->xml->attrs[$attr] ? $this->xml->attrs[$attr] : null;
+ $val = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val) {
return null;
}
$val = new XMPPJid($val);
return $val->$key;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val = $this->xml->exists($prop);
if (!$val) {
return null;
}
return $val->text;
break;
default:
return null;
break;
}
}
public function __set($prop, $val)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop = $val;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
$this->xml->attrs[$prop] = $val;
return true;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
- $val1 = @$this->xml->attrs[$attr];
+ $val1 = isset($this->xml->attrs[$attr]) ? $this->xml->attrs[$attr] : null;
if (!$val1) {
$val1 = '';
}
$val1 = new XMPPJid($val1);
$val1->$key = $val;
$this->xml->attrs[$attr] = $val1->to_string();
return true;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val1 = $this->xml->exists($prop);
if (!$val1) {
$this->xml->c($prop)->t($val)->up();
} else {
$this->xml->update($prop, $val1->ns, $val1->attrs, $val);
}
return true;
break;
default:
return null;
break;
}
}
}
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php
index 6f763dc..9948334 100644
--- a/xmpp/xmpp_stream.php
+++ b/xmpp/xmpp_stream.php
@@ -1,763 +1,763 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
require_once JAXL_CWD.'/core/jaxl_xml_stream.php';
require_once JAXL_CWD.'/core/jaxl_util.php';
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/xmpp/xmpp_msg.php';
require_once JAXL_CWD.'/xmpp/xmpp_pres.php';
require_once JAXL_CWD.'/xmpp/xmpp_iq.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
/**
* @var XMPPJid
*/
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
/**
* Socket/BOSH reference.
* @var JAXLSocketClient|XEP_0206
*/
protected $trans = null;
/**
* XML stream reference.
* @var JAXLXmlStream
*/
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
/**
* @param string $transport
* @param XMPPJid|null $jid
* @param string $pass
* @param string $resource
* @param bool $force_tls
*/
public function __construct(
$transport,
- XMPPJid $jid,
+ $jid,
$pass = null,
$resource = null,
$force_tls = false
) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//_debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
_error("got invalid return value from state handler '".$this->state."', sending end stream...");
$this->send_end_stream();
$this->state = "logged_out";
_notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers");
}
public function send($stanza)
{
$this->trans->send($stanza->to_string());
}
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
_debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
- $socket_path = @$args[0];
+ $socket_path = isset($args[0]) ? $args[0] : null;
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//_debug("stream started");
return "wait_for_stream_features";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', NS_BIND) ? true : false;
$sess = $stanza->exists('session', NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
_debug("no catch");
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) {
$this->xml->reset_parser();
$this->trans->compress();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_compression_result", 0);
break;
}
}
public function wait_for_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) {
$reason = $stanza->childrens[0]->name;
//_debug("sasl failed with reason ".$reason."");
$this->handle_auth_failure($reason);
return "logged_out";
} elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_challenge_response($challenge);
return "wait_for_sasl_response";
} elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) {
$this->xml->reset_parser();
- $this->send_start_stream(@$this->jid);
+ $this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
_debug("got unhandled sasl response");
}
return "wait_for_sasl_response";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_sasl_response", 0);
break;
}
}
public function wait_for_bind_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// TODO: chk on id
if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result'
&& ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) {
$this->full_jid = new XMPPJid($jid->text);
$this->send_session_pkt();
return "wait_for_session_response";
} else {
// FIXME:
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_bind_response", 0);
break;
}
}
public function wait_for_session_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$this->handle_auth_success();
return "logged_in";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_session_response", 0);
break;
}
}
public function logged_in($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// call abstract
if ($stanza->name == 'message') {
$this->handle_message($stanza);
} elseif ($stanza->name == 'presence') {
$this->handle_presence($stanza);
} elseif ($stanza->name == 'iq') {
$this->handle_iq($stanza);
} else {
$this->handle_other($event, $args);
}
return "logged_in";
break;
case "end_cb":
$this->send_end_stream();
return "logged_out";
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_in", 0);
break;
}
}
public function logged_out($event, $args)
{
switch ($event) {
case "end_cb":
$this->trans->disconnect();
return "disconnected";
break;
case "end_stream":
return "disconnected";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
case "connect":
return $this->do_connect($args);
break;
default:
// exit for any other event in logged_out state
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_out", 0);
break;
}
}
}
|
jaxl/JAXL | 5cefdc7f4e6ea105b84b26049865fd20e4947a31 | Add type hints | diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php
index 799aaaf..bba616a 100644
--- a/core/jaxl_socket_client.php
+++ b/core/jaxl_socket_client.php
@@ -1,250 +1,256 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_loop.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
class JAXLSocketClient
{
private $host = null;
private $port = null;
private $transport = null;
+ /** @var resource */
private $stream_context = null;
private $blocking = false;
public $fd = null;
public $errno = null;
public $errstr = null;
private $timeout = 10;
private $ibuffer = "";
private $obuffer = "";
private $compressed = false;
private $recv_bytes = 0;
private $send_bytes = 0;
private $recv_cb = null;
private $recv_chunk_size = 1024;
private $writing = false;
+ /**
+ * @param resource $stream_context Resource created with stream_context_create().
+ */
public function __construct($stream_context = null)
{
$this->stream_context = $stream_context;
}
public function __destruct()
{
//_debug("cleaning up xmpp socket...");
$this->disconnect();
}
public function set_callback($recv_cb)
{
$this->recv_cb = $recv_cb;
}
/**
* @param string | resource $socket_path
*/
public function connect($socket_path)
{
if (gettype($socket_path) == "string") {
$path_parts = explode(":", $socket_path);
$this->transport = $path_parts[0];
$this->host = substr($path_parts[1], 2, strlen($path_parts[1]));
if (sizeof($path_parts) == 3) {
$this->port = $path_parts[2];
}
_info("trying ".$socket_path);
if ($this->stream_context) {
$this->fd = @stream_socket_client(
$socket_path,
$this->errno,
$this->errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
$this->stream_context
);
} else {
$this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout);
}
- } else {
+ } elseif (is_resource($socket_path)) {
$this->fd = &$socket_path;
+ } else {
+ // Some error occurred.
}
if ($this->fd) {
_debug("connected to ".$socket_path."");
stream_set_blocking($this->fd, $this->blocking);
// watch descriptor for read/write events
JAXLLoop::watch($this->fd, array(
'read' => array(&$this, 'on_read_ready')
));
return true;
} else {
_error(sprintf(
"unable to connect %s with error no: %s, error str: %s",
is_null($socket_path) ? 'NULL' : $socket_path,
is_null($this->errno) ? 'NULL' : $this->errno,
is_null($this->errstr) ? 'NULL' : $this->errstr
));
$this->disconnect();
return false;
}
}
public function disconnect()
{
JAXLLoop::unwatch($this->fd, array(
'read' => true,
'write' => true
));
if (is_resource($this->fd)) {
fclose($this->fd);
}
$this->fd = null;
}
public function compress()
{
$this->compressed = true;
//stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ);
//stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE);
}
public function crypt()
{
// set blocking (since tls negotiation fails if stream is non-blocking)
stream_set_blocking($this->fd, true);
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT);
if ($ret == false) {
$ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
}
}
}
// switch back to non-blocking
stream_set_blocking($this->fd, false);
return $ret;
}
public function send($data)
{
$this->obuffer .= $data;
// add watch for write events
if ($this->writing) {
return;
}
JAXLLoop::watch($this->fd, array(
'write' => array(&$this, 'on_write_ready')
));
$this->writing = true;
}
public function on_read_ready($fd)
{
//_debug("on read ready called");
$raw = @fread($fd, $this->recv_chunk_size);
$bytes = strlen($raw);
if ($bytes === 0) {
$meta = stream_get_meta_data($fd);
if ($meta['eof'] === true) {
_warning("socket eof, disconnecting");
JAXLLoop::unwatch($fd, array(
'read' => true
));
$this->disconnect();
return;
}
}
$this->recv_bytes += $bytes;
$total = $this->ibuffer.$raw;
$this->ibuffer = "";
_debug("read ".$bytes."/".$this->recv_bytes." of data");
if ($bytes > 0) {
_debug($raw);
}
// callback
if ($this->recv_cb) {
call_user_func($this->recv_cb, $raw);
}
}
public function on_write_ready($fd)
{
//_debug("on write ready called");
$total = strlen($this->obuffer);
$bytes = @fwrite($fd, $this->obuffer);
$this->send_bytes += $bytes;
_debug("sent ".$bytes."/".$this->send_bytes." of data");
_debug(substr($this->obuffer, 0, $bytes));
$this->obuffer = substr($this->obuffer, $bytes, $total-$bytes);
// unwatch for write if obuffer is empty
if (strlen($this->obuffer) === 0) {
JAXLLoop::unwatch($fd, array(
'write' => true
));
$this->writing = false;
}
//_debug("current obuffer size: ".strlen($this->obuffer)."");
}
}
diff --git a/jaxl.php b/jaxl.php
index 9513eff..e87dbf2 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,915 +1,919 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream
{
// lib meta info
const version = '3.0.1';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
/**
* Event callback engine for XMPP stream lifecycle.
* @var JAXLEvent
*/
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
- // local cache of roster list
+
+ /**
+ * Local cache of roster list.
+ * @var XMPPRosterItem[]
+ */
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $log_colorize = true;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->cfg = $config;
// setup logger
if (isset($this->cfg['log_path'])) {
JAXLLogger::$path = $this->cfg['log_path'];
}
//else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; }
if (isset($this->cfg['log_level'])) {
JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
} else {
JAXLLogger::$level = $this->log_level;
}
if (isset($this->cfg['log_colorize'])) {
JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize'];
} else {
JAXLLogger::$colorize = $this->log_colorize;
}
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true;
if ($strict) {
$this->add_exception_handlers();
}
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if (extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if (!is_dir($this->priv_dir)) {
mkdir($this->priv_dir);
}
if (!is_dir($this->tmp_dir)) {
mkdir($this->tmp_dir);
}
if (!is_dir($this->pid_dir)) {
mkdir($this->pid_dir);
}
if (!is_dir($this->log_dir)) {
mkdir($this->log_dir);
}
if (!is_dir($this->sock_dir)) {
mkdir($this->sock_dir);
}
// touch pid file
if ($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = @$this->cfg['host'];
$port = @$this->cfg['port'];
if ((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host;
$this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if (@$this->cfg['bosh_url']) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
} else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = @$this->cfg['stream_context'];
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
@$this->cfg['pass'],
@$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
@$this->cfg['force_tls']
);
}
public function __destruct()
{
// delete pid file
_info("cleaning up pid and unix sock files");
@unlink($this->get_pid_file_path());
@unlink($this->get_sock_file_path());
parent::__destruct();
}
public function add_exception_handlers()
{
_info("strict mode enabled, adding exception handlers. ' .
'Set 'strict' => TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path()
{
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path()
{
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
/**
* @param array $xeps
*/
public function require_xep(array $xeps)
{
if (!is_array($xeps)) {
$xeps = array($xeps);
}
foreach ($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach ($this->xeps[$xep]->init() as $ev => $cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
/**
* Add callback.
*
* @see JAXLEvent::add
*
* @param string $ev Event to subscribe.
* @param callable? $cb
* @param number $pri
* @return string
*/
public function add_cb($ev, $cb, $pri = 1)
{
return $this->ev->add($ev, $cb, $pri);
}
public function del_cb($ref)
{
$this->ev->del($ref);
}
public function set_status($status, $show = 'chat', $priority = 10)
{
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread = null, $subject = null)
{
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid = null, $cb = null)
{
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if ($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function get_roster($cb = null)
{
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if ($cb) {
$this->add_cb('on_stanza_id_'.$pkt->id, $cb);
}
$this->send($pkt);
}
public function subscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to)
{
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path()
{
if (isset($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
} else {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
}
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry()
{
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start($opts = array())
{
// is bosh bot?
if (@$this->cfg['bosh_url']) {
$this->trans->session_start();
for (;;) {
// while any of the curl request is pending
// keep receiving response
while (sizeof($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if (!$this->ev->exists('on_connect')) {
$this->add_cb('on_connect', array($this, 'start_stream'));
}
// connect to the destination host/port
if ($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if (@$opts['--with-debug-shell']) {
$this->enable_debug_shell();
}
if (@$opts['--with-unix-sock']) {
$this->enable_unix_sock();
}
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
} else {
// if connection to the destination fails
if ($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
} else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
// signals callback handler
// not for public api consumption
public function signal_handler($sig)
{
$this->end_stream();
$this->disconnect();
$this->ev->emit('on_disconnect');
switch ($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr)
{
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw)
{
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock()
{
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw)
{
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell()
{
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge)
{
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge)
{
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," +
// client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
} else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms)
{
if ($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if ($mechanisms) {
foreach ($mechanisms->childrens as $mechanism) {
$mechs[$mechanism->text] = true;
}
}
// check if preferred auth type exists in available mechanisms
$pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if ($pref_auth_exists) {
$mech = $pref_auth;
} else {
// if pref auth doesn't exists, choose one from available mechanisms
foreach ($mechs as $mech => $any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if ($mech == 'X-FACEBOOK-PLATFORM') {
if (@$this->cfg['fb_access_token']) {
break;
}
} else {
// else try first of the available methods
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass);
if ($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
} elseif ($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
} elseif ($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success()
{
// if not a component
/*if(!@$this->xeps['0114']) {
- $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
- $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
- }*/
+ $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
+ $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
+ }*/
$this->ev->emit('on_auth_success');
}
public function handle_auth_failure($reason)
{
$this->ev->emit('on_auth_failure', array(
$reason
));
}
public function handle_stream_start($stanza)
{
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza)
{
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach ($query->childrens as $child) {
if ($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach ($child->childrens as $group) {
if ($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if (!$emited) {
$this->ev->emit('on_roster_update');
}
}
// if managing roster
// catch contact vcard results
if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if (@$this->roster[$stanza->from]) {
$this->roster[$stanza->from]->vcard = $query;
}
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if (!$emited) {
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
}
public function handle_presence($stanza)
{
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if ($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if ($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
} elseif ($type == 'unavailable') {
if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) {
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
}
// if managing subscription requests
// we need to automate stuff here
if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if ($this->manage_subscribe == "mutual") {
$this->subscribe($stanza->from);
}
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza)
{
$stanza = new XMPPStanza($stanza);
$stanza->type = (@$stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args)
{
$stanza = @$args[0];
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if ($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
} else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza)
{
$query = $stanza->exists('query', NS_DISCO_INFO);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'identity') {
//echo 'identity category:'.@$child->attrs['category'].', type:'.
// @$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL;
} elseif ($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
} elseif ($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza)
{
$query = $stanza->exists('query', NS_DISCO_ITEMS);
foreach ($query->childrens as $k => $child) {
if ($child->name == 'item') {
//echo 'item jid:'.@$child->attrs['jid'].', name:'.
// @$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL;
}
}
}
/**
* Used to define JAXL_CWD in tests.
*/
public static function dummy()
{
// Do nothing.
}
}
diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php
index 6b2a9aa..6247332 100644
--- a/xmpp/xmpp_stanza.php
+++ b/xmpp/xmpp_stanza.php
@@ -1,190 +1,193 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
/**
* Generic xmpp stanza object which provide convinient access pattern over xml objects
* Also to be able to convert an existing xml object into stanza object (to get access patterns going)
* this class doesn't extend xml, but infact works on a reference of xml object
* If not provided during constructor, new xml object is created and saved as reference
*
* @author abhinavsingh
*
*/
class XMPPStanza
{
+ /**
+ * @var JAXLXml
+ */
private $xml;
public function __construct($name, $attrs = array(), $ns = NS_JABBER_CLIENT)
{
if ($name instanceof JAXLXml) {
$this->xml = $name;
} else {
$this->xml = new JAXLXml($name, $ns, $attrs);
}
}
public function __call($method, $args)
{
return call_user_func_array(array($this->xml, $method), $args);
}
public function __get($prop)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
return @$this->xml->attrs[$prop] ? $this->xml->attrs[$prop] : null;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val = @$this->xml->attrs[$attr] ? $this->xml->attrs[$attr] : null;
if (!$val) {
return null;
}
$val = new XMPPJid($val);
return $val->$key;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val = $this->xml->exists($prop);
if (!$val) {
return null;
}
return $val->text;
break;
default:
return null;
break;
}
}
public function __set($prop, $val)
{
switch ($prop) {
// access to jaxl xml properties
case 'name':
case 'ns':
case 'text':
case 'attrs':
case 'childrens':
return $this->xml->$prop = $val;
break;
// access to common xml attributes
case 'to':
case 'from':
case 'id':
case 'type':
$this->xml->attrs[$prop] = $val;
return true;
break;
// access to parts of common xml attributes
case 'to_node':
case 'to_domain':
case 'to_resource':
case 'from_node':
case 'from_domain':
case 'from_resource':
list($attr, $key) = explode('_', $prop);
$val1 = @$this->xml->attrs[$attr];
if (!$val1) {
$val1 = '';
}
$val1 = new XMPPJid($val1);
$val1->$key = $val;
$this->xml->attrs[$attr] = $val1->to_string();
return true;
break;
// access to first child element text
case 'status':
case 'show':
case 'priority':
case 'body':
case 'thread':
case 'subject':
$val1 = $this->xml->exists($prop);
if (!$val1) {
$this->xml->c($prop)->t($val)->up();
} else {
$this->xml->update($prop, $val1->ns, $val1->attrs, $val);
}
return true;
break;
default:
return null;
break;
}
}
}
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php
index d05a149..6f763dc 100644
--- a/xmpp/xmpp_stream.php
+++ b/xmpp/xmpp_stream.php
@@ -1,740 +1,763 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once JAXL_CWD.'/core/jaxl_fsm.php';
require_once JAXL_CWD.'/core/jaxl_xml.php';
require_once JAXL_CWD.'/core/jaxl_xml_stream.php';
require_once JAXL_CWD.'/core/jaxl_util.php';
require_once JAXL_CWD.'/core/jaxl_socket_client.php';
require_once JAXL_CWD.'/xmpp/xmpp_nss.php';
require_once JAXL_CWD.'/xmpp/xmpp_jid.php';
require_once JAXL_CWD.'/xmpp/xmpp_msg.php';
require_once JAXL_CWD.'/xmpp/xmpp_pres.php';
require_once JAXL_CWD.'/xmpp/xmpp_iq.php';
/**
*
* Enter description here ...
* @author abhinavsingh
*
*/
abstract class XMPPStream extends JAXLFsm
{
// jid with binding resource value
public $full_jid = null;
// input parameters
+ /**
+ * @var XMPPJid
+ */
public $jid = null;
public $pass = null;
public $resource = null;
public $force_tls = false;
- // underlying socket/bosh and xml stream ref
+ /**
+ * Socket/BOSH reference.
+ * @var JAXLSocketClient|XEP_0206
+ */
protected $trans = null;
+
+ /**
+ * XML stream reference.
+ * @var JAXLXmlStream
+ */
protected $xml = null;
// stanza id
protected $last_id = 0;
//
// abstract methods
//
abstract public function handle_stream_start($stanza);
abstract public function handle_auth_mechs($stanza, $mechs);
abstract public function handle_auth_success();
abstract public function handle_auth_failure($reason);
abstract public function handle_iq($stanza);
abstract public function handle_presence($stanza);
abstract public function handle_message($stanza);
abstract public function handle_other($event, $args);
//
// public api
//
- public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false)
- {
+ /**
+ * @param string $transport
+ * @param XMPPJid|null $jid
+ * @param string $pass
+ * @param string $resource
+ * @param bool $force_tls
+ */
+ public function __construct(
+ $transport,
+ XMPPJid $jid,
+ $pass = null,
+ $resource = null,
+ $force_tls = false
+ ) {
$this->jid = $jid;
$this->pass = $pass;
$this->resource = $resource ? $resource : md5(time());
$this->force_tls = $force_tls;
$this->trans = $transport;
$this->xml = new JAXLXmlStream();
$this->trans->set_callback(array(&$this->xml, "parse"));
$this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb"));
parent::__construct("setup");
}
public function __destruct()
{
//_debug("cleaning up xmpp stream...");
}
public function handle_invalid_state($r)
{
_error("got invalid return value from state handler '".$this->state."', sending end stream...");
$this->send_end_stream();
$this->state = "logged_out";
_notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers");
}
public function send($stanza)
{
$this->trans->send($stanza->to_string());
}
public function send_raw($data)
{
$this->trans->send($data);
}
//
// pkt creation utilities
//
- public function get_start_stream($jid)
+ public function get_start_stream(XMPPJid $jid)
{
$xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" ';
//if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; }
if (isset($jid->domain)) {
$xml .= 'to="'.$jid->domain.'" ';
}
$xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">';
return $xml;
}
public function get_end_stream()
{
return '</stream:stream>';
}
public function get_starttls_pkt()
{
$stanza = new JAXLXml('starttls', NS_TLS);
return $stanza;
}
public function get_compress_pkt($method)
{
$stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL);
$stanza->c('method')->t($method);
return $stanza;
}
// someday this all needs to go inside jaxl_sasl_auth
public function get_auth_pkt($mechanism, $user, $pass)
{
$stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism));
switch ($mechanism) {
case 'PLAIN':
case 'X-OAUTH2':
$stanza->t(base64_encode("\x00".$user."\x00".$pass));
break;
case 'DIGEST-MD5':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
// client first message always starts with n, y or p for GS2 extensibility
$stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false)));
break;
case 'ANONYMOUS':
break;
case 'EXTERNAL':
// If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='.
if (strlen($pass) == 0) {
$stanza->t('=');
}
break;
default:
break;
}
return $stanza;
}
public function get_challenge_response_pkt($challenge)
{
$stanza = new JAXLXml('response', NS_SASL);
$decoded = $this->explode_data(base64_decode($challenge));
if (!isset($decoded['rspauth'])) {
_debug("calculating response to challenge");
$stanza->t($this->get_challenge_response($decoded));
}
return $stanza;
}
public function get_challenge_response($decoded)
{
$response = array();
$nc = '00000001';
if (!isset($decoded['digest-uri'])) {
$decoded['digest-uri'] = 'xmpp/'.$this->jid->domain;
}
$decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce());
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
$decoded['qop'] = 'auth';
}
$data = array_merge($decoded, array('nc' => $nc));
$response = array(
'username'=> $this->jid->node,
'response' => $this->encrypt_password($data, $this->jid->node, $this->pass),
'charset' => 'utf-8',
'nc' => $nc,
'qop' => 'auth'
);
foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
if (isset($decoded[$key])) {
$response[$key] = $decoded[$key];
}
}
return base64_encode($this->implode_data($response));
}
public function get_bind_pkt($resource)
{
$stanza = new JAXLXml('bind', NS_BIND);
$stanza->c('resource')->t($resource);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_session_pkt()
{
$stanza = new JAXLXml('session', NS_SESSION);
return $this->get_iq_pkt(array(
'type' => 'set'
), $stanza);
}
public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)
{
$msg = new XMPPMsg($attrs, $body, $thread, $subject);
if (!$msg->id) {
$msg->id = $this->get_id();
}
if ($payload) {
$msg->cnode($payload);
}
return $msg;
}
public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)
{
$pres = new XMPPPres($attrs, $status, $show, $priority);
if (!$pres->id) {
$pres->id = $this->get_id();
}
if ($payload) {
$pres->cnode($payload);
}
return $pres;
}
public function get_iq_pkt($attrs, $payload)
{
$iq = new XMPPIq($attrs);
if (!$iq->id) {
$iq->id = $this->get_id();
}
if ($payload) {
$iq->cnode($payload);
}
return $iq;
}
public function get_id()
{
++$this->last_id;
return dechex($this->last_id);
}
public function explode_data($data)
{
$data = explode(',', $data);
$pairs = array();
$key = false;
foreach ($data as $pair) {
$dd = strpos($pair, '=');
if ($dd) {
$key = trim(substr($pair, 0, $dd));
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
} elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) {
$pairs[$key] .= ',' . trim(trim($pair), '"');
continue;
}
}
return $pairs;
}
public function implode_data($data)
{
$return = array();
foreach ($data as $key => $value) {
$return[] = $key . '="' . $value . '"';
}
return implode(',', $return);
}
public function encrypt_password($data, $user, $pass)
{
foreach (array('realm', 'cnonce', 'digest-uri') as $key) {
if (!isset($data[$key])) {
$data[$key] = '';
}
}
$pack = md5($user.':'.$data['realm'].':'.$pass);
if (isset($data['authzid'])) {
$a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
} else {
$a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
}
$a2 = 'AUTHENTICATE:'.$data['digest-uri'];
return md5(sprintf(
'%s:%s:%s:%s:%s:%s',
md5($a1),
$data['nonce'],
$data['nc'],
$data['cnonce'],
$data['qop'],
md5($a2)
));
}
//
// socket senders
//
- protected function send_start_stream($jid)
+ protected function send_start_stream(XMPPJid $jid)
{
$this->send_raw($this->get_start_stream($jid));
}
public function send_end_stream()
{
$this->send_raw($this->get_end_stream());
}
protected function send_auth_pkt($type, $user, $pass)
{
$this->send($this->get_auth_pkt($type, $user, $pass));
}
protected function send_starttls_pkt()
{
$this->send($this->get_starttls_pkt());
}
protected function send_compress_pkt($method)
{
$this->send($this->get_compress_pkt($method));
}
protected function send_challenge_response($challenge)
{
$this->send($this->get_challenge_response_pkt($challenge));
}
protected function send_bind_pkt($resource)
{
$this->send($this->get_bind_pkt($resource));
}
protected function send_session_pkt()
{
$this->send($this->get_session_pkt());
}
private function do_connect($args)
{
$socket_path = @$args[0];
if ($this->trans->connect($socket_path)) {
return array("connected", 1);
} else {
return array("disconnected", 0);
}
}
//
// fsm States
//
public function setup($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
// someone else already started the stream
// even before "connect" was called must be bosh
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
//print_r($args);
return $this->handle_other($event, $args);
//return array("setup", 0);
break;
}
}
public function connected($event, $args)
{
switch ($event) {
case "start_stream":
$this->send_start_stream($this->jid);
return array("wait_for_stream_start", 1);
break;
// someone else already started the stream before us
// even before "start_stream" was called
// must be component
case "start_cb":
$stanza = $args[0];
return $this->handle_stream_start($stanza);
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("connected", 0);
break;
}
}
public function disconnected($event, $args)
{
switch ($event) {
case "connect":
return $this->do_connect($args);
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("disconnected", 0);
break;
}
}
public function wait_for_stream_start($event, $args)
{
switch ($event) {
case "start_cb":
// TODO: save stream id and other meta info
//_debug("stream started");
return "wait_for_stream_features";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_start", 0);
break;
}
}
// XEP-0170: Recommended Order of Stream Feature Negotiation
public function wait_for_stream_features($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// get starttls requirements
$starttls = $stanza->exists('starttls', NS_TLS);
if ($starttls) {
if ($this->force_tls) {
$required = true;
} else {
$required = $starttls->exists('required') ? true : false;
}
} else {
$required = false;
}
if ($starttls && $required) {
$this->send_starttls_pkt();
return "wait_for_tls_result";
}
// handle auth mech
$mechs = $stanza->exists('mechanisms', NS_SASL);
if ($mechs) {
$new_state = $this->handle_auth_mechs($stanza, $mechs);
return $new_state ? $new_state : "wait_for_sasl_response";
}
// post auth
$bind = $stanza->exists('bind', NS_BIND) ? true : false;
$sess = $stanza->exists('session', NS_SESSION) ? true : false;
$comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false;
if ($bind) {
$this->send_bind_pkt($this->resource);
return "wait_for_bind_response";
/*} elseif ($comp) {
// compression not supported due to bug in php stream filters
$this->send_compress_pkt("zlib");
return "wait_for_compression_result";
*/
} else {
_debug("no catch");
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_stream_features", 0);
break;
}
}
public function wait_for_tls_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) {
if ($this->trans->crypt()) {
$this->xml->reset_parser();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
} else {
$this->handle_auth_failure("tls-negotiation-failed");
return "logged_out";
}
} else {
// FIXME: here
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_tls_result", 0);
break;
}
}
public function wait_for_compression_result($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) {
$this->xml->reset_parser();
$this->trans->compress();
$this->send_start_stream($this->jid);
return "wait_for_stream_start";
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_compression_result", 0);
break;
}
}
public function wait_for_sasl_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) {
$reason = $stanza->childrens[0]->name;
//_debug("sasl failed with reason ".$reason."");
$this->handle_auth_failure($reason);
return "logged_out";
} elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_challenge_response($challenge);
return "wait_for_sasl_response";
} elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) {
$this->xml->reset_parser();
$this->send_start_stream(@$this->jid);
return "wait_for_stream_start";
} else {
_debug("got unhandled sasl response");
}
return "wait_for_sasl_response";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_sasl_response", 0);
break;
}
}
public function wait_for_bind_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// TODO: chk on id
if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result'
&& ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) {
$this->full_jid = new XMPPJid($jid->text);
$this->send_session_pkt();
return "wait_for_session_response";
} else {
// FIXME:
}
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_bind_response", 0);
break;
}
}
public function wait_for_session_response($event, $args)
{
switch ($event) {
case "stanza_cb":
$this->handle_auth_success();
return "logged_in";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("wait_for_session_response", 0);
break;
}
}
public function logged_in($event, $args)
{
switch ($event) {
case "stanza_cb":
$stanza = $args[0];
// call abstract
if ($stanza->name == 'message') {
$this->handle_message($stanza);
} elseif ($stanza->name == 'presence') {
$this->handle_presence($stanza);
} elseif ($stanza->name == 'iq') {
$this->handle_iq($stanza);
} else {
$this->handle_other($event, $args);
}
return "logged_in";
break;
case "end_cb":
$this->send_end_stream();
return "logged_out";
break;
case "end_stream":
$this->send_end_stream();
return "logged_out";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
default:
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_in", 0);
break;
}
}
public function logged_out($event, $args)
{
switch ($event) {
case "end_cb":
$this->trans->disconnect();
return "disconnected";
break;
case "end_stream":
return "disconnected";
break;
case "disconnect":
$this->trans->disconnect();
return "disconnected";
break;
case "connect":
return $this->do_connect($args);
break;
default:
// exit for any other event in logged_out state
_debug("uncatched $event");
return $this->handle_other($event, $args);
//return array("logged_out", 0);
break;
}
}
}
diff --git a/xmpp/xmpp_xep.php b/xmpp/xmpp_xep.php
index 4188b0c..28a3431 100644
--- a/xmpp/xmpp_xep.php
+++ b/xmpp/xmpp_xep.php
@@ -1,65 +1,67 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
*
* @author abhinavsingh
*
*/
abstract class XMPPXep
{
// init() method defines various callbacks
// required by this xep extension
abstract public function init();
//abstract public $description;
//abstract public $dependencies;
- // reference to jaxl instance
- // which required me
+ /**
+ * Reference to JAXL instance which required me.
+ * @var JAXL
+ */
protected $jaxl = null;
- public function __construct($jaxl)
+ public function __construct(JAXL $jaxl)
{
$this->jaxl = $jaxl;
}
public function __destruct()
{
}
}
|
jaxl/JAXL | 370555ec6abe952dbfc5b281f381566a33b2690a | Fix check of colorize | diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php
index 88843e5..0738133 100644
--- a/core/jaxl_logger.php
+++ b/core/jaxl_logger.php
@@ -1,97 +1,97 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// log level
define('JAXL_ERROR', 1);
define('JAXL_WARNING', 2);
define('JAXL_NOTICE', 3);
define('JAXL_INFO', 4);
define('JAXL_DEBUG', 5);
// generic global logging shortcuts for different level of verbosity
function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); }
function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); }
function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); }
function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); }
function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); }
// generic global terminal output colorize method
// finally sends colorized message to terminal using error_log/1
// this method is mainly to escape $msg from file:line and time
// prefix done by _debug, _error, ... methods
function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); }
class JAXLLogger {
public static $colorize = true;
public static $level = JAXL_DEBUG;
public static $path = null;
public static $max_log_size = 1000;
protected static $colors = array(
1 => 31, // error: red
2 => 34, // warning: blue
3 => 33, // notice: yellow
4 => 32, // info: green
5 => 37 // debug: white
);
public static function log($msg, $verbosity=1) {
if($verbosity <= self::$level) {
$bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt);
$msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg;
$size = strlen($msg);
if($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...';
if(isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path);
else error_log(self::colorize($msg, $verbosity));
}
}
public static function colorize($msg, $verbosity) {
if (self::$colorize) {
+ return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m";
+ } else {
return $msg;
}
-
- return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m";
}
}
?>
|
jaxl/JAXL | dc51d6154d15a53627ed0bffbb78c3d075ee9b3e | The protocol directive from cfg should not be empty | diff --git a/jaxl.php b/jaxl.php
index 9a8367e..f677452 100644
--- a/jaxl.php
+++ b/jaxl.php
@@ -1,812 +1,813 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2012, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
date_default_timezone_set("UTC");
declare(ticks = 1);
define('JAXL_CWD', dirname(__FILE__));
require_once JAXL_CWD.'/core/jaxl_exception.php';
require_once JAXL_CWD.'/core/jaxl_cli.php';
require_once JAXL_CWD.'/core/jaxl_loop.php';
require_once JAXL_CWD.'/xmpp/xmpp_stream.php';
require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php';
require_once JAXL_CWD.'/core/jaxl_event.php';
require_once JAXL_CWD.'/core/jaxl_logger.php';
require_once JAXL_CWD.'/core/jaxl_socket_server.php';
/**
* Jaxl class extends base XMPPStream class with following functionalities:
* 1) Adds an event based wrapper over xmpp stream lifecycle
* 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream
* 3) Roster management as specified in XMPP-IM
* 4) Management of XEP's inside xmpp stream lifecycle
* 5) Adds a logging facility
* 6) Adds a cron job facility in sync with connected xmpp stream timeline
*
* @author abhinavsingh
*
*/
class JAXL extends XMPPStream {
// lib meta info
const version = '3.0.1';
const name = 'JAXL :: Jabber XMPP Library';
// cached init config array
public $cfg = array();
// event callback engine for xmpp stream lifecycle
protected $ev = null;
// reference to various xep instance objects
public $xeps = array();
// local cache of roster list
public $roster = array();
// whether jaxl must also populate local roster cache with
// received presence information about the contacts
public $manage_roster = true;
// what to do with presence sub requests
// "none" | "accept" | "mutual"
public $manage_subscribe = "none";
// path variables
public $log_level = JAXL_INFO;
public $priv_dir;
public $tmp_dir;
public $log_dir;
public $pid_dir;
public $sock_dir;
// ipc utils
private $sock;
private $cli;
// env
public $local_ip;
public $pid;
public $mode;
// current status message
public $status;
// identity
public $features = array();
public $category = 'client';
public $type = 'bot';
public $lang = 'en';
// after cth failed attempt
// retry connect after k * $retry_interval seconds
// where k is a random number between 0 and 2^c - 1.
public $retry = true;
private $retry_interval = 1;
private $retry_attempt = 0;
private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries)
public function __construct($config) {
$this->cfg = $config;
// setup logger
if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path'];
//else JAXLLogger::$path = $this->log_dir."/jaxl.log";
if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level'];
else JAXLLogger::$level = $this->log_level;
// env
$strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE;
if($strict) $this->add_exception_handlers();
$this->mode = PHP_SAPI;
$this->local_ip = gethostbyname(php_uname('n'));
$this->pid = getmypid();
// jid object
$jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null;
// handle signals
if(extension_loaded('pcntl')) {
pcntl_signal(SIGHUP, array($this, 'signal_handler'));
pcntl_signal(SIGINT, array($this, 'signal_handler'));
pcntl_signal(SIGTERM, array($this, 'signal_handler'));
}
// create .jaxl directory in JAXL_CWD
// for our /tmp, /run and /log folders
// overwrite these using jaxl config array
$this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl";
$this->tmp_dir = $this->priv_dir."/tmp";
$this->pid_dir = $this->priv_dir."/run";
$this->log_dir = $this->priv_dir."/log";
$this->sock_dir = $this->priv_dir."/sock";
if(!is_dir($this->priv_dir)) mkdir($this->priv_dir);
if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir);
if(!is_dir($this->pid_dir)) mkdir($this->pid_dir);
if(!is_dir($this->log_dir)) mkdir($this->log_dir);
if(!is_dir($this->sock_dir)) mkdir($this->sock_dir);
// touch pid file
if($this->mode == "cli") {
touch($this->get_pid_file_path());
_info("created pid file ".$this->get_pid_file_path());
}
// include mandatory xmpp xeps
// service discovery and entity caps
// are recommended for every xmpp entity
$this->require_xep(array('0030', '0115'));
// do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified
$host = @$this->cfg['host'];
$port = @$this->cfg['port'];
if((!$host || !$port) && $jid) {
// this dns lookup is blocking
_info("dns srv lookup for ".$jid->domain);
list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
}
$this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host;
$this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port;
// choose appropriate transport
// if 'bosh_url' cfg is defined include 0206
if(@$this->cfg['bosh_url']) {
_debug("including bosh xep");
$this->require_xep('0206');
$transport = $this->xeps['0206'];
}
else {
//list($host, $port) = JAXLUtil::get_dns_srv($jid->domain);
$stream_context = @$this->cfg['stream_context'];
$transport = new JAXLSocketClient($stream_context);
}
// lifecycle events callback
$this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array());
// initialize xmpp stream with configured transport
parent::__construct(
$transport,
$jid,
@$this->cfg['pass'],
@$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()),
@$this->cfg['force_tls']
);
}
public function __destruct() {
// delete pid file
_info("cleaning up pid and unix sock files");
@unlink($this->get_pid_file_path());
@unlink($this->get_sock_file_path());
parent::__destruct();
}
public function add_exception_handlers() {
_info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this");
set_error_handler(array('JAXLException', 'error_handler'));
set_exception_handler(array('JAXLException', 'exception_handler'));
register_shutdown_function(array('JAXLException', 'shutdown_handler'));
}
public function get_pid_file_path() {
return $this->pid_dir."/jaxl_".$this->pid.".pid";
}
public function get_sock_file_path() {
return $this->sock_dir."/jaxl_".$this->pid.".sock";
}
public function require_xep($xeps) {
if(!is_array($xeps))
$xeps = array($xeps);
foreach($xeps as $xep) {
$filename = 'xep_'.$xep.'.php';
$classname = 'XEP_'.$xep;
// include xep
require_once JAXL_CWD.'/xep/'.$filename;
$this->xeps[$xep] = new $classname($this);
// add necessary requested callback on events
foreach($this->xeps[$xep]->init() as $ev=>$cb) {
$this->add_cb($ev, array($this->xeps[$xep], $cb));
}
}
}
public function add_cb($ev, $cb, $pri=1) {
return $this->ev->add($ev, $cb, $pri);
}
public function del_cb($ref) {
$this->ev->del($ref);
}
public function set_status($status, $show='chat', $priority=10) {
$this->send($this->get_pres_pkt(
array(),
$status,
$show,
$priority
));
}
public function send_chat_msg($to, $body, $thread=null, $subject=null) {
$msg = new XMPPMsg(
array(
'type'=>'chat',
'to'=>$to,
'from'=>$this->full_jid->to_string()
),
$body,
$thread,
$subject
);
$this->send($msg);
}
public function get_vcard($jid=null, $cb=null) {
$attrs = array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
);
if($jid) {
$jid = new XMPPJid($jid);
$attrs['to'] = $jid->node."@".$jid->domain;
}
$pkt = $this->get_iq_pkt(
$attrs,
new JAXLXml('vCard', 'vcard-temp')
);
if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb);
$this->send($pkt);
}
public function get_roster($cb=null) {
$pkt = $this->get_iq_pkt(
array(
'type'=>'get',
'from'=>$this->full_jid->to_string()
),
new JAXLXml('query', 'jabber:iq:roster')
);
if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb);
$this->send($pkt);
}
public function subscribe($to) {
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribe')
));
}
public function subscribed($to) {
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'subscribed')
));
}
public function unsubscribe($to) {
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribe')
));
}
public function unsubscribed($to) {
$this->send($this->get_pres_pkt(
array('to'=>$to, 'type'=>'unsubscribed')
));
}
public function get_socket_path() {
$protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp");
- if (@$this->cfg['protocol'])
+ if (!empty($this->cfg['protocol'])) {
$protocol = $this->cfg['protocol'];
+ }
return $protocol."://".$this->cfg['host'].":".$this->cfg['port'];
}
public function retry() {
$retry_after = pow(2, $this->retry_attempt) * $this->retry_interval;
$this->retry_attempt++;
_info("Will try to restart in ".$retry_after." seconds");
// TODO: use jaxl cron if sigalarms cannnot be used
sleep($retry_after);
$this->start();
}
public function start($opts=array()) {
// is bosh bot?
if(@$this->cfg['bosh_url']) {
$this->trans->session_start();
for(;;) {
// while any of the curl request is pending
// keep receiving response
while(sizeof($this->trans->chs) != 0) {
$this->trans->recv();
}
// if no request in queue, ping bosh end point
// and repeat recv
$this->trans->ping();
}
$this->trans->session_end();
return;
}
// is xmpp client or component?
// if on_connect event have no callbacks
// set default on_connect callback to $this->start_stream()
// i.e. xmpp client mode
if(!$this->ev->exists('on_connect'))
$this->add_cb('on_connect', array($this, 'start_stream'));
// connect to the destination host/port
if($this->connect($this->get_socket_path())) {
// reset in case we connected back after retries
$this->retry_attempt = 0;
// emit
$this->ev->emit('on_connect');
// parse opts
if(@$opts['--with-debug-shell']) $this->enable_debug_shell();
if(@$opts['--with-unix-sock']) $this->enable_unix_sock();
// run main loop
JAXLLoop::run();
// emit
$this->ev->emit('on_disconnect');
}
// if connection to the destination fails
else {
if($this->trans->errno == 61
|| $this->trans->errno == 110
|| $this->trans->errno == 111
) {
_debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")");
$this->retry();
}
else {
$this->ev->emit('on_connect_error', array(
$this->trans->errno,
$this->trans->errstr
));
}
}
}
//
// callback methods
//
// signals callback handler
// not for public api consumption
public function signal_handler($sig) {
$this->end_stream();
$this->disconnect();
$this->ev->emit('on_disconnect');
switch($sig) {
// terminal line hangup
case SIGHUP:
_debug("got sighup");
break;
// interrupt program
case SIGINT:
_debug("got sigint");
break;
// software termination signal
case SIGTERM:
_debug("got sigterm");
break;
}
exit;
}
// called internally for ipc
// not for public consumption
public function on_unix_sock_accept($_c, $addr) {
$this->sock->read($_c);
}
// this currently simply evals the incoming raw string
// know what you are doing while in production
public function on_unix_sock_request($_c, $_raw) {
_debug("evaling raw string rcvd over unix sock: ".$_raw);
$this->sock->send($_c, serialize(eval($_raw)));
$this->sock->read($_c);
}
public function enable_unix_sock() {
$this->sock = new JAXLSocketServer(
'unix://'.$this->get_sock_file_path(),
array(&$this, 'on_unix_sock_accept'),
array(&$this, 'on_unix_sock_request')
);
}
// this simply eval the incoming raw data
// inside current jaxl environment
// security is all upto you, no checks made here
public function handle_debug_shell($_raw) {
print_r(eval($_raw));
echo PHP_EOL;
JAXLCli::prompt();
}
protected function enable_debug_shell() {
$this->cli = new JAXLCli(array(&$this, 'handle_debug_shell'));
JAXLCli::prompt();
}
//
// abstract method implementation
//
protected function send_fb_challenge_response($challenge) {
$this->send($this->get_fb_challenge_response_pkt($challenge));
}
// refer https://developers.facebook.com/docs/chat/#jabber
public function get_fb_challenge_response_pkt($challenge) {
$stanza = new JAXLXml('response', NS_SASL);
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_arr);
$response = http_build_query(array(
'method' => $challenge_arr['method'],
'nonce' => $challenge_arr['nonce'],
'access_token' => $this->cfg['fb_access_token'],
'api_key' => $this->cfg['fb_app_key'],
'call_id' => 0,
'v' => '1.0'
));
$stanza->t(base64_encode($response));
return $stanza;
}
public function wait_for_fb_sasl_response($event, $args) {
switch($event) {
case "stanza_cb":
$stanza = $args[0];
if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$this->send_fb_challenge_response($challenge);
return "wait_for_sasl_response";
}
else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// someday this needs to go inside xmpp stream
public function wait_for_cram_md5_response($event, $args) {
switch($event) {
case "stanza_cb":
$stanza = $args[0];
if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = base64_decode($stanza->text);
$resp = new JAXLXml('response', NS_SASL);
$resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass)));
$this->send($resp);
return "wait_for_sasl_response";
}
else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
// http://tools.ietf.org/html/rfc5802#section-5
public function get_scram_sha1_response($pass, $challenge) {
// it contains users iteration count i and the user salt
// also server will append it's own nonce to the one we specified
$decoded = $this->explode_data(base64_decode($challenge));
// r=,s=,i=
$nonce = $decoded['r'];
$salt = base64_decode($decoded['s']);
$iteration = intval($decoded['i']);
// SaltedPassword := Hi(Normalize(password), salt, i)
$salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$client_key = hash_hmac('sha1', $salted, "Client Key", true);
// StoredKey := H(ClientKey)
$stored_key = hash('sha1', $client_key, true);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof
$auth_message = '';
// ClientSignature := HMAC(StoredKey, AuthMessage)
$signature = hash_hmac('sha1', $stored_key, $auth_message, true);
// ClientProof := ClientKey XOR ClientSignature
$client_proof = $client_key ^ $signature;
$proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof);
return base64_encode($proof);
}
public function wait_for_scram_sha1_response($event, $args) {
switch($event) {
case "stanza_cb":
$stanza = $args[0];
if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) {
$challenge = $stanza->text;
$resp = new JAXLXml('response', NS_SASL);
$resp->t($this->get_scram_sha1_response($this->pass, $challenge));
$this->send($resp);
return "wait_for_sasl_response";
}
else {
_debug("got unhandled sasl response, should never happen here");
exit;
}
break;
default:
_debug("not catched $event, should never happen here");
exit;
break;
}
}
public function handle_auth_mechs($stanza, $mechanisms) {
if($this->ev->exists('on_stream_features')) {
return $this->ev->emit('on_stream_features', array($stanza));
}
// extract available mechanisms
$mechs = array();
if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true;
// check if preferred auth type exists in available mechanisms
$pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN';
$pref_auth_exists = isset($mechs[$pref_auth]) ? true : false;
_debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists"));
// if pref auth exists, try it
if($pref_auth_exists) {
$mech = $pref_auth;
}
// if pref auth doesn't exists, choose one from available mechanisms
else {
foreach($mechs as $mech=>$any) {
// choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available
if($mech == 'X-FACEBOOK-PLATFORM') {
if(@$this->cfg['fb_access_token']) {
break;
}
}
// else try first of the available methods
else {
break;
}
}
_error("preferred auth type not supported, trying $mech");
}
$this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass);
if($pref_auth == 'X-FACEBOOK-PLATFORM') {
return "wait_for_fb_sasl_response";
}
else if($pref_auth == 'CRAM-MD5') {
return "wait_for_cram_md5_response";
}
else if($pref_auth == 'SCRAM-SHA-1') {
return "wait_for_scram_sha1_response";
}
}
public function handle_auth_success() {
// if not a component
/*if(!@$this->xeps['0114']) {
$this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info'));
$this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items'));
}*/
$this->ev->emit('on_auth_success');
}
public function handle_auth_failure($reason) {
$this->ev->emit('on_auth_failure', array(
$reason
));
}
public function handle_stream_start($stanza) {
$stanza = new XMPPStanza($stanza);
$this->ev->emit('on_stream_start', array($stanza));
return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1);
}
public function handle_iq($stanza) {
$stanza = new XMPPStanza($stanza);
// emit callback registered on stanza id's
$emited = false;
if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) {
//_debug("on stanza id callbackd");
$emited = true;
$this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza));
}
// catch roster list
if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) {
foreach($query->childrens as $child) {
if($child->name == 'item') {
$jid = $child->attrs['jid'];
$subscription = $child->attrs['subscription'];
$groups = array();
foreach($child->childrens as $group) {
if($group->name == 'group') {
$groups[] = $group->text;
}
}
$this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups);
}
}
// emit this event if not emited above
if(!$emited)
$this->ev->emit('on_roster_update');
}
// if managing roster
// catch contact vcard results
if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) {
if(@$this->roster[$stanza->from])
$this->roster[$stanza->from]->vcard = $query;
}
// on_get_iq, on_result_iq, and other events are only
// emitted if on_stanza_id_{id} wasn't emitted above
// TODO: can we add more checks here before calling back
// e.g. checks on existence of an attribute, check on 1st level child ns and so on
if(!$emited)
$this->ev->emit('on_'.$stanza->type.'_iq', array($stanza));
}
public function handle_presence($stanza) {
$stanza = new XMPPStanza($stanza);
// if managing roster
// catch available/unavailable type stanza
if($this->manage_roster) {
$type = ($stanza->type ? $stanza->type : "available");
$jid = new XMPPJid($stanza->from);
if($type == 'available') {
$this->roster[$jid->bare]->resources[$jid->resource] = $stanza;
}
else if($type == 'unavailable') {
if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource])
unset($this->roster[$jid->bare]->resources[$jid->resource]);
}
}
// if managing subscription requests
// we need to automate stuff here
if($stanza->type == "subscribe" && $this->manage_subscribe != "none") {
$this->subscribed($stanza->from);
if($this->manage_subscribe == "mutual")
$this->subscribe($stanza->from);
}
$this->ev->emit('on_presence_stanza', array($stanza));
}
public function handle_message($stanza) {
$stanza = new XMPPStanza($stanza);
$stanza->type = (@$stanza->type ? $stanza->type : 'normal');
$this->ev->emit('on_'.$stanza->type.'_message', array($stanza));
}
// unhandled event and arguments bubbled up
// TODO: in a lot of cases this will be called, need more checks
public function handle_other($event, $args) {
$stanza = @$args[0];
$stanza = new XMPPStanza($stanza);
$ev = 'on_'.$stanza->name.'_stanza';
if($this->ev->exists($ev)) {
return $this->ev->emit($ev, array($stanza));
}
else {
_warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name);
}
}
public function handle_domain_info($stanza) {
$query = $stanza->exists('query', NS_DISCO_INFO);
foreach($query->childrens as $k=>$child) {
if($child->name == 'identity') {
//echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL;
}
else if($child->name == 'x') {
//echo 'x ns:'.$child->ns.PHP_EOL;
}
else if($child->name == 'feature') {
//echo 'feature var:'.$child->attrs['var'].PHP_EOL;
}
}
}
public function handle_domain_items($stanza) {
$query = $stanza->exists('query', NS_DISCO_ITEMS);
foreach($query->childrens as $k=>$child) {
if($child->name == 'item') {
//echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL;
}
}
}
}
?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.