autometal-piwik 0.4.4 → 0.6.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/LICENSE ADDED
@@ -0,0 +1,4 @@
1
+ No-Copyright (c)
2
+
3
+ You have all the Copyright. This code is yours.
4
+
@@ -0,0 +1,88 @@
1
+ # autometal-piwik
2
+ * https://github.com/Achillefs/autometal-piwik
3
+ * http://humbuckercode.co.uk/licks/gems/piwik
4
+
5
+ ## DESCRIPTION:
6
+ A simple Ruby client for the Piwik API. This gem is based on Rodrigo Tassinari de Oliveira's piwik gem (https://github.com/riopro/piwik). Since it hasn't been updated since 2008, I took the liberty to fork it, and finish it up.
7
+
8
+ ## FEATURES/PROBLEMS:
9
+
10
+ * Object-oriented interface to the Piwik API;
11
+ * For now, only a small subset of the API is implemented (only basic actions)
12
+
13
+ ## SYNOPSIS:
14
+ Piwik is an open source web analytics software, written in PHP. It provides an
15
+ extensive REST-like API, and this gem aims to be a simple Ruby wrapper to access
16
+ this API in a Ruby-friendly way. For example:
17
+
18
+ require 'rubygems'
19
+ require 'piwik'
20
+ Piwik.auth_token = "i need to configure simple-piwik with my auth_token here"
21
+ Piwik.piwik_url = "http://piwik.mypiwikdomain.org"
22
+ site = Piwik::Site.load(1)
23
+ => #<Piwik::Site:0xb74bf994 @name="Example.com", @config={:auth_token=>"some_auth_key", :piwik_url=>"http://your.piwi.install"}, @id=1, @main_url="http://www.example.com", @created_at=Tue Jul 15 18:55:40 -0300 2008>
24
+ site.pageviews(:month, Date.today)
25
+ => 3002378
26
+ user = Piwik::User.load(1, 'http://piwik.mypiwikdomain.org', 'my_auth_key')
27
+ => #<Piwik::User:0xb66bf544 @login="Example.com", @config={:auth_token=>"some_auth_key", :piwik_url=>"http://your.piwi.install"}, @id=1, @main_url="http://www.example.com", @created_at=Tue Jul 15 18:55:40 -0300 2008>
28
+
29
+ Configuring with initializer config/initializers/simple-piwik.rb :
30
+
31
+ if Rails.env.production?
32
+ Piwik.piwik_url # "http://piwik.mypiwikdomain.org"
33
+ Piwik.auth_token # "2ad590308b1efa590a9a43ad86d3ac1s"
34
+ elsif Rails.env.development?
35
+ #this is currently set to the same as production
36
+ Piwik.piwik_url # "http://piwik.mypiwikdomain.org"
37
+ Piwik.auth_token # "2ad590308b1efa590a9a43ad86d3ac1s"
38
+ end
39
+
40
+ * Piwik website (http://piwik.org)
41
+ * Piwik API reference (http://dev.piwik.org/trac/wiki/API/Reference)
42
+
43
+ ## REQUIREMENTS:
44
+
45
+ activesupport, rest-client, json
46
+
47
+ ## INSTALL:
48
+
49
+ gem install simple-piwik
50
+
51
+ ## CHANGELOG:
52
+ * 0.6.1
53
+ New methods (pulled from [yehezkielbs' fork](https://github.com/Achillefs/autometal-piwik/pull/6))
54
+ * `Site#bounce_count`
55
+ * `Site#sum_visits_length`
56
+ * `Site#website_referrers`
57
+ * 0.6.0
58
+ Merged a few updates from [Mihael's fork](https://github.com/Achillefs/autometal-piwik/pull/5)
59
+ Gem now works with Rails 3.x, and the credentials specification strategy changed slightly
60
+ * 0.4.2
61
+ Final fix for inconsistent API outputs caused by Rails using its own version of XmlSimple.
62
+ * 0.4.1
63
+ Quick fixed api result parsing in site creation. The API's responses are inconsistent, but I am not sure why.
64
+ * 0.4.0
65
+ Added Piwik::Trackable controller mixing, pretty much swiped off of halfdan's piwik analytics project (https://github.com/halfdan/piwik_analytics/). The version included in this plugin is not suitable for application tracking, and is instead geared towards tracking multiple websites stored as ActiveRecord models
66
+ * 0.3.0
67
+ UsersManager CRUD implementation, with tests
68
+ * 0.2.3
69
+ Started adding some tests
70
+ * 0.2.0
71
+ Reworked plugin to also look for a rails config file called piwik.yml, and not just the .piwik user prefs file.
72
+ * 0.0.2 2008-07-22 (riopro)
73
+ * Added specs for existing API methods
74
+ * Created RubyForge project at http://rubyforge.org/projects/piwik/
75
+ * 0.0.1 2008-07-21 (riopro)
76
+ * major enhancement:
77
+ * Initial release
78
+
79
+ ## LICENSE:
80
+ (The MIT License)
81
+
82
+ Copyright © 2010-2013 Achillefs Charmpilas, Humbucker Ltd
83
+
84
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
85
+
86
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
87
+
88
+ THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile CHANGED
@@ -1,16 +1,33 @@
1
- require 'rubygems'
2
- gem 'hoe', '>= 2.1.0'
3
- require 'hoe'
4
- require 'fileutils'
5
- require './lib/piwik'
6
-
7
- Hoe.plugin :newgem
8
- $hoe = Hoe.spec 'autometal-piwik' do
9
- self.developer 'Achillefs Charmpilas', 'ac@humbuckercode.co.uk'
10
- self.post_install_message = File.read('PostInstall.txt')
11
- self.rubyforge_name = self.name
12
- self.extra_deps = [['activesupport','>= 2.3.8'],['xml-simple',">=1.0.11"],["rest-client",">= 1.6.1"]]
13
- end
14
-
15
- require 'newgem/tasks'
16
- Dir['tasks/**/*.rake'].each { |t| load t }
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "autometal-piwik"
8
+ gem.summary = %Q{A ruby client for the Piwik API.}
9
+ gem.description = %Q{Provides simple access to the Piwik API.}
10
+ gem.email = "ac@humbuckercode.co.uk"
11
+ gem.homepage = "https://github.com/Achillefs/autometal-piwik"
12
+ gem.authors = ['Achillefs Charmpilas', 'mihael']
13
+ gem.add_dependency "activesupport", ">= 3.0.9"
14
+ gem.add_dependency "rest-client", ">= 1.6.1"
15
+ gem.add_dependency "json", ">= 1.4.6"
16
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
17
+ end
18
+ rescue LoadError
19
+ puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
20
+ end
21
+
22
+ require 'rake/testtask'
23
+ Rake::TestTask.new(:test) do |test|
24
+ test.libs << 'lib' << 'test'
25
+ test.pattern = 'test/**/*_test.rb'
26
+ test.verbose = true
27
+ end
28
+
29
+ task :test => :check_dependencies
30
+
31
+ task :default => :test
32
+
33
+
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.6.1
@@ -1,50 +1,59 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
1
4
  # -*- encoding: utf-8 -*-
2
5
 
3
6
  Gem::Specification.new do |s|
4
7
  s.name = %q{autometal-piwik}
5
- s.version = "0.4.2"
8
+ s.version = "0.6.1"
6
9
 
7
10
  s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
8
- s.authors = ["Achillefs Charmpilas"]
9
- s.date = %q{2011-01-18}
10
- s.description = %q{A simple Ruby client for the Piwik API. This gem is based on Rodrigo Tassinari de Oliveira's piwik gem (https://github.com/riopro/piwik). Since it hasn't been updated since 2008, I took the liberty to fork it, and finish it up.}
11
- s.email = ["ac@humbuckercode.co.uk"]
12
- s.extra_rdoc_files = ["License.txt", "Manifest.txt", "PostInstall.txt", "Todo.txt"]
13
- s.files = ["License.txt", "Manifest.txt", "PostInstall.txt", "README.rdoc", "Rakefile", "Todo.txt", "autometal-piwik.gemspec", "lib/piwik.rb", "lib/piwik/base.rb", "lib/piwik/site.rb", "lib/piwik/trackable.rb", "lib/piwik/user.rb", "script/console", "script/destroy", "script/generate", "script/txt2html", "setup.rb", "test/files/config/piwik.yml", "test/piwik_test.rb", "test/test_helper.rb"]
14
- s.homepage = %q{http://github.com/Achillefs/tree/master}
15
- s.post_install_message = %q{
16
- For more information on piwik, see http://piwik.rubyforge.org or
17
- http://github.com/Achillefs/piwik/
18
-
19
- }
20
- s.rdoc_options = ["--main", "README.rdoc"]
11
+ s.authors = ["Achillefs Charmpilas", "mihael"]
12
+ s.date = %q{2013-01-05}
13
+ s.description = %q{Provides simple access to the Piwik API.}
14
+ s.email = %q{ac@humbuckercode.co.uk}
15
+ s.extra_rdoc_files = [
16
+ "LICENSE",
17
+ "README.md"
18
+ ]
19
+ s.files = [
20
+ ".document",
21
+ "LICENSE",
22
+ "README.md",
23
+ "Rakefile",
24
+ "VERSION",
25
+ "autometal-piwik.gemspec",
26
+ "lib/piwik.rb",
27
+ "lib/piwik/base.rb",
28
+ "lib/piwik/site.rb",
29
+ "lib/piwik/trackable.rb",
30
+ "lib/piwik/user.rb",
31
+ "script/console",
32
+ "test/files/config/example_piwik.yml",
33
+ "test/piwik_test.rb",
34
+ "test/test_helper.rb"
35
+ ]
36
+ s.homepage = %q{https://github.com/Achillefs/autometal-piwik}
21
37
  s.require_paths = ["lib"]
22
- s.rubyforge_project = %q{autometal-piwik}
23
- s.rubygems_version = %q{1.4.2}
24
- s.summary = %q{A simple Ruby client for the Piwik API}
25
- s.test_files = ["test/test_helper.rb"]
38
+ s.rubygems_version = %q{1.6.1}
39
+ s.summary = %q{A ruby client for the Piwik API.}
26
40
 
27
41
  if s.respond_to? :specification_version then
28
42
  s.specification_version = 3
29
43
 
30
44
  if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
31
- s.add_runtime_dependency(%q<activesupport>, [">= 2.3.8"])
32
- s.add_runtime_dependency(%q<xml-simple>, [">= 1.0.11"])
45
+ s.add_runtime_dependency(%q<activesupport>, [">= 3.0.9"])
33
46
  s.add_runtime_dependency(%q<rest-client>, [">= 1.6.1"])
34
- s.add_development_dependency(%q<rubyforge>, [">= 2.0.4"])
35
- s.add_development_dependency(%q<hoe>, [">= 2.6.2"])
47
+ s.add_runtime_dependency(%q<json>, [">= 1.4.6"])
36
48
  else
37
- s.add_dependency(%q<activesupport>, [">= 2.3.8"])
38
- s.add_dependency(%q<xml-simple>, [">= 1.0.11"])
49
+ s.add_dependency(%q<activesupport>, [">= 3.0.9"])
39
50
  s.add_dependency(%q<rest-client>, [">= 1.6.1"])
40
- s.add_dependency(%q<rubyforge>, [">= 2.0.4"])
41
- s.add_dependency(%q<hoe>, [">= 2.6.2"])
51
+ s.add_dependency(%q<json>, [">= 1.4.6"])
42
52
  end
43
53
  else
44
- s.add_dependency(%q<activesupport>, [">= 2.3.8"])
45
- s.add_dependency(%q<xml-simple>, [">= 1.0.11"])
54
+ s.add_dependency(%q<activesupport>, [">= 3.0.9"])
46
55
  s.add_dependency(%q<rest-client>, [">= 1.6.1"])
47
- s.add_dependency(%q<rubyforge>, [">= 2.0.4"])
48
- s.add_dependency(%q<hoe>, [">= 2.6.2"])
56
+ s.add_dependency(%q<json>, [">= 1.4.6"])
49
57
  end
50
58
  end
59
+
@@ -1,10 +1,6 @@
1
- $:.unshift(File.dirname(__FILE__)) unless
2
- $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
1
+ $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
3
2
 
4
3
  require 'piwik/base.rb'
5
4
  require 'piwik/site.rb'
6
5
  require 'piwik/user.rb'
7
- require 'piwik/trackable.rb'
8
- module Piwik
9
- VERSION = "0.4.4"
10
- end
6
+ require 'piwik/trackable.rb'
@@ -1,8 +1,8 @@
1
1
  require 'rubygems'
2
2
  require 'cgi'
3
- require 'active_support'
3
+ require 'active_support/all'
4
+ require 'json/ext'
4
5
  require 'rest_client'
5
- require 'xmlsimple'
6
6
 
7
7
  module Piwik
8
8
  class ApiError < StandardError; end
@@ -10,6 +10,13 @@ module Piwik
10
10
  class UnknownSite < ArgumentError; end
11
11
  class UnknownUser < ArgumentError; end
12
12
 
13
+ mattr_accessor :piwik_url
14
+ mattr_accessor :auth_token
15
+
16
+ def self.is_configured?
17
+ @@piwik_url!=nil && @@auth_token!=nil
18
+ end
19
+
13
20
  class Base
14
21
  @@template = <<-EOF
15
22
  # .piwik
@@ -22,15 +29,27 @@ module Piwik
22
29
  piwik_url:
23
30
  auth_token:
24
31
  EOF
25
- =begin rdoc
26
- This is required to normalize the API responses when the Rails XmlSimple version is used
27
- =end
28
- def self.parse_xml xml
29
- result = XmlSimple.xml_in(xml, {'ForceArray' => false})
30
- result = result['result'] if result['result']
31
- result
32
+
33
+ def self.config_file
34
+ if defined?(Rails.root) && Rails.root!=nil
35
+ # puts "config_file from Rails.root: #{Rails.root.to_s}"
36
+ Rails.root.join('config', 'piwik.yml')
37
+ # elsif defined?(RAILS_ROOT) && RAILS_ROOT!=nil
38
+ # puts "config_file from RAILS_ROOT: #{RAILS_ROOT}"
39
+ # File.join(RAILS_ROOT, 'config', 'piwik.yml')
40
+ else
41
+ # puts "config_file from ~/.piwik"
42
+ File.join( ENV['HOME'] || ENV['USERPROFILE'] || ENV['HOMEPATH'] || ".", '.piwik' )
43
+ end
44
+ end
45
+
46
+ def self.parse_json json
47
+ JSON.parse json
48
+ end
49
+
50
+ def parse_json json
51
+ self.class.parse_json json
32
52
  end
33
- def parse_xml xml; self.class.parse_xml xml; end
34
53
 
35
54
  private
36
55
  # Calls the supplied Piwik API method, with the supplied parameters.
@@ -44,49 +63,45 @@ EOF
44
63
 
45
64
  # Calls the supplied Piwik API method, with the supplied parameters.
46
65
  #
47
- # Returns a string containing the XML reply from Piwik, or raises a
66
+ # Returns the object parsed from JSON reply from Piwik, or raises a
48
67
  # <tt>Piwik::ApiError</tt> exception with the error message returned by Piwik
49
68
  # in case it receives an error.
50
69
  def self.call(method, params={}, piwik_url=nil, auth_token=nil)
51
- raise MissingConfiguration, "Please edit ~/.piwik to include your piwik url and auth_key" if piwik_url.nil? || auth_token.nil?
52
- url = "#{piwik_url}/?module=API&format=xml&method=#{method}"
70
+ raise MissingConfiguration, "Please edit #{config_file} to include your piwik url and auth_token or configure Piwik.piwik_url and Piwik.auth_token before use" if piwik_url.nil? || auth_token.nil?
71
+ url = "#{piwik_url}/?module=API&format=json&method=#{method}"
53
72
  url << "&token_auth=#{auth_token}" unless auth_token.nil?
54
73
  params.each { |k, v| url << "&#{k}=#{CGI.escape(v.to_s)}" }
55
74
  verbose_obj_save = $VERBOSE
56
75
  $VERBOSE = nil # Suppress "warning: peer certificate won't be verified in this SSL session"
57
- xml = RestClient.get(url)
76
+ json = RestClient.get(url)
58
77
  $VERBOSE = verbose_obj_save
59
- if xml =~ /error message=/
60
- result = XmlSimple.xml_in(xml, {'ForceArray' => false})
78
+ result = self.parse_json json
79
+ if json =~ /error message=/
61
80
  raise ApiError, result['error']['message'] if result['error']
62
81
  end
63
- xml
82
+ result
64
83
  end
65
84
 
66
85
  # Checks for the config, creates it if not found
67
- def self.load_config_from_file
86
+ def self.load_config
68
87
  config = {}
69
- if defined?(RAILS_ROOT) and RAILS_ROOT != nil
70
- home = RAILS_ROOT
71
- filename = "config/piwik.yml"
88
+ if Piwik.is_configured?
89
+ config = { :piwik_url => Piwik.piwik_url, :auth_token => Piwik.auth_token }
72
90
  else
73
- home = ENV['HOME'] || ENV['USERPROFILE'] || ENV['HOMEPATH'] || "."
74
- filename = ".piwik"
75
- end
76
- temp_config = if File.exists?(File.join(home,filename))
77
- YAML::load(open(File.join(home,filename)))
78
- else
79
- open(File.join(home,filename),'w') { |f| f.puts @@template }
80
- YAML::load(@@template)
81
- end
82
- temp_config.each { |k,v| config[k.to_sym] = v } if temp_config
83
- if config[:piwik_url] == nil || config[:auth_token] == nil
84
- if defined?(RAILS_ROOT) and RAILS_ROOT != nil
85
- raise MissingConfiguration, "Please edit ./config/piwik.yml to include your piwik url and auth_key"
86
- else
87
- raise MissingConfiguration, "Please edit ~/.piwik to include your piwik url and auth_key"
91
+ config_file = self.config_file
92
+ if config_file
93
+ temp_config = if File.exists?(config_file)
94
+ YAML::load(open(config_file))
95
+ else
96
+ open(config_file,'w') { |f| f.puts @@template }
97
+ YAML::load(@@template)
98
+ end
99
+ temp_config.each { |k,v| config[k.to_sym] = v } if temp_config
88
100
  end
89
-
101
+ raise MissingConfiguration, "Please edit #{config_file} to include piwik url and auth_token or configure Piwik.piwik_url and Piwik.auth_token before use" if config[:piwik_url] == nil || config[:auth_token] == nil
102
+ #cache settings
103
+ Piwik.piwik_url = config[:piwik_url]
104
+ Piwik.auth_token = config[:auth_token]
90
105
  end
91
106
  config
92
107
  end
@@ -16,7 +16,7 @@ module Piwik
16
16
  def initialize(attributes={}, piwik_url=nil, auth_token=nil)
17
17
  raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
18
18
  @config = if piwik_url.nil? || auth_token.nil?
19
- self.class.load_config_from_file
19
+ self.class.load_config
20
20
  else
21
21
  {:piwik_url => piwik_url, :auth_token => auth_token}
22
22
  end
@@ -35,7 +35,7 @@ module Piwik
35
35
  def self.load(site_id, piwik_url=nil, auth_token=nil)
36
36
  raise ArgumentError, "expected a site Id" if site_id.nil?
37
37
  @config = if piwik_url.nil? || auth_token.nil?
38
- load_config_from_file
38
+ load_config
39
39
  else
40
40
  {:piwik_url => piwik_url, :auth_token => auth_token}
41
41
  end
@@ -62,9 +62,8 @@ module Piwik
62
62
  raise ArgumentError, "Site already exists in Piwik, call 'update' instead" unless new?
63
63
  raise ArgumentError, "Name can not be blank" if name.blank?
64
64
  raise ArgumentError, "Main URL can not be blank" if main_url.blank?
65
- xml = call('SitesManager.addSite', :siteName => name, :urls => main_url)
66
- result = parse_xml(xml)
67
- @id = result.to_i
65
+ result = call('SitesManager.addSite', :siteName => name, :urls => main_url)
66
+ @id = result['value'].to_i
68
67
  @created_at = Time.current
69
68
  id && id > 0 ? true : false
70
69
  end
@@ -76,9 +75,8 @@ module Piwik
76
75
  raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
77
76
  raise ArgumentError, "Name can not be blank" if name.blank?
78
77
  raise ArgumentError, "Main URL can not be blank" if main_url.blank?
79
- xml = call('SitesManager.updateSite', :idSite => id, :siteName => name, :urls => main_url)
80
- result = parse_xml(xml)
81
- result['success'] ? true : false
78
+ result = call('SitesManager.updateSite', :idSite => id, :siteName => name, :urls => main_url)
79
+ result['result'] == 'success' ? true : false
82
80
  end
83
81
 
84
82
  def reload
@@ -90,10 +88,10 @@ module Piwik
90
88
  # Equivalent Piwik API call: SitesManager.deleteSite (idSite)
91
89
  def destroy
92
90
  raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
93
- xml = call('SitesManager.deleteSite', :idSite => id)
94
- result = parse_xml(xml)
91
+ result = call('SitesManager.deleteSite', :idSite => id)
92
+ #puts "\n destroy #{result} \n"
95
93
  freeze
96
- result['success'] ? true : false
94
+ result['result'] == 'success' ? true : false
97
95
  end
98
96
 
99
97
  # Gives read access (<tt>'view'</tt>) to the supplied user login for the current
@@ -114,7 +112,8 @@ module Piwik
114
112
  give_access_to(:noaccess, login)
115
113
  end
116
114
  alias_method :remove_access_from, :give_no_access_to
117
-
115
+
116
+
118
117
  # Returns a hash with a summary of access information for the current site
119
118
  # (visits, unique visitors, actions / pageviews, maximum actions per visit,
120
119
  # bounces and total time spent in all visits in seconds), filtered by the
@@ -126,8 +125,7 @@ module Piwik
126
125
  # Equivalent Piwik API call: VisitsSummary.get (idSite, period, date)
127
126
  def summary(period=:day, date=Date.today)
128
127
  raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
129
- xml = call('VisitsSummary.get', :idSite => id, :period => period, :date => date)
130
- result = parse_xml(xml)
128
+ result = call('VisitsSummary.get', :idSite => id, :period => period, :date => date)
131
129
  {
132
130
  :visits => result['nb_visits'].to_i,
133
131
  :unique_visitors => result['nb_uniq_visitors'].to_i,
@@ -147,9 +145,8 @@ module Piwik
147
145
  # Equivalent Piwik API call: VisitsSummary.getVisits (idSite, period, date)
148
146
  def visits(period=:day, date=Date.today)
149
147
  raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
150
- xml = call('VisitsSummary.getVisits', :idSite => id, :period => period, :date => date)
151
- result = parse_xml(xml)
152
- result.to_i
148
+ result = call('VisitsSummary.getVisits', :idSite => id, :period => period, :date => date)
149
+ result['value']
153
150
  end
154
151
 
155
152
  # Returns the amount of unique visitors for the current site, filtered by
@@ -161,9 +158,8 @@ module Piwik
161
158
  # Equivalent Piwik API call: VisitsSummary.getUniqueVisitors (idSite, period, date)
162
159
  def unique_visitors(period=:day, date=Date.today)
163
160
  raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
164
- xml = call('VisitsSummary.getUniqueVisitors', :idSite => id, :period => period, :date => date)
165
- result = parse_xml(xml)
166
- result.to_i
161
+ result = call('VisitsSummary.getUniqueVisitors', :idSite => id, :period => period, :date => date)
162
+ result['value']
167
163
  end
168
164
 
169
165
  # Returns the amount of actions (pageviews) for the current site, filtered
@@ -175,12 +171,68 @@ module Piwik
175
171
  # Equivalent Piwik API call: VisitsSummary.getActions (idSite, period, date)
176
172
  def actions(period=:day, date=Date.today)
177
173
  raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
178
- xml = call('VisitsSummary.getActions', :idSite => id, :period => period, :date => date)
179
- result = parse_xml(xml)
180
- result.to_i
174
+ result = call('VisitsSummary.getActions', :idSite => id, :period => period, :date => date)
175
+ result['value']
181
176
  end
182
177
  alias_method :pageviews, :actions
183
-
178
+
179
+ # Returns a string with the javascript tracking code for the current site.
180
+ #
181
+ # Equivalent Piwik API call: SitesManager.getJavascriptTag (idSite)
182
+ def get_javascript_tag
183
+ raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
184
+ result = call('SitesManager.getJavascriptTag', :idSite => id)
185
+ #puts "get_javascript_tag #{result.to_s}"
186
+ result['value']
187
+ end
188
+
189
+ # Returns a big Array of Hashes with all page titles along with standard Actions metrics for each row, for the current site.
190
+ #
191
+ # Example result:
192
+ # => [{"label"=>" Izdelava spletnih strani | Spletnik d.o.o.", "nb_visits"=>36, "nb_uniq_visitors"=>35, "nb_hits"=>41, "sum_time_spent"=>240, "entry_nb_uniq_visitors"=>"33", "entry_nb_visits"=>"36", "entry_nb_actions"=>"92", "entry_sum_visit_length"=>"3422", "entry_bounce_count"=>"20", "exit_nb_uniq_visitors"=>"19", "exit_nb_visits"=>"22", "avg_time_on_page"=>7, "bounce_rate"=>"56%", "exit_rate"=>"61%"}]
193
+ #
194
+ # Equivalent Piwik API call: Actions.getPageTitles (idSite, period, date, segment = '', expanded = '', idSubtable = '')
195
+ def get_page_titles(params={})
196
+ raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
197
+ result = call('Actions.getPageTitles', {:idSite => id, :period => :day, :date => Date.today, :segment => '', :expanded => '', :idSubtable => ''}.update(params))
198
+ #puts "get_page_titles: #{result}"
199
+ result
200
+ end
201
+
202
+ # Returns a big Array of Hashes with all page urls along with standard Actions metrics for each row, for the current site.
203
+ #
204
+ # Example result:
205
+ # => [{"label"=>"spletnik", "nb_visits"=>69, "nb_hits"=>87, "sum_time_spent"=>4762, "entry_nb_visits"=>40, "entry_nb_actions"=>101, "entry_sum_visit_length"=>6752, "entry_bounce_count"=>26, "exit_nb_visits"=>39, "avg_time_on_page"=>69, "bounce_rate"=>"65%", "exit_rate"=>"57%", "idsubdatatable"=>1}]
206
+ #
207
+ # Example call:
208
+ #
209
+ # Piwik::Site.load(203).get_page_urls(:expanded=>1)
210
+ #
211
+ # Equivalent Piwik API call: Actions.getPageUrls (idSite, period, date, segment = '', expanded = '', idSubtable = '')
212
+ def get_page_urls(params={})
213
+ raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
214
+ result = call('Actions.getPageUrls', { :idSite => id, :period => :day, :date => Date.today, :segment => '', :expanded => '', :idSubtable => '' }.update(params))
215
+ #puts "get_page_urls: #{result}"
216
+ result
217
+ end
218
+
219
+ def bounce_count(period=:day, date=Date.today)
220
+ raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
221
+ result = call('VisitsSummary.getBounceCount', :idSite => id, :period => period, :date => date)
222
+ result['value']
223
+ end
224
+
225
+ def sum_visits_length(period=:day, date=Date.today)
226
+ raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
227
+ result = call('VisitsSummary.getSumVisitsLength', :idSite => id, :period => period, :date => date)
228
+ result['value']
229
+ end
230
+
231
+ def website_referrers(period=:day, date=Date.today)
232
+ raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
233
+ call('Referers.getWebsites', :idSite => id, :period => period, :date => date)
234
+ end
235
+
184
236
  private
185
237
  # Loads the attributes in the instance variables.
186
238
  def load_attributes(attributes)
@@ -198,9 +250,9 @@ module Piwik
198
250
  # Equivalent Piwik API call: UsersManager.setUserAccess (userLogin, access, idSites)
199
251
  def give_access_to(access, login)
200
252
  raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
201
- xml = call('UsersManager.setUserAccess', :idSites => id, :access => access.to_s, :userLogin => login.to_s)
202
- result = parse_xml(xml)
203
- result['success'] ? true : false
253
+ result = call('UsersManager.setUserAccess', :idSites => id, :access => access.to_s, :userLogin => login.to_s)
254
+ #result['success'] ? true : false
255
+ result['result'] == 'success' ? true : false
204
256
  end
205
257
 
206
258
  # Returns a hash with the attributes of the supplied site, identified
@@ -208,15 +260,17 @@ module Piwik
208
260
  #
209
261
  # Equivalent Piwik API call: SitesManager.getSiteFromId (idSite)
210
262
  def self.get_site_attributes_by_id(site_id, piwik_url, auth_token)
211
- xml = call('SitesManager.getSiteFromId', {:idSite => site_id}, piwik_url, auth_token)
212
- result = parse_xml(xml)
263
+ result = call('SitesManager.getSiteFromId', {:idSite => site_id}, piwik_url, auth_token)
264
+ #puts "get_site_attributes_by_id #{result.to_s}"
265
+ raise UnknownSite, "Site not existent in Piwik" if result.kind_of?(Hash) && result['value'] == false
213
266
  attributes = {
214
- :id => result['row']['idsite'].to_i,
215
- :name => result['row']['name'],
216
- :main_url => result['row']['main_url'],
217
- :created_at => Time.parse(result['row']['ts_created'])
267
+ :id => result[0]['idsite'].to_i,
268
+ :name => result[0]['name'],
269
+ :main_url => result[0]['main_url'],
270
+ :created_at => Time.parse(result[0]['ts_created'])
218
271
  }
219
272
  attributes
220
273
  end
274
+
221
275
  end
222
276
  end