repo
string
commit
string
message
string
diff
string
jcoglan/jsclass
79f0a465a56e8890ada8d41edbc3d117e208738d
Add SlimerJS to list of supported platforms.
diff --git a/site/src/pages/platforms.haml b/site/src/pages/platforms.haml index 416579e..a4a9c41 100644 --- a/site/src/pages/platforms.haml +++ b/site/src/pages/platforms.haml @@ -1,46 +1,47 @@ :textile h2. Supported platforms One of the main goals of @jsclass@ is to help you write programs that work across a wide variety of JavaScript platforms. It does this by abstracting some platform-specific details such as "module loading":/packages.html, and by providing cross-platform "testing tools":http://jstest.jcoglan.com. @jsclass@ currently runs without modification on all the following environments: h3. Web browsers * "Chrome":http://www.google.com/chrome * "Firefox":http://www.getfirefox.com/ * "Internet Explorer":http://www.microsoft.com/windows/internet-explorer/default.aspx * "Opera":http://www.opera.com/ * "Safari":http://www.apple.com/safari/ h3. Headless DOM environments * "PhantomJS":http://www.phantomjs.org/ (both in the browser and the scripting runtime) + * "SlimerJS":http://slimerjs.org/ h3. Server-side platforms * "Node.js":http://nodejs.org/ * "Narwhal":http://narwhaljs.org/ * "RingoJS":http://ringojs.org/ h3. Database shells * "MongoDB":http://www.mongodb.org/ h3. GUI frameworks * "Mozilla XULRunner":https://developer.mozilla.org/en/xulrunner * "Adobe AIR":http://www.adobe.com/products/air/ h3. Shell environments * "V8 shell":http://code.google.com/p/v8/ * "Mozilla Rhino":http://www.mozilla.org/rhino/ * "Mozilla SpiderMonkey":http://www.mozilla.org/js/spidermonkey/ * "Windows Script Host":http://msdn.microsoft.com/en-us/library/9bbdkx3k(VS.85).aspx
jcoglan/jsclass
c0e2a8e79041331236430641414fd6479b416bb9
Remove license from source code.
diff --git a/source/core/_head.js b/source/core/_head.js index 4cd4fd8..4ffefe0 100644 --- a/source/core/_head.js +++ b/source/core/_head.js @@ -1,19 +1,17 @@ -<%- wake.comment(wake.file('LICENSE')) %> - var JS = (typeof this.JS === 'undefined') ? {} : this.JS; (function(factory) { var $ = (typeof this.global === 'object') ? this.global : this, E = (typeof exports === 'object'); if (E) { exports.JS = exports; JS = exports; } else { $.JS = JS; } factory($, JS); })(function(global, exports) { 'use strict'; diff --git a/source/package/_head.js b/source/package/_head.js index cf5388f..9e019b1 100644 --- a/source/package/_head.js +++ b/source/package/_head.js @@ -1,20 +1,18 @@ -<%- wake.comment(wake.file('LICENSE')) %> - var JS = (typeof this.JS === 'undefined') ? {} : this.JS; JS.Date = Date; (function(factory) { var $ = (typeof this.global === 'object') ? this.global : this, E = (typeof exports === 'object'); if (E) { exports.JS = exports; JS = exports; } else { $.JS = JS; } factory($, JS); })(function(global, exports) { 'use strict';
jcoglan/jsclass
7049ebaaf8cae1c033cfa92598f39f248f450b72
Rename the PhantomJS reporter to Headless and make it run on SlimerJS too.
diff --git a/package.json b/package.json index 0ac1c67..5ac2d32 100644 --- a/package.json +++ b/package.json @@ -1,182 +1,182 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures", "testing"] , "license" : "MIT" , "version" : "4.0.0" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/js.class.git" } , "bugs" : "http://github.com/jcoglan/js.class/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "layout": "apart", "builds": { "src": {"minify": false}, "min": {"minify": true, "sourceMap": "src"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", - "reporters/phantomjs", + "reporters/headless", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "benchmark": "", "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG": "", "index.js": "", "LICENSE": "", "package.json": "", "README.md": "" } } } } diff --git a/source/core/method.js b/source/core/method.js index f94ff6f..702100a 100644 --- a/source/core/method.js +++ b/source/core/method.js @@ -1,166 +1,166 @@ JS.Method = JS.makeClass(); JS.extend(JS.Method.prototype, { initialize: function(module, name, callable) { this.module = module; this.name = name; this.callable = callable; this._words = {}; if (typeof callable !== 'function') return; this.arity = callable.length; var matches = callable.toString().match(/\b[a-z\_\$][a-z0-9\_\$]*\b/ig), i = matches.length; while (i--) this._words[matches[i]] = true; }, setName: function(name) { this.callable.displayName = this.displayName = name; }, contains: function(word) { return this._words.hasOwnProperty(word); }, call: function() { return this.callable.call.apply(this.callable, arguments); }, apply: function(receiver, args) { return this.callable.apply(receiver, args); }, compile: function(environment) { var method = this, trace = method.module.__trace__ || environment.__trace__, callable = method.callable, words = method._words, allWords = JS.Method._keywords, i = allWords.length, keywords = [], keyword; while (i--) { keyword = allWords[i]; if (words[keyword.name]) keywords.push(keyword); } if (keywords.length === 0 && !trace) return callable; var compiled = function() { var N = keywords.length, j = N, previous = {}, keyword, existing, kwd; while (j--) { keyword = keywords[j]; existing = this[keyword.name]; if (existing && !existing.__kwd__) continue; previous[keyword.name] = { _value: existing, _own: this.hasOwnProperty(keyword.name) }; kwd = keyword.filter(method, environment, this, arguments); if (kwd) kwd.__kwd__ = true; this[keyword.name] = kwd; } var returnValue = callable.apply(this, arguments), j = N; while (j--) { keyword = keywords[j]; if (!previous[keyword.name]) continue; if (previous[keyword.name]._own) this[keyword.name] = previous[keyword.name]._value; else delete this[keyword.name]; } return returnValue; }; var StackTrace = trace && (exports.StackTrace || require('./stack_trace').StackTrace); if (trace) return StackTrace.wrap(compiled, method, environment); return compiled; }, toString: function() { var name = this.displayName || (this.module.toString() + '#' + this.name); return '#<Method:' + name + '>'; } }); JS.Method.create = function(module, name, callable) { if (callable && callable.__inc__ && callable.__fns__) return callable; var method = (typeof callable !== 'function') ? callable : new this(module, name, callable); this.notify(method); return method; }; JS.Method.compile = function(method, environment) { - return method && method.compile - ? method.compile(environment) - : method; + return (method instanceof this) + ? method.compile(environment) + : method; }; JS.Method.__listeners__ = []; JS.Method.added = function(block, context) { this.__listeners__.push([block, context]); }; JS.Method.notify = function(method) { var listeners = this.__listeners__, i = listeners.length, listener; while (i--) { listener = listeners[i]; listener[0].call(listener[1], method); } }; JS.Method._keywords = []; JS.Method.keyword = function(name, filter) { this._keywords.push({name: name, filter: filter}); }; JS.Method.tracing = function(classes, block, context) { var pkg = exports.require ? exports : require('./loader'); pkg.require('JS.StackTrace', function(StackTrace) { var logger = StackTrace.logger, active = logger.active; classes = [].concat(classes); this.trace(classes); logger.active = true; block.call(context); this.untrace(classes); logger.active = active; }, this); }; JS.Method.trace = function(classes) { var i = classes.length; while (i--) { classes[i].__trace__ = true; classes[i].resolve(); } }; JS.Method.untrace = function(classes) { var i = classes.length; while (i--) { classes[i].__trace__ = false; classes[i].resolve(); } }; diff --git a/source/test/reporters/headless.js b/source/test/reporters/headless.js new file mode 100644 index 0000000..43e52ad --- /dev/null +++ b/source/test/reporters/headless.js @@ -0,0 +1,40 @@ +// http://phantomjs.org/ +// http://slimerjs.org/ + +Test.Reporters.extend({ + Headless: new JS.Class({ + extend: { + UA: /\b(PhantomJS|SlimerJS)\b/ + }, + + initialize: function(options) { + this._options = options || {}; + + var format = Console.envvar('FORMAT'); + + if (Console.envvar('TAP')) format = format || 'tap'; + this._options.format = this._options.format || format; + + var R = Test.Reporters, + Printer = R.get(this._options.format) || R.Dot, + reporter = new R.Composite(); + + reporter.addReporter(new Printer(options)); + reporter.addReporter(new R.ExitStatus()); + + this._reader = new R.JSON.Reader(reporter); + }, + + open: function(url) { + var page = (typeof WebPage === 'function') ? new WebPage() : require('webpage').create(), + self = this; + + page.onConsoleMessage = function(message) { + if (!self._reader.read(message)) console.log(message); + }; + page.open(url); + return page; + } + }) +}); + diff --git a/source/test/reporters/json.js b/source/test/reporters/json.js index 8fcbf08..fa09f51 100644 --- a/source/test/reporters/json.js +++ b/source/test/reporters/json.js @@ -1,55 +1,55 @@ Test.Reporters.extend({ JSON: new JS.Class({ include: Console, _log: function(eventName, data) { if (!JS.ENV.JSON) return; this.puts(JSON.stringify({jstest: [eventName, data]})); }, extend: { create: function() { if (!JS.ENV.navigator) return; - if (/\bPhantomJS\b/.test(navigator.userAgent)) return new this(); + if (Test.Reporters.Headless.UA.test(navigator.userAgent)) return new this(); }, Reader: new JS.Class({ initialize: function(reporter) { this._reporter = new Test.Reporters.Composite([reporter]); }, read: function(message) { if (!JS.ENV.JSON) return false; try { var data = JSON.parse(message), payload = data.jstest, method = payload[0], event = payload[1]; this._reporter[method](event); return true; } catch (e) { return false; } } }) } }) }); (function() { var methods = Test.Reporters.METHODS, n = methods.length; while (n--) (function(i) { var method = methods[i]; Test.Reporters.JSON.define(method, function(event) { this._log(method, event); }); })(n); })(); Test.Reporters.register('json', Test.Reporters.JSON); diff --git a/source/test/reporters/phantomjs.js b/source/test/reporters/phantomjs.js deleted file mode 100644 index 15c161c..0000000 --- a/source/test/reporters/phantomjs.js +++ /dev/null @@ -1,27 +0,0 @@ -// http://phantomjs.org/ - -Test.Reporters.extend({ - PhantomJS: new JS.Class({ - initialize: function(options, page) { - this._options = options || {}; - - var format = Console.envvar('FORMAT'); - - if (Console.envvar('TAP')) format = format || 'tap'; - this._options.format = this._options.format || format; - - var R = Test.Reporters, - Printer = R.get(this._options.format) || R.Dot, - reporter = new R.Composite(), - bridge = new R.JSON.Reader(reporter); - - reporter.addReporter(new Printer(options)); - reporter.addReporter(new R.ExitStatus()); - - page.onConsoleMessage = function(m) { - if (!bridge.read(m)) console.log(m); - }; - } - }) -}); - diff --git a/test/phantom.js b/test/phantom.js index 602753f..fae0e7f 100644 --- a/test/phantom.js +++ b/test/phantom.js @@ -1,10 +1,8 @@ JSCLASS_PATH = '../build/src' var pkg = require(JSCLASS_PATH + '/loader') pkg.require('JS.Test', function(Test) { - var page = new WebPage(), - reporter = new Test.Reporters.PhantomJS({}, page) - - page.open('test/browser.html') + var reporter = new Test.Reporters.Headless() + reporter.open('test/browser.html') })
jcoglan/jsclass
cf46856d4a7f3e4ce6634a2b1bb2da79db2a7b82
Don't use the BrowserColor backend in Firefox by default. It works in Firebug, but not in Firefox's own console.
diff --git a/source/console/config.js b/source/console/config.js index fc1d0d9..b7935ad 100644 --- a/source/console/config.js +++ b/source/console/config.js @@ -1,32 +1,32 @@ Console.BROWSER = (typeof window !== 'undefined'); Console.NODE = (typeof process === 'object') && !Console.BROWSER; Console.PHANTOM = (typeof phantom !== 'undefined'); Console.AIR = (Console.BROWSER && typeof runtime !== 'undefined'); Console.RHINO = (typeof java !== 'undefined' && typeof java.lang !== 'undefined'); Console.WSH = (typeof WScript !== 'undefined'); var useColor = false, ua; if (Console.BROWSER) { ua = navigator.userAgent; - if (window.console && (/Firefox/.test(ua) || /Chrome/.test(ua))) + if (window.console && /Chrome/.test(ua)) useColor = true; } if (Console.PHANTOM) Console.adapter = new Console.Phantom(); else if (useColor) Console.adapter = new Console.BrowserColor(); else if (Console.BROWSER) Console.adapter = new Console.Browser(); else if (Console.NODE) Console.adapter = new Console.Node(); else if (Console.RHINO) Console.adapter = new Console.Rhino(); else if (Console.WSH) Console.adapter = new Console.Windows(); else Console.adapter = new Console.Base(); for (var type in Console.ESCAPE_CODES) { for (var key in Console.ESCAPE_CODES[type]) (function(type, key) { Console.define(key, function() { Console.adapter.format(type, key, arguments); }); })(type, key); } Console.extend(Console);
jcoglan/jsclass
c30309837eec441333a04d9a365abd508694713e
Make the BrowserColor Console backend not emit %c if there are no pending formatting instructions. This makes it emit output that's safe for colorless machine-readable formats like TAP.
diff --git a/source/console/browser_color.js b/source/console/browser_color.js index 27e2ca0..843bdda 100644 --- a/source/console/browser_color.js +++ b/source/console/browser_color.js @@ -1,65 +1,69 @@ Console.extend({ BrowserColor: new JS.Class(Console.Browser, { COLORS: { green: 'limegreen' }, __queue__: [], - __state__: {}, + __state__: null, format: function(type, name) { name = name.replace(/^bg/, ''); - var state = JS.extend({}, this.__state__), + var state = JS.extend({}, this.__state__ || {}), color = this.COLORS[name] || name, no = /^no/.test(name); if (type === 'reset') - state = {}; + state = null; else if (no) delete state[type]; else if (type === 'weight') state.weight = 'font-weight: ' + name; else if (type === 'style') state.style = 'font-style: ' + name; else if (type === 'underline') state.underline = 'text-decoration: underline'; else if (type === 'color') state.color = 'color: ' + color; else if (type === 'background') state.background = 'background-color: ' + color; else - state = null; + state = undefined; - if (state) { + if (state !== undefined) { this.__state__ = state; this.__queue__.push(state); } }, print: function(string) { this.__queue__.push(string) }, puts: function(string) { this.print(string); var buffer = '', formats = [], item; - while (item = this.__queue__.shift()) { + while ((item = this.__queue__.shift()) !== undefined) { if (typeof item === 'string') { - buffer += '%c' + item; - formats.push(this._serialize(this.__state__)); + if (this.__state__) { + buffer += '%c' + item; + formats.push(this._serialize(this.__state__)); + } else { + buffer += item; + } } else { this.__state__ = item; } } console.log.apply(console, [buffer].concat(formats)); }, _serialize: function(state) { var rules = []; for (var key in state) rules.push(state[key]); return rules.join('; '); } }) });
jcoglan/jsclass
fa92d93dd1e0039da844887af401e6bfa72d4306
Remove some unused code from the CommonJS module loader.
diff --git a/source/package/loaders/commonjs.js b/source/package/loaders/commonjs.js index e39aa63..461c3dd 100644 --- a/source/package/loaders/commonjs.js +++ b/source/package/loaders/commonjs.js @@ -1,33 +1,30 @@ Package.CommonJSLoader = { usable: function() { return typeof require === 'function' && typeof exports === 'object'; }, __FILE__: function() { return this._currentPath; }, loadFile: function(path, fireCallbacks) { - var file; + var file, module; if (typeof process !== 'undefined') { - var cwd = process.cwd(), - module = path.replace(/\.[^\.]+$/g, ''), - path = require('path'); - - file = path.resolve(module); + module = path.replace(/\.[^\.]+$/g, ''); + file = require('path').resolve(module); } else if (typeof phantom !== 'undefined') { file = phantom.libraryPath.replace(/\/$/, '') + '/' + path.replace(/^\//, ''); } this._currentPath = file + '.js'; var module = require(file); fireCallbacks(module); return module; } };
jcoglan/jsclass
428d0cfc65189be074b9f0ab28d8d82db754f91c
Rename readme.
diff --git a/README.markdown b/README.md similarity index 100% rename from README.markdown rename to README.md diff --git a/package.json b/package.json index d378b7d..0ac1c67 100644 --- a/package.json +++ b/package.json @@ -1,182 +1,182 @@ { "name" : "jsclass" , "description" : "Portable class library for JavaScript" , "homepage" : "http://jsclass.jcoglan.com" , "author" : "James Coglan <[email protected]> (http://jcoglan.com/)" , "keywords" : ["oop", "class", "data-structures", "testing"] , "license" : "MIT" , "version" : "4.0.0" , "engines" : {"node": ">=0.4.0"} , "main" : "./index" , "devDependencies" : {"wake": ""} , "scripts" : { "build" : "wake" , "clean" : "rm -rf build" , "pretest" : "npm run-script build" , "test" : "node test/console.js" } , "repository" : { "type" : "git" , "url" : "git://github.com/jcoglan/js.class.git" } , "bugs" : "http://github.com/jcoglan/js.class/issues" , "wake": { "javascript": { "sourceDirectory": "source", "targetDirectory": "build", "layout": "apart", "builds": { "src": {"minify": false}, "min": {"minify": true, "sourceMap": "src"} }, "targets": { "core": { "directory": "core", "files": [ "_head", "utils", "method", "module", "kernel", "class", "bootstrap", "keywords", "interface", "singleton", "_tail" ]}, "package-browser": { "directory": "package", "files": [ "_head", "package", "loaders/browser", "browser", "dsl", "_tail" ]}, "loader-browser": { "extend": "package-browser", "files": ["config"] }, "package": { "directory": "package", "files": [ "_head", "package", "loaders/commonjs", "loaders/browser", "loaders/rhino", "loaders/server", "loaders/wsh", "loaders/xulrunner", "loader", "dsl", "_tail" ]}, "loader": { "extend": "package", "files": ["config"] }, "test": { "directory": "test", "files": [ "_head", "unit", "unit/observable", "unit/assertions", "unit/assertion_message", "unit/failure", "unit/error", "unit/test_result", "unit/test_suite", "unit/test_case", "ui/terminal", "ui/browser", "reporters/error", "reporters/dot", "reporters/json", "reporters/tap", "reporters/exit_status", "reporters/phantomjs", "reporters/browser", "reporters/coverage", "reporters/composite", "reporters/test_swarm", "context/context", "context/life_cycle", "context/shared_behavior", "context/test", "context/suite", "mocking/stub", "mocking/parameters", "mocking/matchers", "mocking/dsl", "async_steps", "fake_clock", "coverage", "helpers", "runner", "_tail" ]}, "dom": { "directory": "dom", "files": [ "_head", "dom", "builder", "event", "_tail" ]}, "console": { "directory": "console", "files": [ "_head", "console", "base", "browser", "browser_color", "node", "phantom", "rhino", "windows", "config", "_tail" ]}, "benchmark": "", "comparable": "", "constant_scope": "", "enumerable": "", "deferrable": "", "observable": "", "forwardable": "", "method_chain": "", "decorator": "", "proxy": "", "command": "", "state": "", "linked_list": "", "hash": "", "range": "", "set": "", "stack_trace": "", "tsort": "" } }, "binary": { "sourceDirectory": ".", "targetDirectory": "build", "targets": { "src/assets/bullet_go.png": "source/assets/bullet_go.png", "min/assets/bullet_go.png": "source/assets/bullet_go.png", "src/assets/testui.css": "source/assets/testui.css", "min/assets/testui.css": "source/assets/testui.css", "CHANGELOG": "", "index.js": "", "LICENSE": "", "package.json": "", - "README.markdown": "" + "README.md": "" } } } }
rmatei/kt
22a7b7d95ca3f86a77f9bee314cd11d1e55be323
change kt_host to api.geo.kontagent.net
diff --git a/kontagent.yml.tpl b/kontagent.yml.tpl index 067abd8..f960177 100644 --- a/kontagent.yml.tpl +++ b/kontagent.yml.tpl @@ -1,142 +1,142 @@ # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. However, if your callback URL # is simply www.example.com/, this value should be left blank. # # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # -kt_host: api.kontagent.com +kt_host: api.geo.kontagent.net # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net # Parameter : use_ab # # Description: Set use_ab to true to enable ab_testing. You also need to be granted permissions in order # to have ab testing fully functional. # use_ab: false kt_disabled: false \ No newline at end of file diff --git a/kontagent.yml.tpl.multi b/kontagent.yml.tpl.multi index fa3850e..ecb99a7 100644 --- a/kontagent.yml.tpl.multi +++ b/kontagent.yml.tpl.multi @@ -1,140 +1,140 @@ <FACEBOOK_API_KEY>: kt_disabled: false # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false # Parameter : use_ab # # Description: Set use_ab to true to enable ab_testing. You also need to be granted permissions in order # to have ab testing fully functional. # use_ab: false ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # -kt_host: api.kontagent.com +kt_host: api.geo.kontagent.net # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net
rmatei/kt
c9d4db701fa7b3797df641e6ec571882bf07f0b9
math.uuid was returning a 36 char string. Change to have it return a 32 char string.
diff --git a/kt_common.js b/kt_common.js index f328330..32afc20 100644 --- a/kt_common.js +++ b/kt_common.js @@ -1,310 +1,310 @@ /* * Generate a random uuid. * * USAGE: Math.uuid(length, radix) * length - the desired number of characters * radix - the number of allowable values for each character. * * EXAMPLES: * // No arguments - returns RFC4122, version 4 ID * >>> Math.uuid() * "92329D39-6F5C-4520-ABFC-AAB64544E172" * * // One argument - returns ID of the specified length * >>> Math.uuid(15) // 15 character ID (default base=62) * "VcydxgltxrVZSTV" * * // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62) * >>> Math.uuid(8, 2) // 8 character ID (base=2) * "01001010" * >>> Math.uuid(8, 10) // 8 character ID (base=10) * "47473046" * >>> Math.uuid(8, 16) // 8 character ID (base=16) * "098F4D35" */ Math.uuid = (function() { // Private array of chars to use var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); return function (len, radix) { var chars = CHARS, uuid = [], rnd = Math.random; radix = radix || chars.length; if (len) { // Compact form for (var i = 0; i < len; i++) uuid[i] = chars[0 | rnd()*radix]; } else { // rfc4122, version 4 form var r; // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = ''; uuid[14] = '4'; // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (var i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | rnd()*16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf]; } } } - - return uuid.join(''); + var ret = uuid.join(''); + return ret.substring(0, 32); }; })(); function urlencode( str ) { // http://kevin.vanzonneveld.net // + original by: Philip Peterson // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: AJ // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: travc // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Lars Fischer // + input by: Ratheous // % note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/ // * example 1: urlencode('Kevin van Zonneveld!'); // * returns 1: 'Kevin+van+Zonneveld%21' // * example 2: urlencode('http://kevin.vanzonneveld.net/'); // * returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F' // * example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'); // * returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a' var hash_map = {}, unicodeStr='', hexEscStr=''; var ret = (str+'').toString(); var replacer = function(search, replace, str) { var tmp_arr = []; tmp_arr = str.split(search); return tmp_arr.join(replace); }; // The hash_map is identical to the one in urldecode. hash_map["'"] = '%27'; hash_map['('] = '%28'; hash_map[')'] = '%29'; hash_map['*'] = '%2A'; hash_map['~'] = '%7E'; hash_map['!'] = '%21'; hash_map['%20'] = '+'; hash_map['\u00DC'] = '%DC'; hash_map['\u00FC'] = '%FC'; hash_map['\u00C4'] = '%D4'; hash_map['\u00E4'] = '%E4'; hash_map['\u00D6'] = '%D6'; hash_map['\u00F6'] = '%F6'; hash_map['\u00DF'] = '%DF'; hash_map['\u20AC'] = '%80'; hash_map['\u0081'] = '%81'; hash_map['\u201A'] = '%82'; hash_map['\u0192'] = '%83'; hash_map['\u201E'] = '%84'; hash_map['\u2026'] = '%85'; hash_map['\u2020'] = '%86'; hash_map['\u2021'] = '%87'; hash_map['\u02C6'] = '%88'; hash_map['\u2030'] = '%89'; hash_map['\u0160'] = '%8A'; hash_map['\u2039'] = '%8B'; hash_map['\u0152'] = '%8C'; hash_map['\u008D'] = '%8D'; hash_map['\u017D'] = '%8E'; hash_map['\u008F'] = '%8F'; hash_map['\u0090'] = '%90'; hash_map['\u2018'] = '%91'; hash_map['\u2019'] = '%92'; hash_map['\u201C'] = '%93'; hash_map['\u201D'] = '%94'; hash_map['\u2022'] = '%95'; hash_map['\u2013'] = '%96'; hash_map['\u2014'] = '%97'; hash_map['\u02DC'] = '%98'; hash_map['\u2122'] = '%99'; hash_map['\u0161'] = '%9A'; hash_map['\u203A'] = '%9B'; hash_map['\u0153'] = '%9C'; hash_map['\u009D'] = '%9D'; hash_map['\u017E'] = '%9E'; hash_map['\u0178'] = '%9F'; // Begin with encodeURIComponent, which most resembles PHP's encoding functions ret = encodeURIComponent(ret); for (unicodeStr in hash_map) { hexEscStr = hash_map[unicodeStr]; ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing } // Uppercase for full PHP compatibility return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) { return "%"+m2.toUpperCase(); }); } function http_build_query( formdata, numeric_prefix, arg_separator ) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Legaev Andrey // + improved by: Michael White (http://getsprink.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + revised by: stag019 // - depends on: urlencode // * example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;'); // * returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk' // * example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_'); // * returns 2: 'php=hypertext+processor&myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk' var value, key, tmp = []; var _http_build_query_helper = function (key, val, arg_separator) { var k, tmp = []; if (val === true) { val = "1"; } else if (val === false) { val = "0"; } if (typeof(val) == "array" || typeof(val) == "object") { for (k in val) { if(val[k] !== null) { tmp.push(_http_build_query_helper(key + "[" + k + "]", val[k], arg_separator)); } } return tmp.join(arg_separator); } else if(typeof(val) != "function") { return this.urlencode(key) + "=" + this.urlencode(val); } }; if (!arg_separator) { arg_separator = "&"; } for (key in formdata) { value = formdata[key]; if (numeric_prefix && !isNaN(key)) { key = String(numeric_prefix) + key; } tmp.push(_http_build_query_helper(key, value, arg_separator)); } return tmp.join(arg_separator); } function kt_getCookie(c_name) { if (document.cookie.length>0) { var c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start = c_start + c_name.length+1; var c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } function gen_feedstory_link(link, uuid, st1, st2) { var param_array = {'kt_type' : 'feedstory', 'kt_ut' : String(uuid) }; if( st1 != undefined) { param_array['kt_st1'] = st1; } if( st2 != undefined) { param_array['kt_st2'] = st2; } var query_str = http_build_query(param_array); var mod_link = append_kt_query_str(link, query_str); return mod_link; } var kt_feed_cookie_prefix = 'KT_FEED_AB_TEST_INFO'; function gen_feedstory_link_vo(link, uuid, campaign) { // check out cache_ab_testing_msg_page_tuplein kt_ab_testing.php to see how data is being stored in cookies // {'data' : page_msg_info, // 'handle_index': handle_index} var abtest_data = JSON.parse(kt_getCookie(kt_feed_cookie_prefix+campaign)); var param_array = { 'kt_type' : 'feedstory', 'kt_ut': String(uuid) }; param_array['kt_st1'] = format_kt_st1(campaign, abtest_data['handle_index']); // For feeds, messages and pages are tightly coupled param_array['kt_st2'] = format_kt_st2(abtest_data['data'][0]); param_array['kt_st3'] = format_kt_st3(abtest_data['data'][0]); var query_str = http_build_query(param_array); var mod_link = append_kt_query_str(link, query_str); return mod_link; } function format_kt_st1(st1_str, handle_index) { return 'aB_'+st1_str+"___"+handle_index; } function format_kt_st2(st2_str) { return 'm'+st2_str; } function format_kt_st3(st3_str) { return 'p'+st3_str; } function get_selected_feed_msg(campaign, data_assoc_array) { var abtest_data = JSON.parse(kt_getCookie(kt_feed_cookie_prefix+campaign)); return replace_vo_custom_variable(abtest_data['data'][3], data_assoc_array); } function get_selected_feed_call_to_action(campaign, data_assoc_array) { var abtest_data = JSON.parse(kt_getCookie(kt_feed_cookie_prefix+campaign)); return replace_vo_custom_variable(abtest_data['data'][2], data_assoc_array); } var AB_TEMPLATE_REGEX = /\{\{(.*?)\}\}/g; var KEY_REGEX = /\{\{(.*?)\}\}/; function replace_vo_custom_variable(text, data_assoc_array) { var variable_list = text.match(AB_TEMPLATE_REGEX); if(variable_list == null) return text; //no variables var len = variable_list.length; for(var i = 0; i < len; i++) { var var_name = variable_list[i]; var key = var_name.match(KEY_REGEX)[1]; text = text.replace(var_name, data_assoc_array[key]); } return text; } function append_kt_query_str(original_url, query_str) { var position = original_url.indexOf('?'); if(position == -1) { return original_url + "?" + query_str; } else { return original_url + "&" + query_str; } }
rmatei/kt
73cb3038a031ed3c541a26f4204fddafc186e534
kt_common.js was outdated.
diff --git a/kt_common.js b/kt_common.js index 74bb8c5..f328330 100644 --- a/kt_common.js +++ b/kt_common.js @@ -1,293 +1,310 @@ /* + * Generate a random uuid. + * + * USAGE: Math.uuid(length, radix) + * length - the desired number of characters + * radix - the number of allowable values for each character. + * + * EXAMPLES: + * // No arguments - returns RFC4122, version 4 ID + * >>> Math.uuid() + * "92329D39-6F5C-4520-ABFC-AAB64544E172" + * + * // One argument - returns ID of the specified length + * >>> Math.uuid(15) // 15 character ID (default base=62) + * "VcydxgltxrVZSTV" + * + * // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62) + * >>> Math.uuid(8, 2) // 8 character ID (base=2) + * "01001010" + * >>> Math.uuid(8, 10) // 8 character ID (base=10) + * "47473046" + * >>> Math.uuid(8, 16) // 8 character ID (base=16) + * "098F4D35" + */ +Math.uuid = (function() { + // Private array of chars to use + var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); + + return function (len, radix) { + var chars = CHARS, uuid = [], rnd = Math.random; + radix = radix || chars.length; + + if (len) { + // Compact form + for (var i = 0; i < len; i++) uuid[i] = chars[0 | rnd()*radix]; + } else { + // rfc4122, version 4 form + var r; + + // rfc4122 requires these characters + uuid[8] = uuid[13] = uuid[18] = uuid[23] = ''; + uuid[14] = '4'; + + // Fill in random data. At i==19 set the high bits of clock sequence as + // per rfc4122, sec. 4.1.5 + for (var i = 0; i < 36; i++) { + if (!uuid[i]) { + r = 0 | rnd()*16; + uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf]; + } + } + } -uuid.js - Version 0.3 -JavaScript Class to create a UUID like identifier - -Copyright (C) 2006-2008, Erik Giberti (AF-Design), All rights reserved. - -This program is free software; you can redistribute it and/or modify it under -the terms of the GNU General Public License as published by the Free Software -Foundation; either version 2 of the License, or (at your option) any later -version. - -This program is distributed in the hope that it will be useful, but WITHOUT ANY -WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A -PARTICULAR PURPOSE. See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License along with -this program; if not, write to the Free Software Foundation, Inc., 59 Temple -Place, Suite 330, Boston, MA 02111-1307 USA - -The latest version of this file can be downloaded from -http://www.af-design.com/resources/javascript_uuid.php - -HISTORY: -6/5/06 - Initial Release -5/22/08 - Updated code to run faster, removed randrange(min,max) in favor of - a simpler rand(max) function. Reduced overhead by using getTime() - method of date class (suggestion by James Hall). -9/5/08 - Fixed a bug with rand(max) and additional efficiencies pointed out - by Robert Kieffer http://broofa.com/ - -KNOWN ISSUES: -- Still no way to get MAC address in JavaScript -- Research into other versions of UUID show promising possibilities - (more research needed) -- Documentation needs improvement - -*/ - -// On creation of a UUID object, set it's initial value -function UUID(){ - this.id = this.createUUID(); -} - -// When asked what this Object is, lie and return it's value -UUID.prototype.valueOf = function(){ return this.id; } -UUID.prototype.toString = function(){ return this.id; } - -// -// INSTANCE SPECIFIC METHODS -// - -UUID.prototype.createUUID = function(){ - // - // Loose interpretation of the specification DCE 1.1: Remote Procedure Call - // described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37 - // since JavaScript doesn't allow access to internal systems, the last 48 bits - // of the node section is made up using a series of random numbers (6 octets long). - // - var dg = new Date(1582, 10, 15, 0, 0, 0, 0); - var dc = new Date(); - var t = dc.getTime() - dg.getTime(); - var h = ''; - var tl = UUID.getIntegerBits(t,0,31); - var tm = UUID.getIntegerBits(t,32,47); - var thv = UUID.getIntegerBits(t,48,59) + '1'; // version 1, security version is 2 - var csar = UUID.getIntegerBits(UUID.rand(4095),0,7); - var csl = UUID.getIntegerBits(UUID.rand(4095),0,7); - - // since detection of anything about the machine/browser is far to buggy, - // include some more random numbers here - // if NIC or an IP can be obtained reliably, that should be put in - // here instead. - var n = UUID.getIntegerBits(UUID.rand(8191),0,7) + - UUID.getIntegerBits(UUID.rand(8191),8,15) + - UUID.getIntegerBits(UUID.rand(8191),0,7) + - UUID.getIntegerBits(UUID.rand(8191),8,15) + - UUID.getIntegerBits(UUID.rand(8191),0,15); // this last number is two octets long - return tl + h + tm + h + thv + h + csar + csl + h + n; -} - - -// -// GENERAL METHODS (Not instance specific) -// - - -// Pull out only certain bits from a very large integer, used to get the time -// code information for the first part of a UUID. Will return zero's if there -// aren't enough bits to shift where it needs to. -UUID.getIntegerBits = function(val,start,end){ - var base16 = UUID.returnBase(val,16); - var quadArray = new Array(); - var quadString = ''; - var i = 0; - for(i=0;i<base16.length;i++){ - quadArray.push(base16.substring(i,i+1)); - } - for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){ - if(!quadArray[i] || quadArray[i] == '') quadString += '0'; - else quadString += quadArray[i]; - } - return quadString; -} - -// Replaced from the original function to leverage the built in methods in -// JavaScript. Thanks to Robert Kieffer for pointing this one out -UUID.returnBase = function(number, base){ - return (number).toString(base).toUpperCase(); -} - -// pick a random number within a range of numbers -// int b rand(int a); where 0 <= b <= a -UUID.rand = function(max){ - return Math.floor(Math.random() * (max + 1)); -} - -// end of UUID class file - + return uuid.join(''); + }; +})(); function urlencode( str ) { // http://kevin.vanzonneveld.net // + original by: Philip Peterson // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: AJ // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: travc // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Lars Fischer // + input by: Ratheous // % note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/ // * example 1: urlencode('Kevin van Zonneveld!'); // * returns 1: 'Kevin+van+Zonneveld%21' // * example 2: urlencode('http://kevin.vanzonneveld.net/'); // * returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F' // * example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'); // * returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a' var hash_map = {}, unicodeStr='', hexEscStr=''; var ret = (str+'').toString(); var replacer = function(search, replace, str) { var tmp_arr = []; tmp_arr = str.split(search); return tmp_arr.join(replace); }; // The hash_map is identical to the one in urldecode. hash_map["'"] = '%27'; hash_map['('] = '%28'; hash_map[')'] = '%29'; hash_map['*'] = '%2A'; hash_map['~'] = '%7E'; hash_map['!'] = '%21'; hash_map['%20'] = '+'; hash_map['\u00DC'] = '%DC'; hash_map['\u00FC'] = '%FC'; hash_map['\u00C4'] = '%D4'; hash_map['\u00E4'] = '%E4'; hash_map['\u00D6'] = '%D6'; hash_map['\u00F6'] = '%F6'; hash_map['\u00DF'] = '%DF'; hash_map['\u20AC'] = '%80'; hash_map['\u0081'] = '%81'; hash_map['\u201A'] = '%82'; hash_map['\u0192'] = '%83'; hash_map['\u201E'] = '%84'; hash_map['\u2026'] = '%85'; hash_map['\u2020'] = '%86'; hash_map['\u2021'] = '%87'; hash_map['\u02C6'] = '%88'; hash_map['\u2030'] = '%89'; hash_map['\u0160'] = '%8A'; hash_map['\u2039'] = '%8B'; hash_map['\u0152'] = '%8C'; hash_map['\u008D'] = '%8D'; hash_map['\u017D'] = '%8E'; hash_map['\u008F'] = '%8F'; hash_map['\u0090'] = '%90'; hash_map['\u2018'] = '%91'; hash_map['\u2019'] = '%92'; hash_map['\u201C'] = '%93'; hash_map['\u201D'] = '%94'; hash_map['\u2022'] = '%95'; hash_map['\u2013'] = '%96'; hash_map['\u2014'] = '%97'; hash_map['\u02DC'] = '%98'; hash_map['\u2122'] = '%99'; hash_map['\u0161'] = '%9A'; hash_map['\u203A'] = '%9B'; hash_map['\u0153'] = '%9C'; hash_map['\u009D'] = '%9D'; hash_map['\u017E'] = '%9E'; hash_map['\u0178'] = '%9F'; // Begin with encodeURIComponent, which most resembles PHP's encoding functions ret = encodeURIComponent(ret); for (unicodeStr in hash_map) { hexEscStr = hash_map[unicodeStr]; ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing } // Uppercase for full PHP compatibility return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) { return "%"+m2.toUpperCase(); }); } function http_build_query( formdata, numeric_prefix, arg_separator ) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Legaev Andrey // + improved by: Michael White (http://getsprink.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + revised by: stag019 // - depends on: urlencode // * example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;'); // * returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk' // * example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_'); // * returns 2: 'php=hypertext+processor&myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk' var value, key, tmp = []; var _http_build_query_helper = function (key, val, arg_separator) { var k, tmp = []; if (val === true) { val = "1"; } else if (val === false) { val = "0"; } if (typeof(val) == "array" || typeof(val) == "object") { for (k in val) { if(val[k] !== null) { tmp.push(_http_build_query_helper(key + "[" + k + "]", val[k], arg_separator)); } } return tmp.join(arg_separator); } else if(typeof(val) != "function") { return this.urlencode(key) + "=" + this.urlencode(val); } }; if (!arg_separator) { arg_separator = "&"; } for (key in formdata) { value = formdata[key]; if (numeric_prefix && !isNaN(key)) { key = String(numeric_prefix) + key; } tmp.push(_http_build_query_helper(key, value, arg_separator)); } return tmp.join(arg_separator); } +function kt_getCookie(c_name) +{ + if (document.cookie.length>0) + { + var c_start=document.cookie.indexOf(c_name + "="); + if (c_start!=-1) + { + c_start = c_start + c_name.length+1; + var c_end=document.cookie.indexOf(";",c_start); + if (c_end==-1) c_end=document.cookie.length; + return unescape(document.cookie.substring(c_start,c_end)); + } + } + return ""; +} function gen_feedstory_link(link, uuid, st1, st2) { var param_array = {'kt_type' : 'feedstory', 'kt_ut' : String(uuid) }; if( st1 != undefined) { param_array['kt_st1'] = st1; } if( st2 != undefined) { param_array['kt_st2'] = st2; } var query_str = http_build_query(param_array); var mod_link = append_kt_query_str(link, query_str); return mod_link; } +var kt_feed_cookie_prefix = 'KT_FEED_AB_TEST_INFO'; + +function gen_feedstory_link_vo(link, uuid, campaign) +{ + // check out cache_ab_testing_msg_page_tuplein kt_ab_testing.php to see how data is being stored in cookies + // {'data' : page_msg_info, + // 'handle_index': handle_index} + var abtest_data = JSON.parse(kt_getCookie(kt_feed_cookie_prefix+campaign)); + var param_array = { 'kt_type' : 'feedstory', + 'kt_ut': String(uuid) }; + + param_array['kt_st1'] = format_kt_st1(campaign, abtest_data['handle_index']); + // For feeds, messages and pages are tightly coupled + param_array['kt_st2'] = format_kt_st2(abtest_data['data'][0]); + param_array['kt_st3'] = format_kt_st3(abtest_data['data'][0]); + + var query_str = http_build_query(param_array); + var mod_link = append_kt_query_str(link, query_str); + return mod_link; +} + +function format_kt_st1(st1_str, handle_index) +{ + return 'aB_'+st1_str+"___"+handle_index; +} + +function format_kt_st2(st2_str) +{ + return 'm'+st2_str; +} + +function format_kt_st3(st3_str) +{ + return 'p'+st3_str; +} + +function get_selected_feed_msg(campaign, data_assoc_array) +{ + var abtest_data = JSON.parse(kt_getCookie(kt_feed_cookie_prefix+campaign)); + return replace_vo_custom_variable(abtest_data['data'][3], data_assoc_array); +} + +function get_selected_feed_call_to_action(campaign, data_assoc_array) +{ + var abtest_data = JSON.parse(kt_getCookie(kt_feed_cookie_prefix+campaign)); + return replace_vo_custom_variable(abtest_data['data'][2], data_assoc_array); +} + +var AB_TEMPLATE_REGEX = /\{\{(.*?)\}\}/g; +var KEY_REGEX = /\{\{(.*?)\}\}/; +function replace_vo_custom_variable(text, data_assoc_array) +{ + var variable_list = text.match(AB_TEMPLATE_REGEX); + if(variable_list == null) return text; //no variables + + var len = variable_list.length; + for(var i = 0; i < len; i++) + { + var var_name = variable_list[i]; + var key = var_name.match(KEY_REGEX)[1]; + text = text.replace(var_name, data_assoc_array[key]); + } + return text; +} + function append_kt_query_str(original_url, query_str) { var position = original_url.indexOf('?'); if(position == -1) { return original_url + "?" + query_str; } else { return original_url + "&" + query_str; } } diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb index de4e9d7..e4a1808 100644 --- a/lib/facebook/rails/controller.rb +++ b/lib/facebook/rails/controller.rb @@ -1,95 +1,100 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'json' module Facebooker module Rails module Controller def application_is_not_installed_by_facebook_user_with_kontagent if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") redirect_to session[:facebook_session].install_url else local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") end end #application_is_not_installed_by_facebook_user_with_kontagent def gen_uuid() Kt::KtAnalytics.instance.gen_long_uuid() end def gen_feedstory_link(link, uuid, st1=nil, st2=nil, st3=nil) Kt::KtAnalytics.instance.gen_feedstory_link(link , uuid, st1, st2, st3) end def kt_feedstory_send(uuid, st1=nil, st2=nil, st3=nil) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.kt_feedstory_send(uid, uuid, st1, st2, st3) end def gen_multifeedstory_link(link, uuid, st1=nil, st2=nil, st3=nil) Kt::KtAnalytics.instance.gen_multifeedstory_link(link, uuid, st1, st2, st3) end def kt_multifeedstory_send(uuid, st1=nil, st2=nil, st3=nil) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.kt_multifeedstory_send(uid, uuid, st1, st2, st3) end def kt_increment_goal_count(goal_id, inc) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.increment_goal_count(uid, goal_id, inc) end def kt_increment_multiple_goal_counts(assoc_array) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.increment_multiple_goal_counts(uid, assoc_array) end + def kt_increment_monetization(money_value) + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + Kt::KtAnalytics.instance.increment_monetization(uid, money_value) + end + def gen_feedstory_link_vo(link, uuid, ab_test_serialized_str) info = JSON.parse(ab_test_serialized_str) st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) return gen_feedstory_link(link , uuid , st1 , st2 , st3) end def kt_get_ab_feed_msg_text(ab_test_serialized_str) info = JSON.parse(ab_test_serialized_str) return info['data'][3] end def kt_feedstory_send_vo(uuid, ab_test_serialized_str) info = JSON.parse(ab_test_serialized_str) st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) kt_feedstory_send(uuid, st1, st2, st3) end def gen_multifeedstory_link_vo(link, uuid, ab_test_serialized_str) info = JSON.parse(ab_test_serialized_str) st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) return gen_multifeedstory_link(link, uuid, st1, st2, st3) end def kt_multifeedstory_send_vo(uuid, ab_test_serialized_str) info = JSON.parse(ab_test_serialized_str) st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) kt_multifeedstory_send(uuid, st1, st2, st3) end alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent end #module Controller end end
rmatei/kt
e98334ed6f3b173fb72e05efc9dc0df212c74cd9
Try turning kt off altogether
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 4f5b1e0..7eb809f 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -9,620 +9,620 @@ require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() kt_outbound_msg('apa', arg_hash) elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() kt_outbound_msg('apa', arg_hash) else kt_outbound_msg('apa', arg_hash) end # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) - Timeout::timeout(1) do - if @m_mode == :async - #timeout(@m_timeout) do - data_hash = { - :qtype => :kt_outbound, - :ctype => type, - :v => 'v1', - :kt_api_key => @m_kt_api_key, - :kt_secret_key => @m_kt_secret_key, - :kt_call_back_host => @m_kt_host, - :kt_call_back_port => @m_kt_host_port, - :kt_url => @m_kt_url, - :arg_hash => arg_hash, - } - Kt::Queue::Task.publish :record, data_hash - #end - else - @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) - end - end + # Timeout::timeout(1) do + # if @m_mode == :async + # #timeout(@m_timeout) do + # data_hash = { + # :qtype => :kt_outbound, + # :ctype => type, + # :v => 'v1', + # :kt_api_key => @m_kt_api_key, + # :kt_secret_key => @m_kt_secret_key, + # :kt_call_back_host => @m_kt_host, + # :kt_call_back_port => @m_kt_host_port, + # :kt_url => @m_kt_url, + # :arg_hash => arg_hash, + # } + # Kt::Queue::Task.publish :record, data_hash + # #end + # else + # @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) + # end + # end rescue Timeout::Error RAILS_DEFAULT_LOGGER.warn "kt_outbound_msg timed out." end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
4403e6848bfcc982b2218a2e6ac853a71f03418a
Reduce kt timeout
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 4ed242a..4f5b1e0 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -9,620 +9,620 @@ require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() kt_outbound_msg('apa', arg_hash) elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() kt_outbound_msg('apa', arg_hash) else kt_outbound_msg('apa', arg_hash) end # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) - Timeout::timeout(2) do + Timeout::timeout(1) do if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end rescue Timeout::Error RAILS_DEFAULT_LOGGER.warn "kt_outbound_msg timed out." end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
3eb4a7048500d0f8266d3ab07fbd386ac952ab38
time out asynchronous messages as well
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 4e984b0..4ed242a 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -9,620 +9,620 @@ require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() kt_outbound_msg('apa', arg_hash) elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() kt_outbound_msg('apa', arg_hash) else kt_outbound_msg('apa', arg_hash) end # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) - if @m_mode == :async - #timeout(@m_timeout) do - data_hash = { - :qtype => :kt_outbound, - :ctype => type, - :v => 'v1', - :kt_api_key => @m_kt_api_key, - :kt_secret_key => @m_kt_secret_key, - :kt_call_back_host => @m_kt_host, - :kt_call_back_port => @m_kt_host_port, - :kt_url => @m_kt_url, - :arg_hash => arg_hash, - } - Kt::Queue::Task.publish :record, data_hash - #end - else - Timeout::timeout(2) do + Timeout::timeout(2) do + if @m_mode == :async + #timeout(@m_timeout) do + data_hash = { + :qtype => :kt_outbound, + :ctype => type, + :v => 'v1', + :kt_api_key => @m_kt_api_key, + :kt_secret_key => @m_kt_secret_key, + :kt_call_back_host => @m_kt_host, + :kt_call_back_port => @m_kt_host_port, + :kt_url => @m_kt_url, + :arg_hash => arg_hash, + } + Kt::Queue::Task.publish :record, data_hash + #end + else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end rescue Timeout::Error RAILS_DEFAULT_LOGGER.warn "kt_outbound_msg timed out." end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
f8a9e4b6660ad31cc749ec78e66728c1c0f59c36
Timing out kt API calls
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 9c6b91c..4e984b0 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -25,600 +25,604 @@ module Kt def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() kt_outbound_msg('apa', arg_hash) elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() kt_outbound_msg('apa', arg_hash) else kt_outbound_msg('apa', arg_hash) end # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else - @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) + Timeout::timeout(2) do + @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) + end end + rescue Timeout::Error + RAILS_DEFAULT_LOGGER.warn "kt_outbound_msg timed out." end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
d3a98cce896550f836c0e1ad85b7aeca55aceaf8
Silence!
diff --git a/init.rb b/init.rb index 410fc51..9468bc2 100644 --- a/init.rb +++ b/init.rb @@ -1,57 +1,57 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER -puts "loading kt..." +# puts "loading kt..." - SILENCE! require 'facebook/session' require 'kt/rails/helpers' require 'facebooker/rails/publisher' require 'facebook/rails/publisher' #require 'facebooker/rails/controller' require 'facebook/rails/controller' require 'kt/rails/controller' config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") if config['mode'] == 'async' require 'starling' require 'starling_ext' require 'kt/queue/queue' require 'kt/queue/processor' require 'kt/queue/task' # Load app applicable Kontagent::Queue::Processor subclasses from app/processors Dir[RAILS_ROOT + '/app/processors/*.rb'].each do |file| require file end end module ::ActionController class Base def self.inherited_with_kt(subclass) inherited_without_kt(subclass) if subclass.to_s == "ApplicationController" subclass.class_eval do subclass.send(:include,Kt::Rails::Controller) end end end #def class << self alias_method_chain :inherited, :kt end end end ActionView::Base.send :include, Kt::Rails::KontagentHelpers
rmatei/kt
c39658adafcf9827265802bc2bfcfc31e5c50ff5
format st1 for abtesting
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 13046d1..cd74bb8 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,697 +1,691 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte, :feedpub=>:feedpub, :feedstory=>:feedstory, :multifeedstory=>:multifeedstory} @@S_profile_types = {:profilebox=>:profilebox, :profileinfo=>:profileinfo} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd' @@S_undirected_val = 'u' @@S_profile_val = 'p' @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr, :m_is_disabled def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] elsif request_params.has_key?('fb_sig_canvas_user') r = request_params['fb_sig_canvas_user'] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def gen_ru_cookie_key() return @m_kt_api_key + "_ru" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end # used for profileinfo and profilefbml only def store_ru_key_in_cookie(cookies, uid) tag = uid.to_s cookies[gen_ru_cookie_key()] = {:value => tag, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['kt_disabled'].blank? @m_is_disabled = false else @m_is_disabled = app_config_map['kt_disabled'] end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? - if handle_index > 0 - return "aB_"+ st1_str + handle_index.to_s - else - return "aB_"+st1_str - end - else - return "aB_" + return "aB_" + st1_str + "___" + handle_index.to_s end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_profile_fbml_link(fbml_txt, st1, st2, owner_id) id, query_str = gen_kt_comm_query_str(:profilebox, nil, st1, st2, nil, nil, owner_id) fbml_txt = fbml_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return fbml_txt end def kt_profile_setFBML_send(uid, st1, st2) arg_hash = { 'tu' => 'profilebox', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_profile_info_link(info_fields, owner_id, st1, st2) id, query_str = gen_kt_comm_query_str(:profileinfo, nil, st1, st2,nil,nil, owner_id) i=0 j=0 info_fields.each do | info_item | item_array = info_item['items'] item_array.each do | item | link = item['link'] info_fields[i]['items'][j]['link'] = append_kt_query_str(link, query_str) j += 1 end i+=1 end return info_fields end def kt_profile_setInfo_send(uid, st1, st2) arg_hash = { 'tu' => 'profileinfo', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_feedstory_link(link, uuid, st1, st2, st3=nil) id, query_str = gen_kt_comm_query_str(:feedstory, nil, st1, st2, st3, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_feedstory_send(uid, uuid, st1, st2, st3=nil) arg_hash = { 'tu' => 'feedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? arg_hash['st3'] = st3 if !st3.nil? kt_outbound_msg('pst', arg_hash) end def gen_multifeedstory_link(link, uuid, st1, st2, st3=nil) id, query_str = gen_kt_comm_query_str(:multifeedstory, nil, st1, st2, st3, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_multifeedstory_send(uid, uuid, st1, st2, st3=nil) arg_hash = { 'tu' => 'multifeedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? arg_hash['st3'] = st3 if !st3.nil? kt_outbound_msg('pst', arg_hash) end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() elsif not cookies[gen_ru_cookie_key()].blank? arg_hash['ru'] = cookies[gen_ru_cookie_key()] cookies.delete gen_ru_cookie_key() end kt_outbound_msg('apa', arg_hash) # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def save_feedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_multifeedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'multifeedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_feedpub_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedpub' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profilebox_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profilebox' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profileinfo_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profileinfo' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid])
rmatei/kt
a2a5b1f7076d064da814c16b0c0a9dc27bb93a27
ab testing for multifeedstory fbml
diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb index 2318684..de4e9d7 100644 --- a/lib/facebook/rails/controller.rb +++ b/lib/facebook/rails/controller.rb @@ -1,79 +1,95 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'json' module Facebooker module Rails module Controller def application_is_not_installed_by_facebook_user_with_kontagent if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") redirect_to session[:facebook_session].install_url else local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") end end #application_is_not_installed_by_facebook_user_with_kontagent def gen_uuid() Kt::KtAnalytics.instance.gen_long_uuid() end def gen_feedstory_link(link, uuid, st1=nil, st2=nil, st3=nil) Kt::KtAnalytics.instance.gen_feedstory_link(link , uuid, st1, st2, st3) end def kt_feedstory_send(uuid, st1=nil, st2=nil, st3=nil) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.kt_feedstory_send(uid, uuid, st1, st2, st3) end - def gen_multifeedstory_link(link, uuid, st1=nil, st2=nil) - Kt::KtAnalytics.instance.gen_multifeedstory_link(link, uuid, st1, st2) + def gen_multifeedstory_link(link, uuid, st1=nil, st2=nil, st3=nil) + Kt::KtAnalytics.instance.gen_multifeedstory_link(link, uuid, st1, st2, st3) end - def kt_multifeedstory_send(uuid, st1=nil, st2=nil) + def kt_multifeedstory_send(uuid, st1=nil, st2=nil, st3=nil) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - Kt::KtAnalytics.instance.kt_multifeedstory_send(uid, uuid, st1, st2) + Kt::KtAnalytics.instance.kt_multifeedstory_send(uid, uuid, st1, st2, st3) end def kt_increment_goal_count(goal_id, inc) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.increment_goal_count(uid, goal_id, inc) end def kt_increment_multiple_goal_counts(assoc_array) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.increment_multiple_goal_counts(uid, assoc_array) end def gen_feedstory_link_vo(link, uuid, ab_test_serialized_str) info = JSON.parse(ab_test_serialized_str) st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) return gen_feedstory_link(link , uuid , st1 , st2 , st3) end def kt_get_ab_feed_msg_text(ab_test_serialized_str) info = JSON.parse(ab_test_serialized_str) return info['data'][3] end def kt_feedstory_send_vo(uuid, ab_test_serialized_str) info = JSON.parse(ab_test_serialized_str) st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) kt_feedstory_send(uuid, st1, st2, st3) end + def gen_multifeedstory_link_vo(link, uuid, ab_test_serialized_str) + info = JSON.parse(ab_test_serialized_str) + st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s + st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) + st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) + return gen_multifeedstory_link(link, uuid, st1, st2, st3) + end + + def kt_multifeedstory_send_vo(uuid, ab_test_serialized_str) + info = JSON.parse(ab_test_serialized_str) + st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s + st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) + st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) + kt_multifeedstory_send(uuid, st1, st2, st3) + end + alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent end #module Controller end end diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index ebbc59d..13046d1 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,842 +1,843 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte, :feedpub=>:feedpub, :feedstory=>:feedstory, :multifeedstory=>:multifeedstory} @@S_profile_types = {:profilebox=>:profilebox, :profileinfo=>:profileinfo} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd' @@S_undirected_val = 'u' @@S_profile_val = 'p' @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr, :m_is_disabled def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] elsif request_params.has_key?('fb_sig_canvas_user') r = request_params['fb_sig_canvas_user'] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def gen_ru_cookie_key() return @m_kt_api_key + "_ru" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end # used for profileinfo and profilefbml only def store_ru_key_in_cookie(cookies, uid) tag = uid.to_s cookies[gen_ru_cookie_key()] = {:value => tag, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['kt_disabled'].blank? @m_is_disabled = false else @m_is_disabled = app_config_map['kt_disabled'] end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_profile_fbml_link(fbml_txt, st1, st2, owner_id) id, query_str = gen_kt_comm_query_str(:profilebox, nil, st1, st2, nil, nil, owner_id) fbml_txt = fbml_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return fbml_txt end def kt_profile_setFBML_send(uid, st1, st2) arg_hash = { 'tu' => 'profilebox', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_profile_info_link(info_fields, owner_id, st1, st2) id, query_str = gen_kt_comm_query_str(:profileinfo, nil, st1, st2,nil,nil, owner_id) i=0 j=0 info_fields.each do | info_item | item_array = info_item['items'] item_array.each do | item | link = item['link'] info_fields[i]['items'][j]['link'] = append_kt_query_str(link, query_str) j += 1 end i+=1 end return info_fields end def kt_profile_setInfo_send(uid, st1, st2) arg_hash = { 'tu' => 'profileinfo', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end - def gen_feedstory_link(link, uuid, st1, st2, st3) + def gen_feedstory_link(link, uuid, st1, st2, st3=nil) id, query_str = gen_kt_comm_query_str(:feedstory, nil, st1, st2, st3, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_feedstory_send(uid, uuid, st1, st2, st3=nil) arg_hash = { 'tu' => 'feedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? arg_hash['st3'] = st3 if !st3.nil? kt_outbound_msg('pst', arg_hash) end - def gen_multifeedstory_link(link, uuid, st1, st2) - id, query_str = gen_kt_comm_query_str(:multifeedstory, nil, st1, st2, nil, uuid) + def gen_multifeedstory_link(link, uuid, st1, st2, st3=nil) + id, query_str = gen_kt_comm_query_str(:multifeedstory, nil, st1, st2, st3, uuid) r_url = append_kt_query_str(link, query_str) return r_url end - def kt_multifeedstory_send(uid, uuid, st1, st2) + def kt_multifeedstory_send(uid, uuid, st1, st2, st3=nil) arg_hash = { 'tu' => 'multifeedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? - + arg_hash['st3'] = st3 if !st3.nil? + kt_outbound_msg('pst', arg_hash) end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() elsif not cookies[gen_ru_cookie_key()].blank? arg_hash['ru'] = cookies[gen_ru_cookie_key()] cookies.delete gen_ru_cookie_key() end kt_outbound_msg('apa', arg_hash) # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def save_feedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_multifeedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'multifeedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_feedpub_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedpub' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profilebox_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profilebox' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profileinfo_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profileinfo' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def kt_outbound_msg(type, arg_hash) if @m_is_disabled == true return #short circuit end if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end # uid: can simply be one number or an array of uids def increment_goal_count(uid, goal_id, inc) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['gc'+goal_id.to_s] = inc kt_outbound_msg(msg_type, arg_hash) end # goal_counts_assoc_array : { goal_id0 => inc0, goal_id1 => inc1, .... } def increment_multiple_goal_counts(uid, goal_counts_assoc_array) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid goal_counts_assoc_array.each_pair do | k, v| arg_hash['gc'+k.to_s] = v end kt_outbound_msg(msg_type, arg_hash) end def increment_monetization(uid, money_value) msg_type = 'mtu' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['v'] = money_value kt_outbound_msg(msg_type, arg_hash) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def profile_type?(comm_type) @@S_profile_types.has_key?(comm_type) end # if $uuid is provided, then it doesn't generate a new one (directed comm) def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3=nil, uuid_arg=nil, uid_arg=nil) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val elsif profile_type? comm_type dir_val = @@S_profile_val end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val if uuid_arg.nil? uuid = gen_long_uuid() param_array[:kt_ut] = uuid else param_array[:kt_ut] = uuid_arg end elsif dir_val == @@S_profile_val param_array[:kt_owner_uid] = uid_arg end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
7fc83254b1644d76f586ba936d38d4864fdabbcb
ab testing for fbml feedstory
diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb index 9c243be..2318684 100644 --- a/lib/facebook/rails/controller.rb +++ b/lib/facebook/rails/controller.rb @@ -1,57 +1,79 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' +require 'json' module Facebooker module Rails module Controller def application_is_not_installed_by_facebook_user_with_kontagent if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") redirect_to session[:facebook_session].install_url else local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") end end #application_is_not_installed_by_facebook_user_with_kontagent def gen_uuid() Kt::KtAnalytics.instance.gen_long_uuid() end - def gen_feedstory_link(link, uuid, st1=nil, st2=nil) - Kt::KtAnalytics.instance.gen_feedstory_link(link , uuid, st1, st2) + def gen_feedstory_link(link, uuid, st1=nil, st2=nil, st3=nil) + Kt::KtAnalytics.instance.gen_feedstory_link(link , uuid, st1, st2, st3) end - def kt_feedstory_send(uuid, st1=nil, st2=nil) + def kt_feedstory_send(uuid, st1=nil, st2=nil, st3=nil) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - Kt::KtAnalytics.instance.kt_feedstory_send(uid, uuid, st1, st2) + Kt::KtAnalytics.instance.kt_feedstory_send(uid, uuid, st1, st2, st3) end def gen_multifeedstory_link(link, uuid, st1=nil, st2=nil) Kt::KtAnalytics.instance.gen_multifeedstory_link(link, uuid, st1, st2) end def kt_multifeedstory_send(uuid, st1=nil, st2=nil) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.kt_multifeedstory_send(uid, uuid, st1, st2) end def kt_increment_goal_count(goal_id, inc) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.increment_goal_count(uid, goal_id, inc) end - + def kt_increment_multiple_goal_counts(assoc_array) uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') Kt::KtAnalytics.instance.increment_multiple_goal_counts(uid, assoc_array) end + + def gen_feedstory_link_vo(link, uuid, ab_test_serialized_str) + info = JSON.parse(ab_test_serialized_str) + st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s + st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) + st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) + return gen_feedstory_link(link , uuid , st1 , st2 , st3) + end + + def kt_get_ab_feed_msg_text(ab_test_serialized_str) + info = JSON.parse(ab_test_serialized_str) + return info['data'][3] + end + + def kt_feedstory_send_vo(uuid, ab_test_serialized_str) + info = JSON.parse(ab_test_serialized_str) + st1 = "aB_" + info['campaign'] + "___" + info['handle_index'].to_s + st2 = Kt::KtAnalytics.instance.format_kt_st2(info['data'][0]) + st3 = Kt::KtAnalytics.instance.format_kt_st3(info['data'][0]) + kt_feedstory_send(uuid, st1, st2, st3) + end alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent end #module Controller end end diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index 6cc5012..f132e8b 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,352 +1,362 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' require 'digest/md5' require 'ruby-debug' module Kt class AB_Testing_Manager @@URL_PREFIX = "/abtest/campaign_info" @@VO_CUSTOM_VARIABLE_REGEX_STR = /\{\{(.*?)\}\}/ public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} end private def append_sig(url_str, force) arg_array = {} time_stamp = Time.now.to_s sig = Digest::MD5.hexdigest("AB_TEST" + time_stamp + @m_backend_secret_key) if force arg_array['f'] = 1 end arg_array['ts'] = time_stamp arg_array['kt_sig'] = sig url_str = url_str+"?"+arg_array.to_query return url_str end private def validate_checksum(json_obj) key_lst = json_obj.keys.sort sig = "" key_lst.each do |k| sig = sig + k + "=" + JSON.unparse(json_obj[k]).gsub(" ","") unless k == 'sig' end sig += @m_backend_secret_key if Digest::MD5.hexdigest(sig) != json_obj["sig"] raise "Your inbound ab test message from kontagent fails checksum validation" end end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" url_str = append_sig(url_str, force) url = URI.parse(url_str) if url.query.nil? url_str = url.path else url_str = url.path + "?" + url.query end req = Net::HTTP::Get.new(url_str) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true validate_checksum(json_obj) if !json_obj["page_and_messages"].nil? # process message and page together for feed related campaigns page_msg_lst = json_obj["page_and_messages"] weight_array = [] curr_idx = 0 page_msg_lst.each do |pm| w = pm[1] w.times { weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['weight'] = weight_array else # process message list msg_lst = json_obj["messages"] msg_weight_array = [] curr_idx = 0 msg_lst.each do |m| w = m[1] w.times { msg_weight_array << curr_idx } curr_idx += 1 end # process page list page_lst = json_obj['pages'] page_weight_array = [] curr_idx = 0 page_lst.each do |p| w = p[1] w.times { page_weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['msg_weight'] = msg_weight_array store_dict['page_weight'] = page_weight_array end r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) if r.nil? #No changes on the ab test server. So, use the serialized_campaign_str r = Marshal.load( serialized_campaign_str ) end end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end public def get_ab_testing_campaign_handle_index(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return json_obj['handle_index'] end end public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public def get_ab_testing_page_msg_tuple(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_msg_lst = json_obj['page_and_messages'] weight_array = dict['weight'] index = weight_array[rand(weight_array.size)] return page_msg_lst[index] end end public def are_page_message_coupled(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return !json_obj['page_and_messages'].nil? end end + def serialize_msg_page_tuple_helper(campaign, page_msg_info) + data = {} + data['campaign'] = campaign + data['data'] = page_msg_info + data['handle_index'] = get_ab_testing_campaign_handle_index(campaign) + return JSON.unparse(data) + end + def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end def cache_ab_testing_msg_page_tuple(campaign, page_msg_info, cookies) @m_selected_msg_page_pair_dict[campaign] = {'page_msg' => page_msg_info} cookie_data = { :data => page_msg_info, :handle_index => get_ab_testing_campaign_handle_index(campaign) } cookies["KT_FEED_AB_TEST_INFO"+campaign] = JSON.unparse(cookie_data) end - public - def get_selected_page_msg_info(campaign, custom_data=nil) - @m_selected_msg_page_pair_dict[campaign]['page_msg'] + def get_selected_page_msg_info(campaign, pg_custom_data=nil, msg_custom_data=nil) + r = @m_selected_msg_page_pair_dict[campaign]['page_msg'] + r[2] = replace_vo_custom_variable(r[2], pg_custom_data) + r[3] = replace_vo_custom_variable(r[3], msg_custom_data) + return r end def get_selected_msg_info(campaign, custom_data=nil) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], replace_vo_custom_variable(msg_info[2], custom_data) end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else return page_msg_info[0], replace_vo_custom_variable(page_msg_info[3], custom_data) end end end def get_selected_msg_info_button(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[3] end end def get_selected_msg_info_title(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[4] end end def get_selected_page_info(campaign, custom_data=nil) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification page_info = @m_selected_msg_page_pair_dict[campaign]['page'] if page_info.nil? return nil else return page_info[0], replace_vo_custom_variable(page_info[2], custom_data) end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else return page_msg_info[0], replace_vo_custom_variable(page_msg_info[2], custom_data) end end end private def replace_vo_custom_variable(text, data_dict) return text if data_dict.nil? matched_variables_lst = text.scan(@@VO_CUSTOM_VARIABLE_REGEX_STR) matched_variables_lst.each do |key| k = key[0] if data_dict[k].nil? raise k + " is not defined in the data_assoc_array." else text = text.gsub('{{'+k+'}}' , data_dict[k]) end end return text end private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module #mgr = Kt::AB_Testing_Manager.new('56956a4098794fdc98e582f052205b1b', '03df281d926f4e5a9e409cd14f31c060', # 'http://www.kontagent.com', 80) #mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', # 'http://www.kontagent.com', 80) # 'http://kthq.dyndns.org', 9999) # mgr.fetch_ab_testing_data('hello') #puts mgr.get_ab_testing_message('test_u2u_notif') # puts mgr.get_ab_testing_page('hello') diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index af5a631..ebbc59d 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,842 +1,842 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte, :feedpub=>:feedpub, :feedstory=>:feedstory, :multifeedstory=>:multifeedstory} @@S_profile_types = {:profilebox=>:profilebox, :profileinfo=>:profileinfo} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd' @@S_undirected_val = 'u' @@S_profile_val = 'p' @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr, :m_is_disabled def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] elsif request_params.has_key?('fb_sig_canvas_user') r = request_params['fb_sig_canvas_user'] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def gen_ru_cookie_key() return @m_kt_api_key + "_ru" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end # used for profileinfo and profilefbml only def store_ru_key_in_cookie(cookies, uid) tag = uid.to_s cookies[gen_ru_cookie_key()] = {:value => tag, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['kt_disabled'].blank? @m_is_disabled = false else @m_is_disabled = app_config_map['kt_disabled'] end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_profile_fbml_link(fbml_txt, st1, st2, owner_id) id, query_str = gen_kt_comm_query_str(:profilebox, nil, st1, st2, nil, nil, owner_id) fbml_txt = fbml_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return fbml_txt end def kt_profile_setFBML_send(uid, st1, st2) arg_hash = { 'tu' => 'profilebox', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_profile_info_link(info_fields, owner_id, st1, st2) id, query_str = gen_kt_comm_query_str(:profileinfo, nil, st1, st2,nil,nil, owner_id) i=0 j=0 info_fields.each do | info_item | item_array = info_item['items'] item_array.each do | item | link = item['link'] info_fields[i]['items'][j]['link'] = append_kt_query_str(link, query_str) j += 1 end i+=1 end return info_fields end def kt_profile_setInfo_send(uid, st1, st2) arg_hash = { 'tu' => 'profileinfo', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end - def gen_feedstory_link(link, uuid, st1, st2) - id, query_str = gen_kt_comm_query_str(:feedstory, nil, st1, st2, nil, uuid) + def gen_feedstory_link(link, uuid, st1, st2, st3) + id, query_str = gen_kt_comm_query_str(:feedstory, nil, st1, st2, st3, uuid) r_url = append_kt_query_str(link, query_str) return r_url end - def kt_feedstory_send(uid, uuid, st1, st2, st3) + def kt_feedstory_send(uid, uuid, st1, st2, st3=nil) arg_hash = { 'tu' => 'feedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? arg_hash['st3'] = st3 if !st3.nil? kt_outbound_msg('pst', arg_hash) end def gen_multifeedstory_link(link, uuid, st1, st2) id, query_str = gen_kt_comm_query_str(:multifeedstory, nil, st1, st2, nil, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_multifeedstory_send(uid, uuid, st1, st2) arg_hash = { 'tu' => 'multifeedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() elsif not cookies[gen_ru_cookie_key()].blank? arg_hash['ru'] = cookies[gen_ru_cookie_key()] cookies.delete gen_ru_cookie_key() end kt_outbound_msg('apa', arg_hash) # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def save_feedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_multifeedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'multifeedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_feedpub_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedpub' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profilebox_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profilebox' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profileinfo_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profileinfo' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def kt_outbound_msg(type, arg_hash) if @m_is_disabled == true return #short circuit end if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end # uid: can simply be one number or an array of uids def increment_goal_count(uid, goal_id, inc) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['gc'+goal_id.to_s] = inc kt_outbound_msg(msg_type, arg_hash) end # goal_counts_assoc_array : { goal_id0 => inc0, goal_id1 => inc1, .... } def increment_multiple_goal_counts(uid, goal_counts_assoc_array) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid goal_counts_assoc_array.each_pair do | k, v| arg_hash['gc'+k.to_s] = v end kt_outbound_msg(msg_type, arg_hash) end def increment_monetization(uid, money_value) msg_type = 'mtu' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['v'] = money_value kt_outbound_msg(msg_type, arg_hash) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def profile_type?(comm_type) @@S_profile_types.has_key?(comm_type) end # if $uuid is provided, then it doesn't generate a new one (directed comm) def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3=nil, uuid_arg=nil, uid_arg=nil) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val elsif profile_type? comm_type dir_val = @@S_profile_val end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val if uuid_arg.nil? uuid = gen_long_uuid() param_array[:kt_ut] = uuid else param_array[:kt_ut] = uuid_arg end elsif dir_val == @@S_profile_val param_array[:kt_owner_uid] = uid_arg end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index 250e3fb..65090aa 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,170 +1,147 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'cgi' require 'ruby-debug' module Kt module Rails module KontagentHelpers # example: page_custom_data : { 'foo' => 'FOO' } def kt_get_page_text(campaign, page_custom_data=nil) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign, page_custom_data) return page_text end # example: msg_custom_data : { 'foo' => 'FOO' } def kt_get_msg_text(campaign, msg_custom_data=nil) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign, msg_custom_data) return msg_text end def kt_get_msg_buttons(campaign, index) msg_id, msg_buttons = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_button(campaign) if msg_id.nil? return "" end if msg_buttons[index].nil? return "" else msg_buttons[index] end end def kt_get_msg_title(campaign) msg_id, msg_title = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_title(campaign) return msg_title end def kt_get_invite_post_link_vo(invite_post_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, uid, session['invite_uuid'], campaign) # session['invite_uuid'] = nil end return url end def kt_clear_invite_tag() session['invite_uuid'] = nil end def kt_get_invite_content_link_vo(invite_content_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, uid, session['invite_uuid'], campaign) #session['invite_uuid'] = nil end return url end def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) #session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) #session['invite_uuid'] = nil end return url end def kt_track_page_view() if Kt::KtAnalytics.instance.m_is_disabled return "" end uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end def kt_get_callback_url() return Kt::KtAnalytics.instance.m_call_back_host + Kt::KtAnalytics.instance.m_call_back_req_uri end - -# def kt_track_page_view_pm() -# uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') -# url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) - -# kt_api_url = "/api" -# version = "v1" -# kt_api_key = "KT_API_KEY" -# kt_secret_key = "KT_SECRET_KEY" -# api_func = 'pgr' - -# arg_hash = {} -# arg_hash['ts'] = Time.now.to_s -# arg_hash['s'] = uid - -# keys = arg_hash.keys.sort -# sig = '' -# keys.each do |key| -# sig += key+"="+arg_hash[key].to_s -# end - -# sig += kt_secret_key - -# arg_hash['an_sig'] = Digest::MD5.hexdigest(sig) -# query = arg_hash.to_query - -# url_str = kt_api_url + "/" + version + "/" + kt_api_key + "/" + api_func + "/?" + query -# track_code_str = "<img src='http://api.global.kontagent.net#{url_str}' width='0px' height='0px' />" -# return track_code_str -# end # for product madness only - + def kt_get_serialized_msg_page_tuple(campaign, pg_custom_data=nil, msg_custom_data=nil) + info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_msg_info(campaign, + pg_custom_data, + msg_custom_data) + return Kt::KtAnalytics.instance.m_ab_testing_mgr.serialize_msg_page_tuple_helper(campaign, + info) + end + end end end
rmatei/kt
161ae912976bf63d48998c7ded05b6338c6e383d
handles ab testing for feeds in js
diff --git a/kt_facebooker.js b/kt_facebooker.js index db6ea83..2c0a9c3 100644 --- a/kt_facebooker.js +++ b/kt_facebooker.js @@ -1,11 +1,39 @@ function feedstory_send(url_prefix, uid, uuid, st1, st2) { var img = document.createElement('img'); var param_array = { 'uid' : String(uid), 'uuid' : String(uuid) }; + + if( st1 != undefined ) + { + param_array['st1'] = st1; + } + if( st2 != undefined ) + { + param_array['st2'] = st2; + } + var query_str = http_build_query(param_array); img.src = url_prefix+'/ajax_kt_feedstory_send/?' + query_str; +} + +function feedstory_send_vo(url_prefix, uid, uuid, campaign) +{ + var img = document.createElement('img'); + var abtest_data = JSON.parse(kt_getCookie(kt_feed_cookie_prefix+campaign)); + + var param_array = { + 'uid' : String(uid), + 'uuid' : String(uuid) + }; + + param_array['st1'] = format_kt_st1(campaign, abtest_data['handle_index']); + param_array['st2'] = format_kt_st2(abtest_data['data'][0]); + param_array['st3'] = format_kt_st3(abtest_data['data'][0]); + var query_str = http_build_query(param_array); + alert(url_prefix + '/ajax_kt_feedstory_send/?' + query_str);//xxx + img.src = url_prefix + '/ajax_kt_feedstory_send/?' + query_str; } \ No newline at end of file diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index b816f83..6cc5012 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,342 +1,352 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' require 'digest/md5' require 'ruby-debug' module Kt class AB_Testing_Manager @@URL_PREFIX = "/abtest/campaign_info" @@VO_CUSTOM_VARIABLE_REGEX_STR = /\{\{(.*?)\}\}/ public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} end private def append_sig(url_str, force) arg_array = {} time_stamp = Time.now.to_s sig = Digest::MD5.hexdigest("AB_TEST" + time_stamp + @m_backend_secret_key) if force arg_array['f'] = 1 end arg_array['ts'] = time_stamp arg_array['kt_sig'] = sig url_str = url_str+"?"+arg_array.to_query return url_str end private def validate_checksum(json_obj) key_lst = json_obj.keys.sort sig = "" key_lst.each do |k| sig = sig + k + "=" + JSON.unparse(json_obj[k]).gsub(" ","") unless k == 'sig' end sig += @m_backend_secret_key if Digest::MD5.hexdigest(sig) != json_obj["sig"] raise "Your inbound ab test message from kontagent fails checksum validation" end end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" url_str = append_sig(url_str, force) url = URI.parse(url_str) if url.query.nil? url_str = url.path else url_str = url.path + "?" + url.query end req = Net::HTTP::Get.new(url_str) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true validate_checksum(json_obj) if !json_obj["page_and_messages"].nil? # process message and page together for feed related campaigns page_msg_lst = json_obj["page_and_messages"] weight_array = [] curr_idx = 0 page_msg_lst.each do |pm| w = pm[1] w.times { weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['weight'] = weight_array else # process message list msg_lst = json_obj["messages"] msg_weight_array = [] curr_idx = 0 msg_lst.each do |m| w = m[1] w.times { msg_weight_array << curr_idx } curr_idx += 1 end # process page list page_lst = json_obj['pages'] page_weight_array = [] curr_idx = 0 page_lst.each do |p| w = p[1] w.times { page_weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['msg_weight'] = msg_weight_array store_dict['page_weight'] = page_weight_array end r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) + if r.nil? + #No changes on the ab test server. So, use the serialized_campaign_str + r = Marshal.load( serialized_campaign_str ) + end end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end public def get_ab_testing_campaign_handle_index(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return json_obj['handle_index'] end end public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public def get_ab_testing_page_msg_tuple(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_msg_lst = json_obj['page_and_messages'] weight_array = dict['weight'] index = weight_array[rand(weight_array.size)] return page_msg_lst[index] end end public def are_page_message_coupled(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return !json_obj['page_and_messages'].nil? end end def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end - def cache_ab_testing_msg_page_tuple(campaign, page_msg_info) + def cache_ab_testing_msg_page_tuple(campaign, page_msg_info, cookies) @m_selected_msg_page_pair_dict[campaign] = {'page_msg' => page_msg_info} + + cookie_data = { + :data => page_msg_info, + :handle_index => get_ab_testing_campaign_handle_index(campaign) + } + cookies["KT_FEED_AB_TEST_INFO"+campaign] = JSON.unparse(cookie_data) end public def get_selected_page_msg_info(campaign, custom_data=nil) @m_selected_msg_page_pair_dict[campaign]['page_msg'] end def get_selected_msg_info(campaign, custom_data=nil) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], replace_vo_custom_variable(msg_info[2], custom_data) end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else return page_msg_info[0], replace_vo_custom_variable(page_msg_info[3], custom_data) end end end def get_selected_msg_info_button(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[3] end end def get_selected_msg_info_title(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[4] end end def get_selected_page_info(campaign, custom_data=nil) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification page_info = @m_selected_msg_page_pair_dict[campaign]['page'] if page_info.nil? return nil else return page_info[0], replace_vo_custom_variable(page_info[2], custom_data) end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else return page_msg_info[0], replace_vo_custom_variable(page_msg_info[2], custom_data) end end end private def replace_vo_custom_variable(text, data_dict) return text if data_dict.nil? matched_variables_lst = text.scan(@@VO_CUSTOM_VARIABLE_REGEX_STR) matched_variables_lst.each do |key| k = key[0] if data_dict[k].nil? raise k + " is not defined in the data_assoc_array." else text = text.gsub('{{'+k+'}}' , data_dict[k]) end end return text end private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module #mgr = Kt::AB_Testing_Manager.new('56956a4098794fdc98e582f052205b1b', '03df281d926f4e5a9e409cd14f31c060', # 'http://www.kontagent.com', 80) #mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', # 'http://www.kontagent.com', 80) # 'http://kthq.dyndns.org', 9999) # mgr.fetch_ab_testing_data('hello') #puts mgr.get_ab_testing_message('test_u2u_notif') # puts mgr.get_ab_testing_page('hello') diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index aeebe98..af5a631 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,841 +1,842 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte, :feedpub=>:feedpub, :feedstory=>:feedstory, :multifeedstory=>:multifeedstory} @@S_profile_types = {:profilebox=>:profilebox, :profileinfo=>:profileinfo} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd' @@S_undirected_val = 'u' @@S_profile_val = 'p' @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr, :m_is_disabled def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] elsif request_params.has_key?('fb_sig_canvas_user') r = request_params['fb_sig_canvas_user'] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def gen_ru_cookie_key() return @m_kt_api_key + "_ru" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end # used for profileinfo and profilefbml only def store_ru_key_in_cookie(cookies, uid) tag = uid.to_s cookies[gen_ru_cookie_key()] = {:value => tag, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['kt_disabled'].blank? @m_is_disabled = false else @m_is_disabled = app_config_map['kt_disabled'] end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_profile_fbml_link(fbml_txt, st1, st2, owner_id) id, query_str = gen_kt_comm_query_str(:profilebox, nil, st1, st2, nil, nil, owner_id) fbml_txt = fbml_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return fbml_txt end def kt_profile_setFBML_send(uid, st1, st2) arg_hash = { 'tu' => 'profilebox', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_profile_info_link(info_fields, owner_id, st1, st2) id, query_str = gen_kt_comm_query_str(:profileinfo, nil, st1, st2,nil,nil, owner_id) i=0 j=0 info_fields.each do | info_item | item_array = info_item['items'] item_array.each do | item | link = item['link'] info_fields[i]['items'][j]['link'] = append_kt_query_str(link, query_str) j += 1 end i+=1 end return info_fields end def kt_profile_setInfo_send(uid, st1, st2) arg_hash = { 'tu' => 'profileinfo', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_feedstory_link(link, uuid, st1, st2) id, query_str = gen_kt_comm_query_str(:feedstory, nil, st1, st2, nil, uuid) r_url = append_kt_query_str(link, query_str) return r_url end - def kt_feedstory_send(uid, uuid, st1, st2) + def kt_feedstory_send(uid, uuid, st1, st2, st3) arg_hash = { 'tu' => 'feedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? + arg_hash['st3'] = st3 if !st3.nil? kt_outbound_msg('pst', arg_hash) end def gen_multifeedstory_link(link, uuid, st1, st2) id, query_str = gen_kt_comm_query_str(:multifeedstory, nil, st1, st2, nil, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_multifeedstory_send(uid, uuid, st1, st2) arg_hash = { 'tu' => 'multifeedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() elsif not cookies[gen_ru_cookie_key()].blank? arg_hash['ru'] = cookies[gen_ru_cookie_key()] cookies.delete gen_ru_cookie_key() end kt_outbound_msg('apa', arg_hash) # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def save_feedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_multifeedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'multifeedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_feedpub_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedpub' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profilebox_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profilebox' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profileinfo_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profileinfo' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def kt_outbound_msg(type, arg_hash) if @m_is_disabled == true return #short circuit end if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end # uid: can simply be one number or an array of uids def increment_goal_count(uid, goal_id, inc) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['gc'+goal_id.to_s] = inc kt_outbound_msg(msg_type, arg_hash) end # goal_counts_assoc_array : { goal_id0 => inc0, goal_id1 => inc1, .... } def increment_multiple_goal_counts(uid, goal_counts_assoc_array) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid goal_counts_assoc_array.each_pair do | k, v| arg_hash['gc'+k.to_s] = v end kt_outbound_msg(msg_type, arg_hash) end def increment_monetization(uid, money_value) msg_type = 'mtu' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['v'] = money_value kt_outbound_msg(msg_type, arg_hash) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def profile_type?(comm_type) @@S_profile_types.has_key?(comm_type) end # if $uuid is provided, then it doesn't generate a new one (directed comm) def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3=nil, uuid_arg=nil, uid_arg=nil) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val elsif profile_type? comm_type dir_val = @@S_profile_val end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val if uuid_arg.nil? uuid = gen_long_uuid() param_array[:kt_ut] = uuid else param_array[:kt_ut] = uuid_arg end elsif dir_val == @@S_profile_val param_array[:kt_owner_uid] = uid_arg end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 9b07a5d..9336ef9 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,223 +1,223 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) if Kt::KtAnalytics.instance.m_ab_testing_mgr.are_page_message_coupled(campaign) page_msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page_msg_tuple(campaign) - Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_page_tuple(campaign, page_msg_info) + Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_page_tuple(campaign, page_msg_info, cookies) else page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end end def ajax_kt_feedstory_send - Kt::KtAnalytics.instance.kt_feedstory_send(params[:uid], params[:uuid], params[:st1], params[:st2]) + Kt::KtAnalytics.instance.kt_feedstory_send(params[:uid], params[:uuid], params[:st1], params[:st2], params[:st3]) render :nothing => true end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing => true end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end if cookies[gen_kt_install_cookie_key()].nil? or cookies[gen_kt_install_cookie_key()].blank? cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} else if cookies[gen_kt_install_cookie_key()] == "0" and params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" Kt::KtAnalytics.instance.save_app_added(params, cookies) cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} end end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) when "ad" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) when "partner" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) when "feedstory" Kt::KtAnalytics.instance.save_feedstory_click(params, cookies) when "multifeedstory" Kt::KtAnalytics.instance.save_multifeedstory_click(params, cookies) when "feedpub" Kt::KtAnalytics.instance.save_feedpub_click(params, cookies) when "profilebox" Kt::KtAnalytics.instance.save_profilebox_click(params, cookies) when "profileinfo" Kt::KtAnalytics.instance.save_profileinfo_click(params, cookies) else end if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private def gen_kt_install_cookie_key() return "KT_"+Facebooker.api_key+"_installed" end def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
767dadd9a8956ea7e45b34a61eec900a658c8974
added authorization for ab testing
diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index cd27543..b816f83 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,312 +1,342 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' +require 'digest/md5' require 'ruby-debug' module Kt class AB_Testing_Manager @@URL_PREFIX = "/abtest/campaign_info" @@VO_CUSTOM_VARIABLE_REGEX_STR = /\{\{(.*?)\}\}/ public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} end + + private + def append_sig(url_str, force) + arg_array = {} + time_stamp = Time.now.to_s + sig = Digest::MD5.hexdigest("AB_TEST" + time_stamp + @m_backend_secret_key) + + if force + arg_array['f'] = 1 + end + arg_array['ts'] = time_stamp + arg_array['kt_sig'] = sig + + url_str = url_str+"?"+arg_array.to_query + return url_str + end + + private + def validate_checksum(json_obj) + key_lst = json_obj.keys.sort + sig = "" + key_lst.each do |k| + sig = sig + k + "=" + JSON.unparse(json_obj[k]).gsub(" ","") unless k == 'sig' + end + sig += @m_backend_secret_key + + if Digest::MD5.hexdigest(sig) != json_obj["sig"] + raise "Your inbound ab test message from kontagent fails checksum validation" + end + end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" - if force == true - url_str += "?f=1" - end + url_str = append_sig(url_str, force) url = URI.parse(url_str) if url.query.nil? url_str = url.path else url_str = url.path + "?" + url.query end req = Net::HTTP::Get.new(url_str) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true + validate_checksum(json_obj) if !json_obj["page_and_messages"].nil? # process message and page together for feed related campaigns page_msg_lst = json_obj["page_and_messages"] weight_array = [] curr_idx = 0 page_msg_lst.each do |pm| w = pm[1] w.times { weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['weight'] = weight_array else # process message list msg_lst = json_obj["messages"] msg_weight_array = [] curr_idx = 0 msg_lst.each do |m| w = m[1] w.times { msg_weight_array << curr_idx } curr_idx += 1 end # process page list page_lst = json_obj['pages'] page_weight_array = [] curr_idx = 0 page_lst.each do |p| w = p[1] w.times { page_weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['msg_weight'] = msg_weight_array store_dict['page_weight'] = page_weight_array end r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end public def get_ab_testing_campaign_handle_index(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return json_obj['handle_index'] end end public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public def get_ab_testing_page_msg_tuple(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_msg_lst = json_obj['page_and_messages'] weight_array = dict['weight'] index = weight_array[rand(weight_array.size)] return page_msg_lst[index] end end public def are_page_message_coupled(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return !json_obj['page_and_messages'].nil? end end def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end def cache_ab_testing_msg_page_tuple(campaign, page_msg_info) @m_selected_msg_page_pair_dict[campaign] = {'page_msg' => page_msg_info} end public def get_selected_page_msg_info(campaign, custom_data=nil) @m_selected_msg_page_pair_dict[campaign]['page_msg'] end def get_selected_msg_info(campaign, custom_data=nil) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], replace_vo_custom_variable(msg_info[2], custom_data) end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else return page_msg_info[0], replace_vo_custom_variable(page_msg_info[3], custom_data) end end end def get_selected_msg_info_button(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[3] end end def get_selected_msg_info_title(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[4] end end def get_selected_page_info(campaign, custom_data=nil) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification page_info = @m_selected_msg_page_pair_dict[campaign]['page'] if page_info.nil? return nil else return page_info[0], replace_vo_custom_variable(page_info[2], custom_data) end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else return page_msg_info[0], replace_vo_custom_variable(page_msg_info[2], custom_data) end end end private def replace_vo_custom_variable(text, data_dict) return text if data_dict.nil? matched_variables_lst = text.scan(@@VO_CUSTOM_VARIABLE_REGEX_STR) matched_variables_lst.each do |key| k = key[0] if data_dict[k].nil? raise k + " is not defined in the data_assoc_array." else text = text.gsub('{{'+k+'}}' , data_dict[k]) end end return text end private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module #mgr = Kt::AB_Testing_Manager.new('56956a4098794fdc98e582f052205b1b', '03df281d926f4e5a9e409cd14f31c060', # 'http://www.kontagent.com', 80) #mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', # 'http://www.kontagent.com', 80) # 'http://kthq.dyndns.org', 9999) # mgr.fetch_ab_testing_data('hello') #puts mgr.get_ab_testing_message('test_u2u_notif') # puts mgr.get_ab_testing_page('hello')
rmatei/kt
31ecf0d8741bd89ea651979594b63f18359c46e0
able to handle templatized ab strings.
diff --git a/lib/facebook/rails/publisher.rb b/lib/facebook/rails/publisher.rb index 62b9f0e..c095128 100644 --- a/lib/facebook/rails/publisher.rb +++ b/lib/facebook/rails/publisher.rb @@ -1,68 +1,73 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER module Facebooker module Rails class Publisher def template(arg) @template = arg end def subtype1(arg) @subtype1 = arg end def subtype2(arg) @subtype2 = arg end def campaign(arg) @campaign = arg end + + def msg_data_array(arg) + @msg_data_array = arg + end def send_message_with_kontagent(method) @recipients = @recipients.is_a?(Array) ? @recipients : [@recipients] if from.nil? and @recipients.size==1 and ! announcement_notification?(from,_body) @from = @recipients.first end # notifications can # omit the from address raise InvalidSender.new("Sender must be a Facebooker::User") unless from.is_a?(Facebooker::User) || announcement_notification?(from,_body) case _body when Facebooker::Feed::TemplatizedAction,Facebooker::Feed::Action from.publish_action(_body) when Facebooker::Feed::Story @recipients.each {|r| r.publish_story(_body)} when Notification (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, - @template, @subtype1, @subtype2, @campaign) + @template, @subtype1, @subtype2, + @campaign, @msg_data_array) when Email from.session.send_email(@recipients, _body.title, _body.text, _body.fbml, @template, @subtype1, @subtype2, @campaign) when Profile # If recipient and from aren't the same person, create a new user object using the # userid from recipient and the session from from if @from != @recipients.first @from = Facebooker::User.new(Facebooker::User.cast_to_facebook_id(@recipients.first),from.session) end @from.set_profile_fbml(_body.profile, _body.mobile_profile, _body.profile_action, _body.profile_main, @subtype1, @subtype2) when Ref @from.session.server_cache.set_ref_handle(_body.handle,_body.fbml) when UserAction - @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general, @subtype1, @subtype2, @campaign) + @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general, @subtype1, @subtype2, @campaign, @msg_data_array) else raise UnspecifiedBodyType.new("You must specify a valid send_as") end end alias_method_chain :send_message, :kontagent end end end diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb index 6359e91..4e0994d 100644 --- a/lib/facebook/session.rb +++ b/lib/facebook/session.rb @@ -1,154 +1,159 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'ruby-debug' module Facebooker class Session - def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) + def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, + template_id = nil, st1 = nil, st2 = nil, + campaign = nil, msg_data_array = nil) if !campaign.nil? # ab testing - msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign, msg_data_array) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nt, nil, campaign, msg_id, page_id, msg_txt) else uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) end r = send_notification_without_kontagent(user_ids, fbml, email_fbml) if !r.blank? arg_hash = { 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } if source_user.nil? arg_hash['s'] = 0.to_s else arg_hash['s'] = source_user.id.to_s end arg_hash['t'] = template_id.to_s unless template_id.nil? if !campaign.nil? arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) else arg_hash['st1'] = st1 arg_hash['st2'] = st2 end Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) end end - def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) + def send_email_with_kontagent(user_ids, subject, text, fbml = nil, + template_id = nil, st1 = nil, st2 = nil, + campaign = nil, msg_data_array = nil) if !campaign.nil? # ab testing - msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign, msg_data_array) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) if fbml != nil uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nte, nil, campaign, msg_id, page_id, msg_txt) else uuid = Kt::KtAnalytics.instance.gen_long_uuid end else if fbml != nil uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, template_id, st1, st2, st3) else uuid = Kt::KtAnalytics.instance.gen_long_uuid end end r = send_email_without_kontagent(user_ids, subject, text, fbml) if !r.blank? arg_hash = { 's' => @user.id.to_s , 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } arg_hash['t'] = template_id.to_s unless template_id.nil? if !campaign.nil? arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) else arg_hash['st1'] = st1 arg_hash['st2'] = st2 end Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) end end # if st2 is set to m{d} and st3 is set to p{d}, we'll assume that it's using ab_testing data. - def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil, campaign=nil) + def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil, + campaign=nil, msg_data_array = nil) if !campaign.nil? - msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign, msg_data_array) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) st1 = campaign st2 = msg_id st3 = page_id end uuid = 0 if(data != nil) data.each_pair do |key,value | if key == :image if !campaign.nil? uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(value[:href], :feedpub, nil, st1, st2, st3, campaign) else uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :feedpub, nil, st1, st2) end value[:href] = fbml data[key] = value # do we even need this line? elsif key == :flash elsif key == :mp3 #Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) elsif key == :video else if !campaign.nil? uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href_vo(value, :feedpub, nil, st1, st2, st3) else uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :feedpub, nil, st1, st2) end data[key] = fbml end end end data['KT_AB_MSG'] = msg_txt if !campaign.nil? r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) if !r.blank? arg_hash = { 's' => @user.id.to_s, 'tu' => 'feedpub' } arg_hash['u'] = uuid if !uuid.nil? arg_hash['tg'] = target_ids if !target_ids.nil? arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? Kt::KtAnalytics.instance.kt_outbound_msg('pst', arg_hash) end end alias_method_chain :send_notification, :kontagent alias_method_chain :send_email, :kontagent alias_method_chain :publish_user_action, :kontagent end end diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index a5917ef..cd27543 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,295 +1,312 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' require 'ruby-debug' module Kt class AB_Testing_Manager - @@URL_PREFIX = "/abtest/campaign_info"; - + @@URL_PREFIX = "/abtest/campaign_info" + @@VO_CUSTOM_VARIABLE_REGEX_STR = /\{\{(.*?)\}\}/ + public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" if force == true url_str += "?f=1" end url = URI.parse(url_str) if url.query.nil? url_str = url.path else url_str = url.path + "?" + url.query end req = Net::HTTP::Get.new(url_str) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true if !json_obj["page_and_messages"].nil? # process message and page together for feed related campaigns page_msg_lst = json_obj["page_and_messages"] weight_array = [] curr_idx = 0 page_msg_lst.each do |pm| w = pm[1] w.times { weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['weight'] = weight_array else # process message list msg_lst = json_obj["messages"] msg_weight_array = [] curr_idx = 0 msg_lst.each do |m| w = m[1] w.times { msg_weight_array << curr_idx } curr_idx += 1 end # process page list page_lst = json_obj['pages'] page_weight_array = [] curr_idx = 0 page_lst.each do |p| w = p[1] w.times { page_weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['msg_weight'] = msg_weight_array store_dict['page_weight'] = page_weight_array end r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end public def get_ab_testing_campaign_handle_index(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return json_obj['handle_index'] end end public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public def get_ab_testing_page_msg_tuple(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_msg_lst = json_obj['page_and_messages'] weight_array = dict['weight'] index = weight_array[rand(weight_array.size)] return page_msg_lst[index] end end public def are_page_message_coupled(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return !json_obj['page_and_messages'].nil? end end def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end def cache_ab_testing_msg_page_tuple(campaign, page_msg_info) @m_selected_msg_page_pair_dict[campaign] = {'page_msg' => page_msg_info} end public - def get_selected_page_msg_info(campaign) + def get_selected_page_msg_info(campaign, custom_data=nil) @m_selected_msg_page_pair_dict[campaign]['page_msg'] end - def get_selected_msg_info(campaign) + def get_selected_msg_info(campaign, custom_data=nil) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else - return msg_info[0], msg_info[2] + return msg_info[0], replace_vo_custom_variable(msg_info[2], custom_data) end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else - return page_msg_info[0], page_msg_info[3] + return page_msg_info[0], replace_vo_custom_variable(page_msg_info[3], custom_data) end end end def get_selected_msg_info_button(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[3] end end def get_selected_msg_info_title(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[4] end end - def get_selected_page_info(campaign) + def get_selected_page_info(campaign, custom_data=nil) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification page_info = @m_selected_msg_page_pair_dict[campaign]['page'] if page_info.nil? return nil else - return page_info[0], page_info[2] + return page_info[0], replace_vo_custom_variable(page_info[2], custom_data) end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else - return page_msg_info[0], page_msg_info[2] + return page_msg_info[0], replace_vo_custom_variable(page_msg_info[2], custom_data) end end end + private + def replace_vo_custom_variable(text, data_dict) + return text if data_dict.nil? + + matched_variables_lst = text.scan(@@VO_CUSTOM_VARIABLE_REGEX_STR) + matched_variables_lst.each do |key| + k = key[0] + if data_dict[k].nil? + raise k + " is not defined in the data_assoc_array." + else + text = text.gsub('{{'+k+'}}' , data_dict[k]) + end + end + return text + end + private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module #mgr = Kt::AB_Testing_Manager.new('56956a4098794fdc98e582f052205b1b', '03df281d926f4e5a9e409cd14f31c060', # 'http://www.kontagent.com', 80) #mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', # 'http://www.kontagent.com', 80) # 'http://kthq.dyndns.org', 9999) # mgr.fetch_ab_testing_data('hello') #puts mgr.get_ab_testing_message('test_u2u_notif') # puts mgr.get_ab_testing_page('hello') diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index ab0d9a4..250e3fb 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,169 +1,170 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'cgi' require 'ruby-debug' module Kt module Rails module KontagentHelpers - def kt_get_page_text(campaign) - page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + # example: page_custom_data : { 'foo' => 'FOO' } + def kt_get_page_text(campaign, page_custom_data=nil) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign, page_custom_data) return page_text end - - def kt_get_msg_text(campaign) - msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + # example: msg_custom_data : { 'foo' => 'FOO' } + def kt_get_msg_text(campaign, msg_custom_data=nil) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign, msg_custom_data) return msg_text end def kt_get_msg_buttons(campaign, index) msg_id, msg_buttons = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_button(campaign) if msg_id.nil? return "" end if msg_buttons[index].nil? return "" else msg_buttons[index] end end def kt_get_msg_title(campaign) msg_id, msg_title = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_title(campaign) return msg_title end def kt_get_invite_post_link_vo(invite_post_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, uid, session['invite_uuid'], campaign) # session['invite_uuid'] = nil end return url end def kt_clear_invite_tag() session['invite_uuid'] = nil end def kt_get_invite_content_link_vo(invite_content_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, uid, session['invite_uuid'], campaign) #session['invite_uuid'] = nil end return url end def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) #session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) #session['invite_uuid'] = nil end return url end def kt_track_page_view() if Kt::KtAnalytics.instance.m_is_disabled return "" end uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end def kt_get_callback_url() return Kt::KtAnalytics.instance.m_call_back_host + Kt::KtAnalytics.instance.m_call_back_req_uri end # def kt_track_page_view_pm() # uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') # url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) # kt_api_url = "/api" # version = "v1" # kt_api_key = "KT_API_KEY" # kt_secret_key = "KT_SECRET_KEY" # api_func = 'pgr' # arg_hash = {} # arg_hash['ts'] = Time.now.to_s # arg_hash['s'] = uid # keys = arg_hash.keys.sort # sig = '' # keys.each do |key| # sig += key+"="+arg_hash[key].to_s # end # sig += kt_secret_key # arg_hash['an_sig'] = Digest::MD5.hexdigest(sig) # query = arg_hash.to_query # url_str = kt_api_url + "/" + version + "/" + kt_api_key + "/" + api_func + "/?" + query # track_code_str = "<img src='http://api.global.kontagent.net#{url_str}' width='0px' height='0px' />" # return track_code_str # end # for product madness only end end end
rmatei/kt
1a783732724773ecb563774e7ee93fadcb5d7b93
handle undefined st1 and st2 for js feeds
diff --git a/kt_common.js b/kt_common.js index 8d1d9d5..74bb8c5 100644 --- a/kt_common.js +++ b/kt_common.js @@ -1,287 +1,293 @@ /* uuid.js - Version 0.3 JavaScript Class to create a UUID like identifier Copyright (C) 2006-2008, Erik Giberti (AF-Design), All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA The latest version of this file can be downloaded from http://www.af-design.com/resources/javascript_uuid.php HISTORY: 6/5/06 - Initial Release 5/22/08 - Updated code to run faster, removed randrange(min,max) in favor of a simpler rand(max) function. Reduced overhead by using getTime() method of date class (suggestion by James Hall). 9/5/08 - Fixed a bug with rand(max) and additional efficiencies pointed out by Robert Kieffer http://broofa.com/ KNOWN ISSUES: - Still no way to get MAC address in JavaScript - Research into other versions of UUID show promising possibilities (more research needed) - Documentation needs improvement */ // On creation of a UUID object, set it's initial value function UUID(){ this.id = this.createUUID(); } // When asked what this Object is, lie and return it's value UUID.prototype.valueOf = function(){ return this.id; } UUID.prototype.toString = function(){ return this.id; } // // INSTANCE SPECIFIC METHODS // UUID.prototype.createUUID = function(){ // // Loose interpretation of the specification DCE 1.1: Remote Procedure Call // described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37 // since JavaScript doesn't allow access to internal systems, the last 48 bits // of the node section is made up using a series of random numbers (6 octets long). // var dg = new Date(1582, 10, 15, 0, 0, 0, 0); var dc = new Date(); var t = dc.getTime() - dg.getTime(); var h = ''; var tl = UUID.getIntegerBits(t,0,31); var tm = UUID.getIntegerBits(t,32,47); var thv = UUID.getIntegerBits(t,48,59) + '1'; // version 1, security version is 2 var csar = UUID.getIntegerBits(UUID.rand(4095),0,7); var csl = UUID.getIntegerBits(UUID.rand(4095),0,7); // since detection of anything about the machine/browser is far to buggy, // include some more random numbers here // if NIC or an IP can be obtained reliably, that should be put in // here instead. var n = UUID.getIntegerBits(UUID.rand(8191),0,7) + UUID.getIntegerBits(UUID.rand(8191),8,15) + UUID.getIntegerBits(UUID.rand(8191),0,7) + UUID.getIntegerBits(UUID.rand(8191),8,15) + UUID.getIntegerBits(UUID.rand(8191),0,15); // this last number is two octets long return tl + h + tm + h + thv + h + csar + csl + h + n; } // // GENERAL METHODS (Not instance specific) // // Pull out only certain bits from a very large integer, used to get the time // code information for the first part of a UUID. Will return zero's if there // aren't enough bits to shift where it needs to. UUID.getIntegerBits = function(val,start,end){ var base16 = UUID.returnBase(val,16); var quadArray = new Array(); var quadString = ''; var i = 0; for(i=0;i<base16.length;i++){ quadArray.push(base16.substring(i,i+1)); } for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){ if(!quadArray[i] || quadArray[i] == '') quadString += '0'; else quadString += quadArray[i]; } return quadString; } // Replaced from the original function to leverage the built in methods in // JavaScript. Thanks to Robert Kieffer for pointing this one out UUID.returnBase = function(number, base){ return (number).toString(base).toUpperCase(); } // pick a random number within a range of numbers // int b rand(int a); where 0 <= b <= a UUID.rand = function(max){ return Math.floor(Math.random() * (max + 1)); } // end of UUID class file function urlencode( str ) { // http://kevin.vanzonneveld.net // + original by: Philip Peterson // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: AJ // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: travc // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Lars Fischer // + input by: Ratheous // % note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/ // * example 1: urlencode('Kevin van Zonneveld!'); // * returns 1: 'Kevin+van+Zonneveld%21' // * example 2: urlencode('http://kevin.vanzonneveld.net/'); // * returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F' // * example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'); // * returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a' var hash_map = {}, unicodeStr='', hexEscStr=''; var ret = (str+'').toString(); var replacer = function(search, replace, str) { var tmp_arr = []; tmp_arr = str.split(search); return tmp_arr.join(replace); }; // The hash_map is identical to the one in urldecode. hash_map["'"] = '%27'; hash_map['('] = '%28'; hash_map[')'] = '%29'; hash_map['*'] = '%2A'; hash_map['~'] = '%7E'; hash_map['!'] = '%21'; hash_map['%20'] = '+'; hash_map['\u00DC'] = '%DC'; hash_map['\u00FC'] = '%FC'; hash_map['\u00C4'] = '%D4'; hash_map['\u00E4'] = '%E4'; hash_map['\u00D6'] = '%D6'; hash_map['\u00F6'] = '%F6'; hash_map['\u00DF'] = '%DF'; hash_map['\u20AC'] = '%80'; hash_map['\u0081'] = '%81'; hash_map['\u201A'] = '%82'; hash_map['\u0192'] = '%83'; hash_map['\u201E'] = '%84'; hash_map['\u2026'] = '%85'; hash_map['\u2020'] = '%86'; hash_map['\u2021'] = '%87'; hash_map['\u02C6'] = '%88'; hash_map['\u2030'] = '%89'; hash_map['\u0160'] = '%8A'; hash_map['\u2039'] = '%8B'; hash_map['\u0152'] = '%8C'; hash_map['\u008D'] = '%8D'; hash_map['\u017D'] = '%8E'; hash_map['\u008F'] = '%8F'; hash_map['\u0090'] = '%90'; hash_map['\u2018'] = '%91'; hash_map['\u2019'] = '%92'; hash_map['\u201C'] = '%93'; hash_map['\u201D'] = '%94'; hash_map['\u2022'] = '%95'; hash_map['\u2013'] = '%96'; hash_map['\u2014'] = '%97'; hash_map['\u02DC'] = '%98'; hash_map['\u2122'] = '%99'; hash_map['\u0161'] = '%9A'; hash_map['\u203A'] = '%9B'; hash_map['\u0153'] = '%9C'; hash_map['\u009D'] = '%9D'; hash_map['\u017E'] = '%9E'; hash_map['\u0178'] = '%9F'; // Begin with encodeURIComponent, which most resembles PHP's encoding functions ret = encodeURIComponent(ret); for (unicodeStr in hash_map) { hexEscStr = hash_map[unicodeStr]; ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing } // Uppercase for full PHP compatibility return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) { return "%"+m2.toUpperCase(); }); } function http_build_query( formdata, numeric_prefix, arg_separator ) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Legaev Andrey // + improved by: Michael White (http://getsprink.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + revised by: stag019 // - depends on: urlencode // * example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;'); // * returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk' // * example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_'); // * returns 2: 'php=hypertext+processor&myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk' var value, key, tmp = []; var _http_build_query_helper = function (key, val, arg_separator) { var k, tmp = []; if (val === true) { val = "1"; } else if (val === false) { val = "0"; } if (typeof(val) == "array" || typeof(val) == "object") { for (k in val) { if(val[k] !== null) { tmp.push(_http_build_query_helper(key + "[" + k + "]", val[k], arg_separator)); } } return tmp.join(arg_separator); } else if(typeof(val) != "function") { return this.urlencode(key) + "=" + this.urlencode(val); } }; if (!arg_separator) { arg_separator = "&"; } for (key in formdata) { value = formdata[key]; if (numeric_prefix && !isNaN(key)) { key = String(numeric_prefix) + key; } tmp.push(_http_build_query_helper(key, value, arg_separator)); } return tmp.join(arg_separator); } function gen_feedstory_link(link, uuid, st1, st2) { var param_array = {'kt_type' : 'feedstory', - 'kt_st1' : st1, - 'kt_st2' : st2, 'kt_ut' : String(uuid) }; + if( st1 != undefined) + { + param_array['kt_st1'] = st1; + } + if( st2 != undefined) + { + param_array['kt_st2'] = st2; + } var query_str = http_build_query(param_array); var mod_link = append_kt_query_str(link, query_str); return mod_link; } function append_kt_query_str(original_url, query_str) { var position = original_url.indexOf('?'); if(position == -1) { return original_url + "?" + query_str; } else { return original_url + "&" + query_str; } }
rmatei/kt
e9c9c4dd60a01377a8789033768201523e117d15
added handling of ab-testing invite titles
diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index 74d41bd..a5917ef 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,286 +1,295 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' require 'ruby-debug' module Kt class AB_Testing_Manager @@URL_PREFIX = "/abtest/campaign_info"; public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" if force == true url_str += "?f=1" end url = URI.parse(url_str) if url.query.nil? url_str = url.path else url_str = url.path + "?" + url.query end req = Net::HTTP::Get.new(url_str) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true if !json_obj["page_and_messages"].nil? # process message and page together for feed related campaigns page_msg_lst = json_obj["page_and_messages"] weight_array = [] curr_idx = 0 page_msg_lst.each do |pm| w = pm[1] w.times { weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['weight'] = weight_array else # process message list msg_lst = json_obj["messages"] msg_weight_array = [] curr_idx = 0 msg_lst.each do |m| w = m[1] w.times { msg_weight_array << curr_idx } curr_idx += 1 end # process page list page_lst = json_obj['pages'] page_weight_array = [] curr_idx = 0 page_lst.each do |p| w = p[1] w.times { page_weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['msg_weight'] = msg_weight_array store_dict['page_weight'] = page_weight_array end r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end public def get_ab_testing_campaign_handle_index(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return json_obj['handle_index'] end end public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public def get_ab_testing_page_msg_tuple(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_msg_lst = json_obj['page_and_messages'] weight_array = dict['weight'] index = weight_array[rand(weight_array.size)] return page_msg_lst[index] end end public def are_page_message_coupled(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return !json_obj['page_and_messages'].nil? end end def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end def cache_ab_testing_msg_page_tuple(campaign, page_msg_info) @m_selected_msg_page_pair_dict[campaign] = {'page_msg' => page_msg_info} end public def get_selected_page_msg_info(campaign) @m_selected_msg_page_pair_dict[campaign]['page_msg'] end def get_selected_msg_info(campaign) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[2] end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else return page_msg_info[0], page_msg_info[3] end end end def get_selected_msg_info_button(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[3] end end + def get_selected_msg_info_title(campaign) + msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] + if msg_info.nil? + return nil + else + return msg_info[0], msg_info[4] + end + end + def get_selected_page_info(campaign) if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? # invite, notification page_info = @m_selected_msg_page_pair_dict[campaign]['page'] if page_info.nil? return nil else return page_info[0], page_info[2] end else # feed related calls page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] if page_msg_info.nil? return nil else return page_msg_info[0], page_msg_info[2] end end end private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module #mgr = Kt::AB_Testing_Manager.new('56956a4098794fdc98e582f052205b1b', '03df281d926f4e5a9e409cd14f31c060', # 'http://www.kontagent.com', 80) #mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', # 'http://www.kontagent.com', 80) # 'http://kthq.dyndns.org', 9999) # mgr.fetch_ab_testing_data('hello') #puts mgr.get_ab_testing_message('test_u2u_notif') # puts mgr.get_ab_testing_page('hello') diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index 50440cf..ab0d9a4 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,164 +1,169 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'cgi' require 'ruby-debug' module Kt module Rails module KontagentHelpers def kt_get_page_text(campaign) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) return page_text end def kt_get_msg_text(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) return msg_text end def kt_get_msg_buttons(campaign, index) msg_id, msg_buttons = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_button(campaign) if msg_id.nil? return "" end if msg_buttons[index].nil? return "" else msg_buttons[index] end end + def kt_get_msg_title(campaign) + msg_id, msg_title = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_title(campaign) + return msg_title + end + def kt_get_invite_post_link_vo(invite_post_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, uid, session['invite_uuid'], campaign) # session['invite_uuid'] = nil end return url end def kt_clear_invite_tag() session['invite_uuid'] = nil end def kt_get_invite_content_link_vo(invite_content_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, uid, session['invite_uuid'], campaign) #session['invite_uuid'] = nil end return url end def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) #session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) #session['invite_uuid'] = nil end return url end def kt_track_page_view() if Kt::KtAnalytics.instance.m_is_disabled return "" end uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end def kt_get_callback_url() return Kt::KtAnalytics.instance.m_call_back_host + Kt::KtAnalytics.instance.m_call_back_req_uri end # def kt_track_page_view_pm() # uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') # url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) # kt_api_url = "/api" # version = "v1" # kt_api_key = "KT_API_KEY" # kt_secret_key = "KT_SECRET_KEY" # api_func = 'pgr' # arg_hash = {} # arg_hash['ts'] = Time.now.to_s # arg_hash['s'] = uid # keys = arg_hash.keys.sort # sig = '' # keys.each do |key| # sig += key+"="+arg_hash[key].to_s # end # sig += kt_secret_key # arg_hash['an_sig'] = Digest::MD5.hexdigest(sig) # query = arg_hash.to_query # url_str = kt_api_url + "/" + version + "/" + kt_api_key + "/" + api_func + "/?" + query # track_code_str = "<img src='http://api.global.kontagent.net#{url_str}' width='0px' height='0px' />" # return track_code_str # end # for product madness only end end end
rmatei/kt
dc047637f4667edfe8ec2aa83654ebd24e6202d3
added the disable kontagent option
diff --git a/kontagent.yml.tpl b/kontagent.yml.tpl index b2a8f69..067abd8 100644 --- a/kontagent.yml.tpl +++ b/kontagent.yml.tpl @@ -1,140 +1,142 @@ # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. However, if your callback URL # is simply www.example.com/, this value should be left blank. # # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net # Parameter : use_ab # # Description: Set use_ab to true to enable ab_testing. You also need to be granted permissions in order # to have ab testing fully functional. # use_ab: false + +kt_disabled: false \ No newline at end of file diff --git a/kontagent.yml.tpl.multi b/kontagent.yml.tpl.multi index 31ea44e..fa3850e 100644 --- a/kontagent.yml.tpl.multi +++ b/kontagent.yml.tpl.multi @@ -1,138 +1,140 @@ <FACEBOOK_API_KEY>: + kt_disabled: false + # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false # Parameter : use_ab # # Description: Set use_ab to true to enable ab_testing. You also need to be granted permissions in order # to have ab testing fully functional. # use_ab: false ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 8ce462f..aeebe98 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,832 +1,841 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte, :feedpub=>:feedpub, :feedstory=>:feedstory, :multifeedstory=>:multifeedstory} @@S_profile_types = {:profilebox=>:profilebox, :profileinfo=>:profileinfo} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd' @@S_undirected_val = 'u' @@S_profile_val = 'p' @@instance_obj = nil - attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr + attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr, :m_is_disabled def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] elsif request_params.has_key?('fb_sig_canvas_user') r = request_params['fb_sig_canvas_user'] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def gen_ru_cookie_key() return @m_kt_api_key + "_ru" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end # used for profileinfo and profilefbml only def store_ru_key_in_cookie(cookies, uid) - uid_length = uid.to_s.length() tag = uid.to_s cookies[gen_ru_cookie_key()] = {:value => tag, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end + if app_config_map['kt_disabled'].blank? + @m_is_disabled = false + else + @m_is_disabled = app_config_map['kt_disabled'] + end + if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_profile_fbml_link(fbml_txt, st1, st2, owner_id) id, query_str = gen_kt_comm_query_str(:profilebox, nil, st1, st2, nil, nil, owner_id) fbml_txt = fbml_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return fbml_txt end def kt_profile_setFBML_send(uid, st1, st2) arg_hash = { 'tu' => 'profilebox', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_profile_info_link(info_fields, owner_id, st1, st2) id, query_str = gen_kt_comm_query_str(:profileinfo, nil, st1, st2,nil,nil, owner_id) i=0 j=0 info_fields.each do | info_item | item_array = info_item['items'] item_array.each do | item | link = item['link'] info_fields[i]['items'][j]['link'] = append_kt_query_str(link, query_str) j += 1 end i+=1 end return info_fields end def kt_profile_setInfo_send(uid, st1, st2) arg_hash = { 'tu' => 'profileinfo', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_feedstory_link(link, uuid, st1, st2) id, query_str = gen_kt_comm_query_str(:feedstory, nil, st1, st2, nil, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_feedstory_send(uid, uuid, st1, st2) arg_hash = { 'tu' => 'feedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_multifeedstory_link(link, uuid, st1, st2) id, query_str = gen_kt_comm_query_str(:multifeedstory, nil, st1, st2, nil, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_multifeedstory_send(uid, uuid, st1, st2) arg_hash = { 'tu' => 'multifeedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() elsif not cookies[gen_ru_cookie_key()].blank? arg_hash['ru'] = cookies[gen_ru_cookie_key()] cookies.delete gen_ru_cookie_key() end kt_outbound_msg('apa', arg_hash) # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def save_feedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_multifeedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'multifeedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_feedpub_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedpub' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profilebox_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profilebox' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_profileinfo_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = 'profileinfo' arg_hash['s'] = request_params[:kt_owner_uid] store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def kt_outbound_msg(type, arg_hash) + if @m_is_disabled == true + return #short circuit + end + if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end # uid: can simply be one number or an array of uids def increment_goal_count(uid, goal_id, inc) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['gc'+goal_id.to_s] = inc kt_outbound_msg(msg_type, arg_hash) end # goal_counts_assoc_array : { goal_id0 => inc0, goal_id1 => inc1, .... } def increment_multiple_goal_counts(uid, goal_counts_assoc_array) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid goal_counts_assoc_array.each_pair do | k, v| arg_hash['gc'+k.to_s] = v end kt_outbound_msg(msg_type, arg_hash) end def increment_monetization(uid, money_value) msg_type = 'mtu' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['v'] = money_value kt_outbound_msg(msg_type, arg_hash) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def profile_type?(comm_type) @@S_profile_types.has_key?(comm_type) end # if $uuid is provided, then it doesn't generate a new one (directed comm) def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3=nil, uuid_arg=nil, uid_arg=nil) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val elsif profile_type? comm_type dir_val = @@S_profile_val end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val if uuid_arg.nil? uuid = gen_long_uuid() param_array[:kt_ut] = uuid else param_array[:kt_ut] = uuid_arg end elsif dir_val == @@S_profile_val param_array[:kt_owner_uid] = uid_arg end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index 6bfb589..50440cf 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,160 +1,164 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'cgi' require 'ruby-debug' module Kt module Rails module KontagentHelpers def kt_get_page_text(campaign) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) return page_text end def kt_get_msg_text(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) return msg_text end def kt_get_msg_buttons(campaign, index) msg_id, msg_buttons = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_button(campaign) if msg_id.nil? return "" end if msg_buttons[index].nil? return "" else msg_buttons[index] end end def kt_get_invite_post_link_vo(invite_post_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, uid, session['invite_uuid'], campaign) # session['invite_uuid'] = nil end return url end def kt_clear_invite_tag() session['invite_uuid'] = nil end def kt_get_invite_content_link_vo(invite_content_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, uid, session['invite_uuid'], campaign) #session['invite_uuid'] = nil end return url end def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) #session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) #session['invite_uuid'] = nil end return url end def kt_track_page_view() + if Kt::KtAnalytics.instance.m_is_disabled + return "" + end + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end def kt_get_callback_url() return Kt::KtAnalytics.instance.m_call_back_host + Kt::KtAnalytics.instance.m_call_back_req_uri end # def kt_track_page_view_pm() # uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') # url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) # kt_api_url = "/api" # version = "v1" # kt_api_key = "KT_API_KEY" # kt_secret_key = "KT_SECRET_KEY" # api_func = 'pgr' # arg_hash = {} # arg_hash['ts'] = Time.now.to_s # arg_hash['s'] = uid # keys = arg_hash.keys.sort # sig = '' # keys.each do |key| # sig += key+"="+arg_hash[key].to_s # end # sig += kt_secret_key # arg_hash['an_sig'] = Digest::MD5.hexdigest(sig) # query = arg_hash.to_query # url_str = kt_api_url + "/" + version + "/" + kt_api_key + "/" + api_func + "/?" + query # track_code_str = "<img src='http://api.global.kontagent.net#{url_str}' width='0px' height='0px' />" # return track_code_str # end # for product madness only end end end
rmatei/kt
28d114851c0212e277921de04d95efc231af487e
no padded zeros
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 0f1abc3..8ce462f 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,607 +1,603 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte, :feedpub=>:feedpub, :feedstory=>:feedstory, :multifeedstory=>:multifeedstory} @@S_profile_types = {:profilebox=>:profilebox, :profileinfo=>:profileinfo} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd' @@S_undirected_val = 'u' @@S_profile_val = 'p' @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] elsif request_params.has_key?('fb_sig_canvas_user') r = request_params['fb_sig_canvas_user'] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def gen_ru_cookie_key() return @m_kt_api_key + "_ru" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end # used for profileinfo and profilefbml only def store_ru_key_in_cookie(cookies, uid) uid_length = uid.to_s.length() - if uid_length < 16 - tag = ("0" * (16 - uid_length)) + uid.to_s - else - tag = uid.to_s - end + tag = uid.to_s cookies[gen_ru_cookie_key()] = {:value => tag, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_profile_fbml_link(fbml_txt, st1, st2, owner_id) id, query_str = gen_kt_comm_query_str(:profilebox, nil, st1, st2, nil, nil, owner_id) fbml_txt = fbml_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return fbml_txt end def kt_profile_setFBML_send(uid, st1, st2) arg_hash = { 'tu' => 'profilebox', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_profile_info_link(info_fields, owner_id, st1, st2) id, query_str = gen_kt_comm_query_str(:profileinfo, nil, st1, st2,nil,nil, owner_id) i=0 j=0 info_fields.each do | info_item | item_array = info_item['items'] item_array.each do | item | link = item['link'] info_fields[i]['items'][j]['link'] = append_kt_query_str(link, query_str) j += 1 end i+=1 end return info_fields end def kt_profile_setInfo_send(uid, st1, st2) arg_hash = { 'tu' => 'profileinfo', 's' => uid, } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_feedstory_link(link, uuid, st1, st2) id, query_str = gen_kt_comm_query_str(:feedstory, nil, st1, st2, nil, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_feedstory_send(uid, uuid, st1, st2) arg_hash = { 'tu' => 'feedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_multifeedstory_link(link, uuid, st1, st2) id, query_str = gen_kt_comm_query_str(:multifeedstory, nil, st1, st2, nil, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_multifeedstory_send(uid, uuid, st1, st2) arg_hash = { 'tu' => 'multifeedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() elsif not cookies[gen_ru_cookie_key()].blank? arg_hash['ru'] = cookies[gen_ru_cookie_key()] cookies.delete gen_ru_cookie_key() end kt_outbound_msg('apa', arg_hash) # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei'
rmatei/kt
942ee8637f57083591d5a1210eee3228a006eda1
tracking userprofile userinfo
diff --git a/init.rb b/init.rb index 410fc51..deb2dfe 100644 --- a/init.rb +++ b/init.rb @@ -1,57 +1,55 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER puts "loading kt..." require 'facebook/session' - - require 'kt/rails/helpers' - require 'facebooker/rails/publisher' require 'facebook/rails/publisher' -#require 'facebooker/rails/controller' require 'facebook/rails/controller' require 'kt/rails/controller' +require 'facebook/models/user' config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") + if config['mode'] == 'async' require 'starling' require 'starling_ext' require 'kt/queue/queue' require 'kt/queue/processor' require 'kt/queue/task' # Load app applicable Kontagent::Queue::Processor subclasses from app/processors Dir[RAILS_ROOT + '/app/processors/*.rb'].each do |file| require file end end module ::ActionController class Base def self.inherited_with_kt(subclass) inherited_without_kt(subclass) if subclass.to_s == "ApplicationController" subclass.class_eval do subclass.send(:include,Kt::Rails::Controller) end end end #def class << self alias_method_chain :inherited, :kt end end end ActionView::Base.send :include, Kt::Rails::KontagentHelpers diff --git a/lib/facebook/models/user.rb b/lib/facebook/models/user.rb new file mode 100644 index 0000000..e16be4f --- /dev/null +++ b/lib/facebook/models/user.rb @@ -0,0 +1,28 @@ +require 'kt/kt_analytics' +require 'ruby-debug' + +module Facebooker + class User + def set_profile_fbml_with_kontagent(profile_fbml, mobile_fbml, profile_action_fbml, profile_main = nil, subtype1=nil, subtype2=nil) + profile_fbml = Kt::KtAnalytics.instance.gen_profile_fbml_link(profile_fbml, subtype1, subtype2, uid) if !profile_fbml.nil? + mobile_fbml = Kt::KtAnalytics.instance.gen_profile_fbml_link(mobile_fbml, subtype1, subtype2, uid) if !mobile_fbml.nil? + profile_action_fbml = Kt::KtAnalytics.instance.gen_profile_fbml_link(profile_action_fbml, subtype1, subtype2, uid) if !profile_action_fbml.nil? + profile_main = Kt::KtAnalytics.instance.gen_profile_fbml_link(profile_main, subtype1, subtype2, uid) if !profile_main.nil? + + set_profile_fbml_without_kontagent(profile_fbml, mobile_fbml, profile_action_fbml, profile_main) + + Kt::KtAnalytics.instance.kt_profile_setFBML_send(uid, subtype1, subtype2) + end + + def set_profile_info_with_kontagent(title, info_fields, format = :text, subtype1=nil, subtype2=nil) + info_fields = Kt::KtAnalytics.instance.gen_profile_info_link(info_fields, uid, subtype1, subtype2) + set_profile_info_without_kontagent(title, info_fields, format) + Kt::KtAnalytics.instance.kt_profile_setInfo_send(uid, subtype1, subtype2) + end + + alias_method_chain :set_profile_fbml, :kontagent + alias_method_chain :set_profile_info, :kontagent + + end + +end diff --git a/lib/facebook/rails/publisher.rb b/lib/facebook/rails/publisher.rb index e7a20b0..62b9f0e 100644 --- a/lib/facebook/rails/publisher.rb +++ b/lib/facebook/rails/publisher.rb @@ -1,68 +1,68 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER module Facebooker module Rails class Publisher def template(arg) @template = arg end def subtype1(arg) @subtype1 = arg end def subtype2(arg) @subtype2 = arg end def campaign(arg) @campaign = arg end def send_message_with_kontagent(method) @recipients = @recipients.is_a?(Array) ? @recipients : [@recipients] if from.nil? and @recipients.size==1 and ! announcement_notification?(from,_body) @from = @recipients.first end # notifications can # omit the from address raise InvalidSender.new("Sender must be a Facebooker::User") unless from.is_a?(Facebooker::User) || announcement_notification?(from,_body) case _body when Facebooker::Feed::TemplatizedAction,Facebooker::Feed::Action from.publish_action(_body) when Facebooker::Feed::Story @recipients.each {|r| r.publish_story(_body)} when Notification (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, @template, @subtype1, @subtype2, @campaign) when Email from.session.send_email(@recipients, _body.title, _body.text, _body.fbml, @template, @subtype1, @subtype2, @campaign) when Profile # If recipient and from aren't the same person, create a new user object using the # userid from recipient and the session from from if @from != @recipients.first @from = Facebooker::User.new(Facebooker::User.cast_to_facebook_id(@recipients.first),from.session) end - from.set_profile_fbml(_body.profile, _body.mobile_profile, _body.profile_action, _body.profile_main) + @from.set_profile_fbml(_body.profile, _body.mobile_profile, _body.profile_action, _body.profile_main, @subtype1, @subtype2) when Ref @from.session.server_cache.set_ref_handle(_body.handle,_body.fbml) when UserAction @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general, @subtype1, @subtype2, @campaign) else raise UnspecifiedBodyType.new("You must specify a valid send_as") end end alias_method_chain :send_message, :kontagent end end end diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index d979456..0f1abc3 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,740 +1,836 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte, :feedpub=>:feedpub, :feedstory=>:feedstory, :multifeedstory=>:multifeedstory} @@S_profile_types = {:profilebox=>:profilebox, :profileinfo=>:profileinfo} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd' @@S_undirected_val = 'u' @@S_profile_val = 'p' @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] + elsif request_params.has_key?('fb_sig_canvas_user') + r = request_params['fb_sig_canvas_user'] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end + def gen_ru_cookie_key() + return @m_kt_api_key + "_ru" + end + def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end + # used for profileinfo and profilefbml only + def store_ru_key_in_cookie(cookies, uid) + uid_length = uid.to_s.length() + if uid_length < 16 + tag = ("0" * (16 - uid_length)) + uid.to_s + else + tag = uid.to_s + end + cookies[gen_ru_cookie_key()] = {:value => tag, :expired => 10.minutes.from_now } + end + def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end + def gen_profile_fbml_link(fbml_txt, st1, st2, owner_id) + id, query_str = gen_kt_comm_query_str(:profilebox, nil, st1, st2, nil, nil, owner_id) + fbml_txt = fbml_txt.gsub(@@URL_REGEX_STR){|match| + if $1.nil? + append_kt_query_str($2, query_str) + else + $1 + append_kt_query_str($2, query_str) + end + } + return fbml_txt + end + + def kt_profile_setFBML_send(uid, st1, st2) + arg_hash = { + 'tu' => 'profilebox', + 's' => uid, + } + + arg_hash['st1'] = st1 if !st1.nil? + arg_hash['st2'] = st2 if !st2.nil? + + kt_outbound_msg('pst', arg_hash) + end + + def gen_profile_info_link(info_fields, owner_id, st1, st2) + id, query_str = gen_kt_comm_query_str(:profileinfo, nil, st1, st2,nil,nil, owner_id) + + i=0 + j=0 + info_fields.each do | info_item | + item_array = info_item['items'] + item_array.each do | item | + link = item['link'] + info_fields[i]['items'][j]['link'] = append_kt_query_str(link, query_str) + j += 1 + end + i+=1 + end + return info_fields + end + + def kt_profile_setInfo_send(uid, st1, st2) + arg_hash = { + 'tu' => 'profileinfo', + 's' => uid, + } + + arg_hash['st1'] = st1 if !st1.nil? + arg_hash['st2'] = st2 if !st2.nil? + + kt_outbound_msg('pst', arg_hash) + end + def gen_feedstory_link(link, uuid, st1, st2) id, query_str = gen_kt_comm_query_str(:feedstory, nil, st1, st2, nil, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_feedstory_send(uid, uuid, st1, st2) arg_hash = { 'tu' => 'feedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def gen_multifeedstory_link(link, uuid, st1, st2) id, query_str = gen_kt_comm_query_str(:multifeedstory, nil, st1, st2, nil, uuid) r_url = append_kt_query_str(link, query_str) return r_url end def kt_multifeedstory_send(uid, uuid, st1, st2) arg_hash = { 'tu' => 'multifeedstory', 's' => uid, 'u' => uuid } arg_hash['st1'] = st1 if !st1.nil? arg_hash['st2'] = st2 if !st2.nil? kt_outbound_msg('pst', arg_hash) end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() - kt_outbound_msg('apa', arg_hash) elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() - kt_outbound_msg('apa', arg_hash) - else - kt_outbound_msg('apa', arg_hash) + elsif not cookies[gen_ru_cookie_key()].blank? + arg_hash['ru'] = cookies[gen_ru_cookie_key()] + cookies.delete gen_ru_cookie_key() end - + + kt_outbound_msg('apa', arg_hash) + # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def save_feedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_multifeedstory_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'multifeedstory' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end def save_feedpub_click(request_params, cookies) msg_type = 'psr' arg_hash = {} arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['u'] = request_params[:kt_ut] store_ut_key_in_cookie(cookies, request_params[:kt_ut]) arg_hash['tu'] = 'feedpub' arg_hash['r'] = get_fb_param(request_params, 'user') arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) end + def save_profilebox_click(request_params, cookies) + msg_type = 'psr' + arg_hash = {} + arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil + arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil + arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil + arg_hash['tu'] = 'profilebox' + arg_hash['s'] = request_params[:kt_owner_uid] + store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) + arg_hash['r'] = get_fb_param(request_params, 'user') + arg_hash['i'] = get_fb_param(request_params, 'added') + kt_outbound_msg(msg_type, arg_hash) + end + + def save_profileinfo_click(request_params, cookies) + msg_type = 'psr' + arg_hash = {} + arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil + arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil + arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil + arg_hash['tu'] = 'profileinfo' + arg_hash['s'] = request_params[:kt_owner_uid] + store_ru_key_in_cookie(cookies, request_params[:kt_owner_uid]) + arg_hash['r'] = get_fb_param(request_params, 'user') + arg_hash['i'] = get_fb_param(request_params, 'added') + kt_outbound_msg(msg_type, arg_hash) + end + def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end # uid: can simply be one number or an array of uids def increment_goal_count(uid, goal_id, inc) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['gc'+goal_id.to_s] = inc kt_outbound_msg(msg_type, arg_hash) end # goal_counts_assoc_array : { goal_id0 => inc0, goal_id1 => inc1, .... } def increment_multiple_goal_counts(uid, goal_counts_assoc_array) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid goal_counts_assoc_array.each_pair do | k, v| arg_hash['gc'+k.to_s] = v end kt_outbound_msg(msg_type, arg_hash) end def increment_monetization(uid, money_value) msg_type = 'mtu' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['v'] = money_value kt_outbound_msg(msg_type, arg_hash) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def profile_type?(comm_type) @@S_profile_types.has_key?(comm_type) end # if $uuid is provided, then it doesn't generate a new one (directed comm) def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3=nil, uuid_arg=nil, uid_arg=nil) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val elsif profile_type? comm_type dir_val = @@S_profile_val end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val if uuid_arg.nil? uuid = gen_long_uuid() param_array[:kt_ut] = uuid else param_array[:kt_ut] = uuid_arg end elsif dir_val == @@S_profile_val - if uid_arg.nil? - uid = get_fb_param(request_params, 'user') - end - param_array[:kt_owner_uid] = uid + param_array[:kt_owner_uid] = uid_arg end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index d6233b7..9b07a5d 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,219 +1,223 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) if Kt::KtAnalytics.instance.m_ab_testing_mgr.are_page_message_coupled(campaign) page_msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page_msg_tuple(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_page_tuple(campaign, page_msg_info) else page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end end def ajax_kt_feedstory_send Kt::KtAnalytics.instance.kt_feedstory_send(params[:uid], params[:uuid], params[:st1], params[:st2]) render :nothing => true end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing => true end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end if cookies[gen_kt_install_cookie_key()].nil? or cookies[gen_kt_install_cookie_key()].blank? cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} else if cookies[gen_kt_install_cookie_key()] == "0" and params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" Kt::KtAnalytics.instance.save_app_added(params, cookies) cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} end end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) when "ad" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) when "partner" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) when "feedstory" Kt::KtAnalytics.instance.save_feedstory_click(params, cookies) when "multifeedstory" Kt::KtAnalytics.instance.save_multifeedstory_click(params, cookies) when "feedpub" Kt::KtAnalytics.instance.save_feedpub_click(params, cookies) + when "profilebox" + Kt::KtAnalytics.instance.save_profilebox_click(params, cookies) + when "profileinfo" + Kt::KtAnalytics.instance.save_profileinfo_click(params, cookies) else end if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private def gen_kt_install_cookie_key() return "KT_"+Facebooker.api_key+"_installed" end def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
1792da3128e3f8090126d81fb9e2fb240aefdbfc
able to track js feedstory
diff --git a/kt_common.js b/kt_common.js new file mode 100644 index 0000000..8d1d9d5 --- /dev/null +++ b/kt_common.js @@ -0,0 +1,287 @@ +/* + +uuid.js - Version 0.3 +JavaScript Class to create a UUID like identifier + +Copyright (C) 2006-2008, Erik Giberti (AF-Design), All rights reserved. + +This program is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation; either version 2 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 59 Temple +Place, Suite 330, Boston, MA 02111-1307 USA + +The latest version of this file can be downloaded from +http://www.af-design.com/resources/javascript_uuid.php + +HISTORY: +6/5/06 - Initial Release +5/22/08 - Updated code to run faster, removed randrange(min,max) in favor of + a simpler rand(max) function. Reduced overhead by using getTime() + method of date class (suggestion by James Hall). +9/5/08 - Fixed a bug with rand(max) and additional efficiencies pointed out + by Robert Kieffer http://broofa.com/ + +KNOWN ISSUES: +- Still no way to get MAC address in JavaScript +- Research into other versions of UUID show promising possibilities + (more research needed) +- Documentation needs improvement + +*/ + +// On creation of a UUID object, set it's initial value +function UUID(){ + this.id = this.createUUID(); +} + +// When asked what this Object is, lie and return it's value +UUID.prototype.valueOf = function(){ return this.id; } +UUID.prototype.toString = function(){ return this.id; } + +// +// INSTANCE SPECIFIC METHODS +// + +UUID.prototype.createUUID = function(){ + // + // Loose interpretation of the specification DCE 1.1: Remote Procedure Call + // described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37 + // since JavaScript doesn't allow access to internal systems, the last 48 bits + // of the node section is made up using a series of random numbers (6 octets long). + // + var dg = new Date(1582, 10, 15, 0, 0, 0, 0); + var dc = new Date(); + var t = dc.getTime() - dg.getTime(); + var h = ''; + var tl = UUID.getIntegerBits(t,0,31); + var tm = UUID.getIntegerBits(t,32,47); + var thv = UUID.getIntegerBits(t,48,59) + '1'; // version 1, security version is 2 + var csar = UUID.getIntegerBits(UUID.rand(4095),0,7); + var csl = UUID.getIntegerBits(UUID.rand(4095),0,7); + + // since detection of anything about the machine/browser is far to buggy, + // include some more random numbers here + // if NIC or an IP can be obtained reliably, that should be put in + // here instead. + var n = UUID.getIntegerBits(UUID.rand(8191),0,7) + + UUID.getIntegerBits(UUID.rand(8191),8,15) + + UUID.getIntegerBits(UUID.rand(8191),0,7) + + UUID.getIntegerBits(UUID.rand(8191),8,15) + + UUID.getIntegerBits(UUID.rand(8191),0,15); // this last number is two octets long + return tl + h + tm + h + thv + h + csar + csl + h + n; +} + + +// +// GENERAL METHODS (Not instance specific) +// + + +// Pull out only certain bits from a very large integer, used to get the time +// code information for the first part of a UUID. Will return zero's if there +// aren't enough bits to shift where it needs to. +UUID.getIntegerBits = function(val,start,end){ + var base16 = UUID.returnBase(val,16); + var quadArray = new Array(); + var quadString = ''; + var i = 0; + for(i=0;i<base16.length;i++){ + quadArray.push(base16.substring(i,i+1)); + } + for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){ + if(!quadArray[i] || quadArray[i] == '') quadString += '0'; + else quadString += quadArray[i]; + } + return quadString; +} + +// Replaced from the original function to leverage the built in methods in +// JavaScript. Thanks to Robert Kieffer for pointing this one out +UUID.returnBase = function(number, base){ + return (number).toString(base).toUpperCase(); +} + +// pick a random number within a range of numbers +// int b rand(int a); where 0 <= b <= a +UUID.rand = function(max){ + return Math.floor(Math.random() * (max + 1)); +} + +// end of UUID class file + + + +function urlencode( str ) { + // http://kevin.vanzonneveld.net + // + original by: Philip Peterson + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + input by: AJ + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + improved by: Brett Zamir (http://brett-zamir.me) + // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + input by: travc + // + input by: Brett Zamir (http://brett-zamir.me) + // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + improved by: Lars Fischer + // + input by: Ratheous + // % note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/ + // * example 1: urlencode('Kevin van Zonneveld!'); + // * returns 1: 'Kevin+van+Zonneveld%21' + // * example 2: urlencode('http://kevin.vanzonneveld.net/'); + // * returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F' + // * example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'); + // * returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a' + + var hash_map = {}, unicodeStr='', hexEscStr=''; + var ret = (str+'').toString(); + + var replacer = function(search, replace, str) { + var tmp_arr = []; + tmp_arr = str.split(search); + return tmp_arr.join(replace); + }; + + // The hash_map is identical to the one in urldecode. + hash_map["'"] = '%27'; + hash_map['('] = '%28'; + hash_map[')'] = '%29'; + hash_map['*'] = '%2A'; + hash_map['~'] = '%7E'; + hash_map['!'] = '%21'; + hash_map['%20'] = '+'; + hash_map['\u00DC'] = '%DC'; + hash_map['\u00FC'] = '%FC'; + hash_map['\u00C4'] = '%D4'; + hash_map['\u00E4'] = '%E4'; + hash_map['\u00D6'] = '%D6'; + hash_map['\u00F6'] = '%F6'; + hash_map['\u00DF'] = '%DF'; + hash_map['\u20AC'] = '%80'; + hash_map['\u0081'] = '%81'; + hash_map['\u201A'] = '%82'; + hash_map['\u0192'] = '%83'; + hash_map['\u201E'] = '%84'; + hash_map['\u2026'] = '%85'; + hash_map['\u2020'] = '%86'; + hash_map['\u2021'] = '%87'; + hash_map['\u02C6'] = '%88'; + hash_map['\u2030'] = '%89'; + hash_map['\u0160'] = '%8A'; + hash_map['\u2039'] = '%8B'; + hash_map['\u0152'] = '%8C'; + hash_map['\u008D'] = '%8D'; + hash_map['\u017D'] = '%8E'; + hash_map['\u008F'] = '%8F'; + hash_map['\u0090'] = '%90'; + hash_map['\u2018'] = '%91'; + hash_map['\u2019'] = '%92'; + hash_map['\u201C'] = '%93'; + hash_map['\u201D'] = '%94'; + hash_map['\u2022'] = '%95'; + hash_map['\u2013'] = '%96'; + hash_map['\u2014'] = '%97'; + hash_map['\u02DC'] = '%98'; + hash_map['\u2122'] = '%99'; + hash_map['\u0161'] = '%9A'; + hash_map['\u203A'] = '%9B'; + hash_map['\u0153'] = '%9C'; + hash_map['\u009D'] = '%9D'; + hash_map['\u017E'] = '%9E'; + hash_map['\u0178'] = '%9F'; + + // Begin with encodeURIComponent, which most resembles PHP's encoding functions + ret = encodeURIComponent(ret); + + for (unicodeStr in hash_map) { + hexEscStr = hash_map[unicodeStr]; + ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing + } + + // Uppercase for full PHP compatibility + return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) { + return "%"+m2.toUpperCase(); + }); +} + +function http_build_query( formdata, numeric_prefix, arg_separator ) { + // http://kevin.vanzonneveld.net + // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + improved by: Legaev Andrey + // + improved by: Michael White (http://getsprink.com) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + revised by: stag019 + // - depends on: urlencode + // * example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;'); + // * returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk' + // * example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_'); + // * returns 2: 'php=hypertext+processor&myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk' + + var value, key, tmp = []; + + var _http_build_query_helper = function (key, val, arg_separator) { + var k, tmp = []; + if (val === true) { + val = "1"; + } else if (val === false) { + val = "0"; + } + if (typeof(val) == "array" || typeof(val) == "object") { + for (k in val) { + if(val[k] !== null) { + tmp.push(_http_build_query_helper(key + "[" + k + "]", val[k], arg_separator)); + } + } + return tmp.join(arg_separator); + } else if(typeof(val) != "function") { + return this.urlencode(key) + "=" + this.urlencode(val); + } + }; + + if (!arg_separator) { + arg_separator = "&"; + } + for (key in formdata) { + value = formdata[key]; + if (numeric_prefix && !isNaN(key)) { + key = String(numeric_prefix) + key; + } + tmp.push(_http_build_query_helper(key, value, arg_separator)); + } + + return tmp.join(arg_separator); +} + + +function gen_feedstory_link(link, uuid, st1, st2) +{ + var param_array = {'kt_type' : 'feedstory', + 'kt_st1' : st1, + 'kt_st2' : st2, + 'kt_ut' : String(uuid) }; + var query_str = http_build_query(param_array); + + var mod_link = append_kt_query_str(link, query_str); + return mod_link; +} + +function append_kt_query_str(original_url, query_str) +{ + var position = original_url.indexOf('?'); + if(position == -1) + { + return original_url + "?" + query_str; + } + else + { + return original_url + "&" + query_str; + } +} + diff --git a/kt_facebooker.js b/kt_facebooker.js new file mode 100644 index 0000000..db6ea83 --- /dev/null +++ b/kt_facebooker.js @@ -0,0 +1,11 @@ +function feedstory_send(url_prefix, uid, uuid, st1, st2) +{ + var img = document.createElement('img'); + + var param_array = { + 'uid' : String(uid), + 'uuid' : String(uuid) + }; + var query_str = http_build_query(param_array); + img.src = url_prefix+'/ajax_kt_feedstory_send/?' + query_str; +} \ No newline at end of file diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 5267c82..d6233b7 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,213 +1,219 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) if Kt::KtAnalytics.instance.m_ab_testing_mgr.are_page_message_coupled(campaign) page_msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page_msg_tuple(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_page_tuple(campaign, page_msg_info) else page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end end + + + def ajax_kt_feedstory_send + Kt::KtAnalytics.instance.kt_feedstory_send(params[:uid], params[:uuid], params[:st1], params[:st2]) + render :nothing => true + end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) - render :nothing + render :nothing => true end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end if cookies[gen_kt_install_cookie_key()].nil? or cookies[gen_kt_install_cookie_key()].blank? cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} else if cookies[gen_kt_install_cookie_key()] == "0" and params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" Kt::KtAnalytics.instance.save_app_added(params, cookies) cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} end end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) when "ad" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) when "partner" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) when "feedstory" Kt::KtAnalytics.instance.save_feedstory_click(params, cookies) when "multifeedstory" Kt::KtAnalytics.instance.save_multifeedstory_click(params, cookies) when "feedpub" Kt::KtAnalytics.instance.save_feedpub_click(params, cookies) else end if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private def gen_kt_install_cookie_key() return "KT_"+Facebooker.api_key+"_installed" end def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index edbd52d..6bfb589 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,156 +1,160 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'cgi' require 'ruby-debug' module Kt module Rails module KontagentHelpers def kt_get_page_text(campaign) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) return page_text end def kt_get_msg_text(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) return msg_text end def kt_get_msg_buttons(campaign, index) msg_id, msg_buttons = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_button(campaign) if msg_id.nil? return "" end if msg_buttons[index].nil? return "" else msg_buttons[index] end end def kt_get_invite_post_link_vo(invite_post_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, uid, session['invite_uuid'], campaign) # session['invite_uuid'] = nil end return url end def kt_clear_invite_tag() session['invite_uuid'] = nil end def kt_get_invite_content_link_vo(invite_content_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, uid, session['invite_uuid'], campaign) #session['invite_uuid'] = nil end return url end def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) #session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) #session['invite_uuid'] = nil end return url end def kt_track_page_view() uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end + def kt_get_callback_url() + return Kt::KtAnalytics.instance.m_call_back_host + Kt::KtAnalytics.instance.m_call_back_req_uri + end + # def kt_track_page_view_pm() # uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') # url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) # kt_api_url = "/api" # version = "v1" # kt_api_key = "KT_API_KEY" # kt_secret_key = "KT_SECRET_KEY" # api_func = 'pgr' # arg_hash = {} # arg_hash['ts'] = Time.now.to_s # arg_hash['s'] = uid # keys = arg_hash.keys.sort # sig = '' # keys.each do |key| # sig += key+"="+arg_hash[key].to_s # end # sig += kt_secret_key # arg_hash['an_sig'] = Digest::MD5.hexdigest(sig) # query = arg_hash.to_query # url_str = kt_api_url + "/" + version + "/" + kt_api_key + "/" + api_func + "/?" + query # track_code_str = "<img src='http://api.global.kontagent.net#{url_str}' width='0px' height='0px' />" # return track_code_str # end # for product madness only end end end
rmatei/kt
e00464254d1f2d2e0b42933b41fc11d030331e87
tracking feedstory, multifeedstory fbml and feedpub.
diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb index b4e6ff4..9c243be 100644 --- a/lib/facebook/rails/controller.rb +++ b/lib/facebook/rails/controller.rb @@ -1,25 +1,57 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' module Facebooker module Rails module Controller def application_is_not_installed_by_facebook_user_with_kontagent if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") redirect_to session[:facebook_session].install_url else local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") end end #application_is_not_installed_by_facebook_user_with_kontagent + + def gen_uuid() + Kt::KtAnalytics.instance.gen_long_uuid() + end + def gen_feedstory_link(link, uuid, st1=nil, st2=nil) + Kt::KtAnalytics.instance.gen_feedstory_link(link , uuid, st1, st2) + end + + def kt_feedstory_send(uuid, st1=nil, st2=nil) + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + Kt::KtAnalytics.instance.kt_feedstory_send(uid, uuid, st1, st2) + end + + def gen_multifeedstory_link(link, uuid, st1=nil, st2=nil) + Kt::KtAnalytics.instance.gen_multifeedstory_link(link, uuid, st1, st2) + end + + def kt_multifeedstory_send(uuid, st1=nil, st2=nil) + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + Kt::KtAnalytics.instance.kt_multifeedstory_send(uid, uuid, st1, st2) + end + + def kt_increment_goal_count(goal_id, inc) + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + Kt::KtAnalytics.instance.increment_goal_count(uid, goal_id, inc) + end + + def kt_increment_multiple_goal_counts(assoc_array) + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + Kt::KtAnalytics.instance.increment_multiple_goal_counts(uid, assoc_array) + end + alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent end #module Controller end end diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb index 55bf432..6359e91 100644 --- a/lib/facebook/session.rb +++ b/lib/facebook/session.rb @@ -1,149 +1,154 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'ruby-debug' module Facebooker class Session def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) if !campaign.nil? # ab testing msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nt, nil, campaign, msg_id, page_id, msg_txt) else uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) end r = send_notification_without_kontagent(user_ids, fbml, email_fbml) if !r.blank? arg_hash = { 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } if source_user.nil? arg_hash['s'] = 0.to_s else arg_hash['s'] = source_user.id.to_s end arg_hash['t'] = template_id.to_s unless template_id.nil? if !campaign.nil? arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) else arg_hash['st1'] = st1 arg_hash['st2'] = st2 end Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) end end def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) if !campaign.nil? # ab testing msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) if fbml != nil uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nte, nil, campaign, msg_id, page_id, msg_txt) else uuid = Kt::KtAnalytics.instance.gen_long_uuid end else if fbml != nil uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, template_id, st1, st2, st3) else uuid = Kt::KtAnalytics.instance.gen_long_uuid end end r = send_email_without_kontagent(user_ids, subject, text, fbml) if !r.blank? arg_hash = { 's' => @user.id.to_s , 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } arg_hash['t'] = template_id.to_s unless template_id.nil? if !campaign.nil? arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) else arg_hash['st1'] = st1 arg_hash['st2'] = st2 end Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) end end # if st2 is set to m{d} and st3 is set to p{d}, we'll assume that it's using ab_testing data. def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil, campaign=nil) if !campaign.nil? msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) st1 = campaign st2 = msg_id st3 = page_id end + uuid = 0 + if(data != nil) data.each_pair do |key,value | if key == :image if !campaign.nil? - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(value[:href], :fdp, - bundle_id, st1, st2, st3, campaign) + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(value[:href], :feedpub, + nil, st1, st2, st3, campaign) else - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, - bundle_id, st1, st2) + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :feedpub, + nil, st1, st2) end value[:href] = fbml data[key] = value # do we even need this line? elsif key == :flash elsif key == :mp3 #Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) elsif key == :video else if !campaign.nil? - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href_vo(value, :fdp, bundle_id, st1, st2, st3) + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href_vo(value, :feedpub, nil, st1, st2, st3) else - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :feedpub, nil, st1, st2) end data[key] = fbml end end end data['KT_AB_MSG'] = msg_txt if !campaign.nil? r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) if !r.blank? arg_hash = { - 'pt' => 4, 's' => @user.id.to_s, - 't' => bundle_id + 'tu' => 'feedpub' } + arg_hash['u'] = uuid if !uuid.nil? + arg_hash['tg'] = target_ids if !target_ids.nil? + arg_hash['st1'] = st1 if !st1.nil? + arg_hash['st2'] = st2 if !st2.nil? - Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) + Kt::KtAnalytics.instance.kt_outbound_msg('pst', arg_hash) end end alias_method_chain :send_notification, :kontagent alias_method_chain :send_email, :kontagent alias_method_chain :publish_user_action, :kontagent end end diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index c82502e..d979456 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,645 +1,740 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ - @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} - @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} + @@S_undirected_types = {:pr=>:pr, :ad=>:ad, :ap=>:ap} + @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte, :feedpub=>:feedpub, :feedstory=>:feedstory, :multifeedstory=>:multifeedstory} + @@S_profile_types = {:profilebox=>:profilebox, :profileinfo=>:profileinfo} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} - @@S_directed_val = 'd'; - @@S_undirected_val = 'u'; + @@S_directed_val = 'd' + @@S_undirected_val = 'u' + @@S_profile_val = 'p' @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end + def gen_feedstory_link(link, uuid, st1, st2) + id, query_str = gen_kt_comm_query_str(:feedstory, nil, st1, st2, nil, uuid) + r_url = append_kt_query_str(link, query_str) + return r_url + end + + def kt_feedstory_send(uid, uuid, st1, st2) + arg_hash = { + 'tu' => 'feedstory', + 's' => uid, + 'u' => uuid + } + + arg_hash['st1'] = st1 if !st1.nil? + arg_hash['st2'] = st2 if !st2.nil? + + kt_outbound_msg('pst', arg_hash) + end + + def gen_multifeedstory_link(link, uuid, st1, st2) + id, query_str = gen_kt_comm_query_str(:multifeedstory, nil, st1, st2, nil, uuid) + r_url = append_kt_query_str(link, query_str) + return r_url + end + + def kt_multifeedstory_send(uid, uuid, st1, st2) + arg_hash = { + 'tu' => 'multifeedstory', + 's' => uid, + 'u' => uuid + } + + arg_hash['st1'] = st1 if !st1.nil? + arg_hash['st2'] = st2 if !st2.nil? + + kt_outbound_msg('pst', arg_hash) + end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end - + def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() kt_outbound_msg('apa', arg_hash) elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() kt_outbound_msg('apa', arg_hash) else kt_outbound_msg('apa', arg_hash) end # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end + def save_feedstory_click(request_params, cookies) + msg_type = 'psr' + arg_hash = {} + arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil + arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil + arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil + arg_hash['u'] = request_params[:kt_ut] + store_ut_key_in_cookie(cookies, request_params[:kt_ut]) + arg_hash['tu'] = 'feedstory' + arg_hash['r'] = get_fb_param(request_params, 'user') + arg_hash['i'] = get_fb_param(request_params, 'added') + kt_outbound_msg(msg_type, arg_hash) + end + + def save_multifeedstory_click(request_params, cookies) + msg_type = 'psr' + arg_hash = {} + arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil + arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil + arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil + arg_hash['u'] = request_params[:kt_ut] + store_ut_key_in_cookie(cookies, request_params[:kt_ut]) + arg_hash['tu'] = 'multifeedstory' + arg_hash['r'] = get_fb_param(request_params, 'user') + arg_hash['i'] = get_fb_param(request_params, 'added') + kt_outbound_msg(msg_type, arg_hash) + end + + def save_feedpub_click(request_params, cookies) + msg_type = 'psr' + arg_hash = {} + arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil + arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil + arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil + arg_hash['u'] = request_params[:kt_ut] + store_ut_key_in_cookie(cookies, request_params[:kt_ut]) + arg_hash['tu'] = 'feedpub' + arg_hash['r'] = get_fb_param(request_params, 'user') + arg_hash['i'] = get_fb_param(request_params, 'added') + kt_outbound_msg(msg_type, arg_hash) + end + def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end # uid: can simply be one number or an array of uids def increment_goal_count(uid, goal_id, inc) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid - arg_hash['gc'+goal_id] = inc + arg_hash['gc'+goal_id.to_s] = inc kt_outbound_msg(msg_type, arg_hash) end # goal_counts_assoc_array : { goal_id0 => inc0, goal_id1 => inc1, .... } def increment_multiple_goal_counts(uid, goal_counts_assoc_array) msg_type = 'gci' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid goal_counts_assoc_array.each_pair do | k, v| - arg_hash['gc'+k] = v + arg_hash['gc'+k.to_s] = v end kt_outbound_msg(msg_type, arg_hash) end def increment_monetization(uid, money_value) msg_type = 'mtu' arg_hash = {} arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid arg_hash['v'] = money_value kt_outbound_msg(msg_type, arg_hash) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end + + def profile_type?(comm_type) + @@S_profile_types.has_key?(comm_type) + end - - def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) + # if $uuid is provided, then it doesn't generate a new one (directed comm) + def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3=nil, + uuid_arg=nil, uid_arg=nil) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val - else - # profile? + elsif profile_type? comm_type + dir_val = @@S_profile_val end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val - uuid = gen_long_uuid() - param_array[:kt_ut] = uuid + if uuid_arg.nil? + uuid = gen_long_uuid() + param_array[:kt_ut] = uuid + else + param_array[:kt_ut] = uuid_arg + end + elsif dir_val == @@S_profile_val + if uid_arg.nil? + uid = get_fb_param(request_params, 'user') + end + param_array[:kt_owner_uid] = uid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 238d7f8..5267c82 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,205 +1,213 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) if Kt::KtAnalytics.instance.m_ab_testing_mgr.are_page_message_coupled(campaign) page_msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page_msg_tuple(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_page_tuple(campaign, page_msg_info) else page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end if cookies[gen_kt_install_cookie_key()].nil? or cookies[gen_kt_install_cookie_key()].blank? cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} else if cookies[gen_kt_install_cookie_key()] == "0" and params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" Kt::KtAnalytics.instance.save_app_added(params, cookies) cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} end end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) - when "fdp" + when "ad" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) + when "partner" + short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) + when "feedstory" + Kt::KtAnalytics.instance.save_feedstory_click(params, cookies) + when "multifeedstory" + Kt::KtAnalytics.instance.save_multifeedstory_click(params, cookies) + when "feedpub" + Kt::KtAnalytics.instance.save_feedpub_click(params, cookies) else end if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private def gen_kt_install_cookie_key() return "KT_"+Facebooker.api_key+"_installed" end def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index c8c7305..edbd52d 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,125 +1,156 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'cgi' require 'ruby-debug' module Kt module Rails module KontagentHelpers def kt_get_page_text(campaign) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) return page_text end def kt_get_msg_text(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) return msg_text end def kt_get_msg_buttons(campaign, index) msg_id, msg_buttons = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_button(campaign) if msg_id.nil? return "" end if msg_buttons[index].nil? return "" else msg_buttons[index] end end def kt_get_invite_post_link_vo(invite_post_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, uid, session['invite_uuid'], campaign) # session['invite_uuid'] = nil end return url end def kt_clear_invite_tag() session['invite_uuid'] = nil end def kt_get_invite_content_link_vo(invite_content_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, uid, session['invite_uuid'], campaign) #session['invite_uuid'] = nil end return url end def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) #session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) #session['invite_uuid'] = nil end return url end def kt_track_page_view() uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end +# def kt_track_page_view_pm() +# uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') +# url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) + +# kt_api_url = "/api" +# version = "v1" +# kt_api_key = "KT_API_KEY" +# kt_secret_key = "KT_SECRET_KEY" +# api_func = 'pgr' + +# arg_hash = {} +# arg_hash['ts'] = Time.now.to_s +# arg_hash['s'] = uid + +# keys = arg_hash.keys.sort +# sig = '' +# keys.each do |key| +# sig += key+"="+arg_hash[key].to_s +# end + +# sig += kt_secret_key + +# arg_hash['an_sig'] = Digest::MD5.hexdigest(sig) +# query = arg_hash.to_query + +# url_str = kt_api_url + "/" + version + "/" + kt_api_key + "/" + api_func + "/?" + query + +# track_code_str = "<img src='http://api.global.kontagent.net#{url_str}' width='0px' height='0px' />" +# return track_code_str +# end # for product madness only + end end end
rmatei/kt
30c02dad60e2a5f5ef21e03d325f58cf30241b20
ab testing for feed related stuff
diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index b4a33cc..74d41bd 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,214 +1,286 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' require 'ruby-debug' module Kt class AB_Testing_Manager @@URL_PREFIX = "/abtest/campaign_info"; public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" if force == true url_str += "?f=1" end url = URI.parse(url_str) if url.query.nil? url_str = url.path else url_str = url.path + "?" + url.query end req = Net::HTTP::Get.new(url_str) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true - msg_lst = json_obj["messages"] - msg_weight_array = [] - curr_idx = 0 - - # process message list - msg_lst.each do |m| - w = m[1] - w.times { msg_weight_array << curr_idx } - curr_idx += 1 - end - - # process page list - page_lst = json_obj['pages'] - page_weight_array = [] - curr_idx = 0 - page_lst.each do |p| - w = p[1] - w.times { page_weight_array << curr_idx } - curr_idx += 1 + if !json_obj["page_and_messages"].nil? + # process message and page together for feed related campaigns + page_msg_lst = json_obj["page_and_messages"] + weight_array = [] + curr_idx = 0 + + page_msg_lst.each do |pm| + w = pm[1] + w.times { weight_array << curr_idx } + curr_idx += 1 + end + + store_dict = {} + store_dict['json'] = json_obj + store_dict['weight'] = weight_array + else + # process message list + msg_lst = json_obj["messages"] + msg_weight_array = [] + curr_idx = 0 + + msg_lst.each do |m| + w = m[1] + w.times { msg_weight_array << curr_idx } + curr_idx += 1 + end + + # process page list + page_lst = json_obj['pages'] + page_weight_array = [] + curr_idx = 0 + page_lst.each do |p| + w = p[1] + w.times { page_weight_array << curr_idx } + curr_idx += 1 + end + + store_dict = {} + store_dict['json'] = json_obj + store_dict['msg_weight'] = msg_weight_array + store_dict['page_weight'] = page_weight_array end - store_dict = {} - store_dict['json'] = json_obj - store_dict['msg_weight'] = msg_weight_array - store_dict['page_weight'] = page_weight_array - r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) + else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end public def get_ab_testing_campaign_handle_index(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return json_obj['handle_index'] end end public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public + def get_ab_testing_page_msg_tuple(campaign) + dict = get_ab_helper(campaign) + if dict.nil? + return nil + else + json_obj = dict['json'] + page_msg_lst = json_obj['page_and_messages'] + weight_array = dict['weight'] + index = weight_array[rand(weight_array.size)] + return page_msg_lst[index] + end + end + + public + def are_page_message_coupled(campaign) + dict = get_ab_helper(campaign) + if dict.nil? + return nil + else + json_obj = dict['json'] + return !json_obj['page_and_messages'].nil? + end + end + def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end + def cache_ab_testing_msg_page_tuple(campaign, page_msg_info) + @m_selected_msg_page_pair_dict[campaign] = {'page_msg' => page_msg_info} + end + public + def get_selected_page_msg_info(campaign) + @m_selected_msg_page_pair_dict[campaign]['page_msg'] + end + def get_selected_msg_info(campaign) - msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] - if msg_info.nil? - return nil + if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? + # invite, notification + msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] + if msg_info.nil? + return nil + else + return msg_info[0], msg_info[2] + end else - return msg_info[0], msg_info[2] + # feed related calls + page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] + if page_msg_info.nil? + return nil + else + return page_msg_info[0], page_msg_info[3] + end end end def get_selected_msg_info_button(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[3] end end def get_selected_page_info(campaign) - page_info = @m_selected_msg_page_pair_dict[campaign]['page'] - if page_info.nil? - return nil + if @m_selected_msg_page_pair_dict[campaign]['page_msg'].nil? + # invite, notification + page_info = @m_selected_msg_page_pair_dict[campaign]['page'] + if page_info.nil? + return nil + else + return page_info[0], page_info[2] + end else - return page_info[0], page_info[2] + # feed related calls + page_msg_info = @m_selected_msg_page_pair_dict[campaign]['page_msg'] + if page_msg_info.nil? + return nil + else + return page_msg_info[0], page_msg_info[2] + end end end private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module #mgr = Kt::AB_Testing_Manager.new('56956a4098794fdc98e582f052205b1b', '03df281d926f4e5a9e409cd14f31c060', # 'http://www.kontagent.com', 80) #mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', # 'http://www.kontagent.com', 80) # 'http://kthq.dyndns.org', 9999) # mgr.fetch_ab_testing_data('hello') #puts mgr.get_ab_testing_message('test_u2u_notif') # puts mgr.get_ab_testing_page('hello') diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 278ce2a..c82502e 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -39,579 +39,607 @@ module Kt end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() kt_outbound_msg('apa', arg_hash) elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() kt_outbound_msg('apa', arg_hash) else kt_outbound_msg('apa', arg_hash) end # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end + # uid: can simply be one number or an array of uids + def increment_goal_count(uid, goal_id, inc) + msg_type = 'gci' + arg_hash = {} + arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid + arg_hash['gc'+goal_id] = inc + kt_outbound_msg(msg_type, arg_hash) + end + + # goal_counts_assoc_array : { goal_id0 => inc0, goal_id1 => inc1, .... } + def increment_multiple_goal_counts(uid, goal_counts_assoc_array) + msg_type = 'gci' + arg_hash = {} + arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid + goal_counts_assoc_array.each_pair do | k, v| + arg_hash['gc'+k] = v + end + kt_outbound_msg(msg_type, arg_hash) + end + + def increment_monetization(uid, money_value) + msg_type = 'mtu' + arg_hash = {} + arg_hash['s'] = uid.is_a?(Array)? uid * "," : uid + arg_hash['v'] = money_value + kt_outbound_msg(msg_type, arg_hash) + end + private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index 7b8c6f2..4fe2a5e 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,142 +1,143 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER #require 'socket' require 'net/http' require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port if @m_host == "api.geo.kontagent.net" @m_ip = fetch_ip() else @m_ip = host end end def _fetch_ip_helper(host_name_str, port) ip_lst = Socket.getaddrinfo(host_name_str, 'http') ip_lst.sort_by{ rand } selected_ip = nil ip_lst.each do |ip_info| ip_str = ip_info[3] socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(port, ip_str) status = -1 timeout(2) do status = socket.connect(sockaddr) end if status == 0 selected_ip = ip_str break end end #loop return selected_ip end # _fetch_ip_helper def fetch_ip() selected_ip = _fetch_ip_helper(@m_host, @m_port) if selected_ip.nil? selected_ip = _fetch_ip_helper("api.global.kontagent.net", 80) end return selected_ip end public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(@m_port, @m_ip) connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN + # socket is already connected #connected = false #puts "Errno::EISCONN!!" rescue connected = false puts "Errno during socket.connect_nonblock" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" buf << "Host:" + @m_ip + ":" + @m_port.to_s + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end sig += secret_key arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test #comm = Kt::KtComm.new('kthq.dyndns.org', '8080') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'}) diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 408fa15..238d7f8 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,200 +1,205 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) - page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) - msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) - Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) + if Kt::KtAnalytics.instance.m_ab_testing_mgr.are_page_message_coupled(campaign) + page_msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page_msg_tuple(campaign) + Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_page_tuple(campaign, page_msg_info) + else + page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) + msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) + Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) + end end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end if cookies[gen_kt_install_cookie_key()].nil? or cookies[gen_kt_install_cookie_key()].blank? cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} else if cookies[gen_kt_install_cookie_key()] == "0" and params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" Kt::KtAnalytics.instance.save_app_added(params, cookies) cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} end end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) else end if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private def gen_kt_install_cookie_key() return "KT_"+Facebooker.api_key+"_installed" end def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
68479b2369fc1546aaccf552d0fc72736c69603b
Errno:EISCONN was mishandled
diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index 08c3d0a..7b8c6f2 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,140 +1,142 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER #require 'socket' require 'net/http' require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port if @m_host == "api.geo.kontagent.net" @m_ip = fetch_ip() else @m_ip = host end end def _fetch_ip_helper(host_name_str, port) ip_lst = Socket.getaddrinfo(host_name_str, 'http') ip_lst.sort_by{ rand } selected_ip = nil ip_lst.each do |ip_info| ip_str = ip_info[3] socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(port, ip_str) status = -1 timeout(2) do status = socket.connect(sockaddr) end if status == 0 selected_ip = ip_str break end end #loop return selected_ip end # _fetch_ip_helper def fetch_ip() selected_ip = _fetch_ip_helper(@m_host, @m_port) if selected_ip.nil? selected_ip = _fetch_ip_helper("api.global.kontagent.net", 80) end return selected_ip end public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(@m_port, @m_ip) connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN + #connected = false + #puts "Errno::EISCONN!!" + rescue connected = false - puts "Errno::EISCONN!!" + puts "Errno during socket.connect_nonblock" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" buf << "Host:" + @m_ip + ":" + @m_port.to_s + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end sig += secret_key arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) - + query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test - -#comm = Kontagent::Kt_Comm.new('67.102.65.65') +#comm = Kt::KtComm.new('kthq.dyndns.org', '8080') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'})
rmatei/kt
05a67724b64999c644fc656fb5bc23aa735fcdbb
forgot to append the secret key prior to invoking md5 hash
diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index 8f0600c..08c3d0a 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,138 +1,140 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER #require 'socket' require 'net/http' require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port if @m_host == "api.geo.kontagent.net" @m_ip = fetch_ip() else @m_ip = host end end def _fetch_ip_helper(host_name_str, port) ip_lst = Socket.getaddrinfo(host_name_str, 'http') ip_lst.sort_by{ rand } selected_ip = nil ip_lst.each do |ip_info| ip_str = ip_info[3] socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(port, ip_str) status = -1 timeout(2) do status = socket.connect(sockaddr) end if status == 0 selected_ip = ip_str break end end #loop return selected_ip end # _fetch_ip_helper def fetch_ip() selected_ip = _fetch_ip_helper(@m_host, @m_port) if selected_ip.nil? selected_ip = _fetch_ip_helper("api.global.kontagent.net", 80) end return selected_ip end public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(@m_port, @m_ip) connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN connected = false puts "Errno::EISCONN!!" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" buf << "Host:" + @m_ip + ":" + @m_port.to_s + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end + sig += secret_key + arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test #comm = Kontagent::Kt_Comm.new('67.102.65.65') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'})
rmatei/kt
811e4cdb9e44f9797b7d32b3371b8b3bd0427b25
Fix nil error to make it possible to run outside of a canvas environment
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 71db83c..c00ab10 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,200 +1,200 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) # controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end if cookies[gen_kt_install_cookie_key()].nil? or cookies[gen_kt_install_cookie_key()].blank? cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} else if cookies[gen_kt_install_cookie_key()] == "0" and params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" Kt::KtAnalytics.instance.save_app_added(params, cookies) cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} end end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) else end if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private def gen_kt_install_cookie_key() - return "KT_"+Facebooker.api_key+"_installed" + return "KT_#{Facebooker.api_key}_installed" end def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
a306cd3793c3869c389505494364493ac72e4780
force back to clean branch
diff --git a/init.rb b/init.rb index 9cc816c..410fc51 100644 --- a/init.rb +++ b/init.rb @@ -1,57 +1,57 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER puts "loading kt..." require 'facebook/session' require 'kt/rails/helpers' require 'facebooker/rails/publisher' require 'facebook/rails/publisher' #require 'facebooker/rails/controller' require 'facebook/rails/controller' require 'kt/rails/controller' config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") if config['mode'] == 'async' require 'starling' require 'starling_ext' require 'kt/queue/queue' require 'kt/queue/processor' require 'kt/queue/task' # Load app applicable Kontagent::Queue::Processor subclasses from app/processors Dir[RAILS_ROOT + '/app/processors/*.rb'].each do |file| require file end end module ::ActionController class Base def self.inherited_with_kt(subclass) inherited_without_kt(subclass) if subclass.to_s == "ApplicationController" subclass.class_eval do subclass.send(:include,Kt::Rails::Controller) end end end #def class << self alias_method_chain :inherited, :kt end end end ActionView::Base.send :include, Kt::Rails::KontagentHelpers diff --git a/install.rb b/install.rb index 906cff2..aaaf2d0 100644 --- a/install.rb +++ b/install.rb @@ -1,20 +1,20 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER # Install hook code here require 'fileutils' require 'rubygems' #require 'ruby-debug' #xxx if ARGV.size != 2 puts "Failure: you need to pass in the controller_name" else controller_name = ARGV[1] handle_iframe_html_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.html.erb") handle_iframe_fbml_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.fbml.erb") kontagent_yml_dst = File.join(RAILS_ROOT, "config", "kontagent.yml") puts "copying kontagent.yml.erb to #{kontagent_yml_dst}" FileUtils.cp( File.join(RAILS_ROOT, "vendor", "plugins", "kt", 'kontagent.yml.tpl'), kontagent_yml_dst ) unless File.exists?( kontagent_yml_dst ) end diff --git a/kontagent.yml.tpl b/kontagent.yml.tpl index b612ef7..b2a8f69 100644 --- a/kontagent.yml.tpl +++ b/kontagent.yml.tpl @@ -1,137 +1,140 @@ # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note -<<<<<<< HEAD:kontagent.yml.tpl -# that this value must start with a '/'. -======= # that this value must start with a '/'. However, if your callback URL # is simply www.example.com/, this value should be left blank. # ->>>>>>> ffb0499da77b2bffd966eba49823370a38d745d2:kontagent.yml.tpl # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # -kt_host_test: api.test.kontagent.net \ No newline at end of file +kt_host_test: api.test.kontagent.net + +# Parameter : use_ab +# +# Description: Set use_ab to true to enable ab_testing. You also need to be granted permissions in order +# to have ab testing fully functional. +# +use_ab: false diff --git a/kontagent.yml.tpl.multi b/kontagent.yml.tpl.multi index fcfa395..31ea44e 100644 --- a/kontagent.yml.tpl.multi +++ b/kontagent.yml.tpl.multi @@ -1,131 +1,138 @@ <FACEBOOK_API_KEY>: # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false + # Parameter : use_ab + # + # Description: Set use_ab to true to enable ab_testing. You also need to be granted permissions in order + # to have ab testing fully functional. + # + use_ab: false + ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb index fe5991d..b4e6ff4 100644 --- a/lib/facebook/rails/controller.rb +++ b/lib/facebook/rails/controller.rb @@ -1,25 +1,25 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' module Facebooker module Rails module Controller def application_is_not_installed_by_facebook_user_with_kontagent if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") redirect_to session[:facebook_session].install_url else local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") end end #application_is_not_installed_by_facebook_user_with_kontagent alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent end #module Controller end end diff --git a/lib/facebook/rails/publisher.rb b/lib/facebook/rails/publisher.rb index dee9cc1..e7a20b0 100644 --- a/lib/facebook/rails/publisher.rb +++ b/lib/facebook/rails/publisher.rb @@ -1,68 +1,68 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER module Facebooker module Rails class Publisher def template(arg) @template = arg end def subtype1(arg) @subtype1 = arg end def subtype2(arg) @subtype2 = arg end def campaign(arg) @campaign = arg end def send_message_with_kontagent(method) @recipients = @recipients.is_a?(Array) ? @recipients : [@recipients] if from.nil? and @recipients.size==1 and ! announcement_notification?(from,_body) @from = @recipients.first end # notifications can # omit the from address raise InvalidSender.new("Sender must be a Facebooker::User") unless from.is_a?(Facebooker::User) || announcement_notification?(from,_body) case _body when Facebooker::Feed::TemplatizedAction,Facebooker::Feed::Action from.publish_action(_body) when Facebooker::Feed::Story @recipients.each {|r| r.publish_story(_body)} when Notification (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, @template, @subtype1, @subtype2, @campaign) when Email from.session.send_email(@recipients, _body.title, _body.text, _body.fbml, @template, @subtype1, @subtype2, @campaign) when Profile # If recipient and from aren't the same person, create a new user object using the # userid from recipient and the session from from if @from != @recipients.first @from = Facebooker::User.new(Facebooker::User.cast_to_facebook_id(@recipients.first),from.session) end from.set_profile_fbml(_body.profile, _body.mobile_profile, _body.profile_action, _body.profile_main) when Ref @from.session.server_cache.set_ref_handle(_body.handle,_body.fbml) when UserAction @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general, @subtype1, @subtype2, @campaign) else raise UnspecifiedBodyType.new("You must specify a valid send_as") end end alias_method_chain :send_message, :kontagent end end end diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb index e4c8cd5..55bf432 100644 --- a/lib/facebook/session.rb +++ b/lib/facebook/session.rb @@ -1,150 +1,149 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'ruby-debug' module Facebooker class Session def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) if !campaign.nil? # ab testing msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nt, nil, campaign, msg_id, page_id, msg_txt) else uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) end r = send_notification_without_kontagent(user_ids, fbml, email_fbml) if !r.blank? arg_hash = { 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } if source_user.nil? arg_hash['s'] = 0.to_s else arg_hash['s'] = source_user.id.to_s end arg_hash['t'] = template_id.to_s unless template_id.nil? if !campaign.nil? arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) else arg_hash['st1'] = st1 arg_hash['st2'] = st2 - arg_hash['st3'] = st3 rescue nil end Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) end end def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) if !campaign.nil? # ab testing msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) if fbml != nil uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nte, nil, campaign, msg_id, page_id, msg_txt) else uuid = Kt::KtAnalytics.instance.gen_long_uuid end else if fbml != nil uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, template_id, st1, st2, st3) else uuid = Kt::KtAnalytics.instance.gen_long_uuid end end r = send_email_without_kontagent(user_ids, subject, text, fbml) if !r.blank? arg_hash = { 's' => @user.id.to_s , 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } arg_hash['t'] = template_id.to_s unless template_id.nil? if !campaign.nil? arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) else arg_hash['st1'] = st1 arg_hash['st2'] = st2 end Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) end end # if st2 is set to m{d} and st3 is set to p{d}, we'll assume that it's using ab_testing data. def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil, campaign=nil) if !campaign.nil? msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) st1 = campaign st2 = msg_id st3 = page_id end if(data != nil) data.each_pair do |key,value | if key == :image if !campaign.nil? uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(value[:href], :fdp, bundle_id, st1, st2, st3, campaign) else uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, bundle_id, st1, st2) end value[:href] = fbml data[key] = value # do we even need this line? elsif key == :flash elsif key == :mp3 #Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) elsif key == :video else if !campaign.nil? uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href_vo(value, :fdp, bundle_id, st1, st2, st3) else uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) end data[key] = fbml end end end data['KT_AB_MSG'] = msg_txt if !campaign.nil? r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) if !r.blank? arg_hash = { 'pt' => 4, 's' => @user.id.to_s, 't' => bundle_id } Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) end end alias_method_chain :send_notification, :kontagent alias_method_chain :send_email, :kontagent alias_method_chain :publish_user_action, :kontagent end end diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index cb821c2..b4a33cc 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,189 +1,214 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' require 'ruby-debug' module Kt class AB_Testing_Manager @@URL_PREFIX = "/abtest/campaign_info"; public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} - rescue Exception => e - # LOCAL - to save our tests... - puts "Failed to initialize KT A/B testing: #{e.message}" - RAILS_DEFAULT_LOGGER.warn "Failed to initialize KT A/B testing: #{e.message}" end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" if force == true url_str += "?f=1" end url = URI.parse(url_str) - req = Net::HTTP::Get.new(url.path+"?"+url.query) + if url.query.nil? + url_str = url.path + else + url_str = url.path + "?" + url.query + end + req = Net::HTTP::Get.new(url_str) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true msg_lst = json_obj["messages"] msg_weight_array = [] curr_idx = 0 # process message list msg_lst.each do |m| w = m[1] w.times { msg_weight_array << curr_idx } curr_idx += 1 end # process page list page_lst = json_obj['pages'] page_weight_array = [] curr_idx = 0 page_lst.each do |p| w = p[1] w.times { page_weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['msg_weight'] = msg_weight_array store_dict['page_weight'] = page_weight_array r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end + + public + def get_ab_testing_campaign_handle_index(campaign) + dict = get_ab_helper(campaign) + if dict.nil? + return nil + else + json_obj = dict['json'] + return json_obj['handle_index'] + end + end + public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end public def get_selected_msg_info(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[2] end end + def get_selected_msg_info_button(campaign) + msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] + if msg_info.nil? + return nil + else + return msg_info[0], msg_info[3] + end + end + def get_selected_page_info(campaign) page_info = @m_selected_msg_page_pair_dict[campaign]['page'] if page_info.nil? return nil else return page_info[0], page_info[2] end end private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module -# mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', -# 'http://kthq.dyndns.org', 9999) -# #mgr.fetch_ab_testing_data('hello') -# puts mgr.get_ab_testing_message('hello') +#mgr = Kt::AB_Testing_Manager.new('56956a4098794fdc98e582f052205b1b', '03df281d926f4e5a9e409cd14f31c060', +# 'http://www.kontagent.com', 80) +#mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', +# 'http://www.kontagent.com', 80) +# 'http://kthq.dyndns.org', 9999) +# mgr.fetch_ab_testing_data('hello') +#puts mgr.get_ab_testing_message('test_u2u_notif') # puts mgr.get_ab_testing_page('hello') diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 27655da..9c6b91c 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,574 +1,624 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end + def gen_ut_cookie_key() + return @m_kt_api_key + "_ut" + end + + def gen_sut_cookie_key() + return @m_kt_api_key + "_sut" + end + + def store_ut_key_in_cookie(cookies, ut) + cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } + end + + def store_sut_key_in_cookie(cookies, sut) + cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } + end + def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] + @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] + @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end - + ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? - if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' + if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 + @use_ab = true end end end public + # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) - return "aB_"+st1_str + handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) + if !handle_index.nil? + if handle_index > 0 + return "aB_"+ st1_str + handle_index.to_s + else + return "aB_"+st1_str + end + else + return "aB_" + end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) - @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, - @m_ab_testing_host, - @m_ab_testing_port) #TODO: get rid of the hardcoding stuff + if @use_ab + @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, + @m_ab_testing_host, + @m_ab_testing_port) #TODO: get rid of the hardcoding stuff + end end - + def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else - return original_url + "?" + query_str rescue "" + return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end - # debugging - RAILS_DEFAULT_LOGGER.warn "kt demographics - birthday: #{user.birthday.inspect} => #{arg_hash['b']}" if arg_hash['b'].length < 4 - -# if !user.current_location.city.blank? &&user.current_location.city != '' -# arg_hash['ly'] = user.current_location.city -# end -# if !user.current_location.state.blank? && user.current_location.state != '' -# arg_hash['ls'] = user.current_location.state -# end -# if !user.current_location.country.blank? && user.current_location.country != '' -# arg_hash['lc'] = user.current_location.country -# end -# if !user.current_location.zip.blank? && user.current_location.zip != '' -# arg_hash['lp'] = user.current_location.zip -# end + # if !user.current_location.city.blank? &&user.current_location.city != '' + # arg_hash['ly'] = user.current_location.city + # end + # if !user.current_location.state.blank? && user.current_location.state != '' + # arg_hash['ls'] = user.current_location.state + # end + # if !user.current_location.country.blank? && user.current_location.country != '' + # arg_hash['lc'] = user.current_location.country + # end + # if !user.current_location.zip.blank? && user.current_location.zip != '' + # arg_hash['lp'] = user.current_location.zip + # end -# if !user.hometown_location.city.blank? &&user.hometown_location.city != '' -# arg_hash['ly'] = user.hometown_location.city -# end -# if !user.hometown_location.state.blank? && user.hometown_location.state != '' -# arg_hash['ls'] = user.hometown_location.state -# end -# if !user.hometown_location.country.blank? && user.hometown_location.country != '' -# arg_hash['lc'] = user.hometown_location.country -# end -# if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' -# arg_hash['lp'] = user.hometown_location.zip -# end + # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' + # arg_hash['ly'] = user.hometown_location.city + # end + # if !user.hometown_location.state.blank? && user.hometown_location.state != '' + # arg_hash['ls'] = user.hometown_location.state + # end + # if !user.hometown_location.country.blank? && user.hometown_location.country != '' + # arg_hash['lc'] = user.hometown_location.country + # end + # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' + # arg_hash['lp'] = user.hometown_location.zip + # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end - + def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end + end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end - def save_app_added(request_params) - has_direction = false - if request_params[:d] != nil - has_direction = true - end + + def save_app_added(request_params, cookies) +# has_direction = false +# if request_params[:d] != nil +# has_direction = true +# end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') - if has_direction == true and request_params[:d] == @@S_directed_val - arg_hash['u'] = request_params[:ut] - kt_outbound_msg('apa', arg_hash) - elsif has_direction == true and request_params[:d] == @@S_undirected_val - arg_hash['su'] = request_params[:sut] + if not cookies[gen_ut_cookie_key()].blank? + arg_hash['u'] = cookies[gen_ut_cookie_key()] + cookies.delete gen_ut_cookie_key() + kt_outbound_msg('apa', arg_hash) + elsif not cookies[gen_sut_cookie_key()].blank? + arg_hash['su'] = cookies[gen_sut_cookie_key()] + cookies.delete gen_sut_cookie_key() kt_outbound_msg('apa', arg_hash) - else # no viral + else kt_outbound_msg('apa', arg_hash) end + +# if has_direction == true and request_params[:d] == @@S_directed_val +# arg_hash['u'] = request_params[:ut] +# kt_outbound_msg('apa', arg_hash) +# elsif has_direction == true and request_params[:d] == @@S_undirected_val +# arg_hash['su'] = request_params[:sut] +# kt_outbound_msg('apa', arg_hash) +# else # no viral +# kt_outbound_msg('apa', arg_hash) +# end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end - def save_invite_click(request_params) + def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? - arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? + arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? + + store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end - def save_notification_click(request_params) + + def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) + store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end - def save_notification_email_click(request_params) + def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) + store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end - def save_undirected_comm_click(request_params) + def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') + store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() - CGI::Session.generate_unique_id('kontagent') - rescue - # Rails 2.3 fix - ActiveSupport::SecureRandom.hex(16) + begin + CGI::Session.generate_unique_id('kontagent') + rescue + # Rails 2.3 fix + ActiveSupport::SecureRandom.hex(16) + end end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index acb1dc5..8f0600c 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,138 +1,138 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER #require 'socket' require 'net/http' require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port if @m_host == "api.geo.kontagent.net" @m_ip = fetch_ip() else @m_ip = host end end def _fetch_ip_helper(host_name_str, port) ip_lst = Socket.getaddrinfo(host_name_str, 'http') ip_lst.sort_by{ rand } selected_ip = nil ip_lst.each do |ip_info| ip_str = ip_info[3] socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(port, ip_str) status = -1 timeout(2) do status = socket.connect(sockaddr) end if status == 0 selected_ip = ip_str break end end #loop return selected_ip end # _fetch_ip_helper def fetch_ip() selected_ip = _fetch_ip_helper(@m_host, @m_port) if selected_ip.nil? selected_ip = _fetch_ip_helper("api.global.kontagent.net", 80) end return selected_ip end public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(@m_port, @m_ip) connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN connected = false - #puts "Errno::EISCONN!!" + puts "Errno::EISCONN!!" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" buf << "Host:" + @m_ip + ":" + @m_port.to_s + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test #comm = Kontagent::Kt_Comm.new('67.102.65.65') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'}) diff --git a/lib/kt/queue/processor.rb b/lib/kt/queue/processor.rb index 1cef858..46cc124 100644 --- a/lib/kt/queue/processor.rb +++ b/lib/kt/queue/processor.rb @@ -1,84 +1,84 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER module Kt module Queue LOST_CONNECTION_ERROR_MESSAGES = [ "Server shutdown in progress", "Broken pipe", "Lost connection to MySQL server during query", "MySQL server has gone away" ] # An object not found proxy exception. This is used inside our generated getter methods # to rescue ActiveRecord::RecordNotFound class NotFound < Exception; end class Processor def options @task.options end # Takes a class name and returns and creates an accessor method and instance # variable for it. If the class responds to find (i.e. ActiveRecord objects), then # it tries to call it with the value of name_id extracted from the Task. # If not, it creates a new instaces of the class, sets an instance variable with that name # and returns it. def self.processes(name) name = name.to_s define_method(name) do ivar = instance_variable_get("@#{name}") return ivar unless ivar.blank? object = Object.const_get(name.camelize) value = if object.respond_to?(:find) begin object.find(@task.options["#{name}_id".intern]) # We provide automatic ActiveRecord::RecordNotFound protection because this method # useless without a correct instance of the model. rescue ActiveRecord::RecordNotFound => rnf raise Kt::NotFound, rnf.message end else Object.const_get(name.camelize).send('new') end instance_variable_set("@#{name}", value) value end end # Runs the process method defined in the Processor subclass (in app/processors). # Any error that is fatal should be rescued to avoid re-entry in to the queue. As a default, we rescue # ActiveRecord::RecordNotFound (record not found). # Subclasses of Processor should rescue any fatal errors specific to them in their own process method. def process!(task) @task = task tries = 0 begin process rescue ActiveRecord::StatementInvalid => sti lost_connection = false LOST_CONNECTION_ERROR_MESSAGES.each do |error| lost_connection = true if sti.message =~ /#{error}/ end if lost_connection && tries == 0 tries += 1 ActiveRecord::Base.connection.reconnect! retry end task.enqueue_with_error(sti) rescue Kt::Queue::NotFound => notfound rescue Exception => e task.enqueue_with_error(e) end end end end end diff --git a/lib/kt/queue/queue.rb b/lib/kt/queue/queue.rb index 9e434b1..e56ed5a 100644 --- a/lib/kt/queue/queue.rb +++ b/lib/kt/queue/queue.rb @@ -1,183 +1,183 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'starling' module Kt module Queue class Queue attr_reader :connection # Max number of reconnection attempts to starling MAX_TRIES = 1 class << self def queue @queue ||= Queue.new end def enqueue(priority, message) queue.enqueue(priority, message) end def process! queue.process! end def stop! queue.stop! end # Statictics methods def count_permanently_failed queue.connection.sizeof("#{queue.config['canvas_page_name']}_p_0") end def count queue.connection.sizeof(:all).inject(0){|c, (k, v)| c+= v} end # Use this method to see what's in the queue def peek(priority, iterate = 1) messages = [] iterate.times do message = queue.connection.get("#{queue.config['canvas_page_name']}_p_#{priority}") enqueue(priority, message) messages << message end messages end # You can use this method to define an external Proc (usually a lambda) that # is sent a notification when a task fails more than the max allowed times. # The lambda is passed the Kt::Queue::Task object, and the last Exception object. # For example: # Kt::Queue::Queue.failure_notification_observer = lambda {|task, error| # Mailer.deliver_exception_mail(...) # } attr_accessor :failure_notification_observer end def initialize self.connect! end def enqueue(priority, message) if message[:action].blank? error = "Tried to queue a task with an empty action. The message being queued was: #{message.inspect}" Kt::Queue::Queue.log(error, true) end @current_message = message value_with_retries do @connection.set("#{config['canvas_page_name']}_p_#{priority}", message) end end def dequeue(priority) @current_message = nil value_with_retries do @connection.get("#{config['canvas_page_name']}_p_#{priority}") end end # Loads the config file def config @config ||= YAML.load_file("#{RAILS_ROOT}/config/kontagent.yml") end # Gets the next_item in the Queue def next_item result = nil 10.times do |i| result = dequeue(i+1) break unless result.blank? end result end def flush 10.times do |i| result = @connection.flush("#{config['canvas_page_name']}_p_#{i+1}") end end # The main loop. It goes like this: # 1. Calls process which: # * calls next_item (returns nil or a task from the queue) # * process returns false if next_item is nil # * process creates a new task and calls process! on it # 2. The loop continues def process! @running = true while @running result = process unless result puts "Waiting..." if RAILS_ENV == "development" GC.enable GC.start sleep 3 end sleep 1 end end def stop! @running = false end def self.log(message, force=false) RAILS_DEFAULT_LOGGER.send(force ? :error : :debug, message) end protected def connect! Kt::Queue::Queue.log "Connecting on #{config['queue_address']}, canvas_page_name: #{config['canvas_page_name']}" @connection = Starling.new(config['queue_address']) end # Gets an item from the queue if there is one, creates a task, and runs process! on it def process task = next_item Kt::Queue::Queue.log "Running #{task.inspect}..." task.blank? ? false : Kt::Queue::Task.from_message(task).process! end def value_with_retries(&block) tries = 0 result = nil begin result = yield rescue MemCache::MemCacheError => e Kt::Queue::Queue.log "Try ##{tries} - Starling Error: #{e.class} -> #{e}" connect! # If we can't connect to the server at all, we just put a line in the log file. # This can be parsed later to write back to the queue if desired if (tries += 1) > MAX_TRIES unless @current_message.blank? Kt::Queue::Queue.log("+++ #{Time.now.to_i} #{@current_message.inspect}", true) if Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(@current_message, e) end end return nil end retry end return result end end end end diff --git a/lib/kt/queue/task.rb b/lib/kt/queue/task.rb index 58b186f..fbf46cc 100644 --- a/lib/kt/queue/task.rb +++ b/lib/kt/queue/task.rb @@ -1,76 +1,76 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/queue/processor' require 'kt/kt_comm_layer' class RecordProcessor < Kt::Queue::Processor def process op = options qtype = op[:qtype] if qtype == :kt_outbound m_comm = Kt::KtComm.instance(op[:kt_call_back_host], op[:kt_call_back_port]) m_comm.api_call_method(op[:kt_url], op[:v], op[:kt_api_key], op[:kt_secret_key], op[:ctype], op[:arg_hash]) elsif qtype == :capture_user_data Kt::KtAnalytics.instance.send_user_data_impl(Marshal.load(op[:user])) end end end module Kt module Queue class Task MAX_ERRORS = 3 attr_reader :options def process! processor.new.process!(self) end # Puts a failed Task back in the Queue with the lowest priority. # If a task fails MAX_ERRORS times, it is put in Queue 0 which is never processed. def enqueue_with_error(e) @options[:failures] = @options[:failures].to_i + 1 @options[:errors] ||= [] @options[:priority] = (@options[:failures] < MAX_ERRORS) ? 10 : 0 Kt::Queue::Queue.enqueue(@options[:priority], @options.merge!({ :action => @action, :errors => @options[:errors] << {:class => e.class.to_s, :message => e.message} })) Kt::Queue::Queue.log("Action '#{@action}' failed #{@options[:failures]} time(s).") # Send failure notification if a notification observer is defined if @options[:priority] == 0 && Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(self, e) end end # Puts actions in the Queue. Priority defaults to 5 def self.publish(action, options={}) priority = options[:priority] || 5 options.merge!({:action => action}) Kt::Queue::Queue.enqueue(priority, options) end # Creates a Task from a message def self.from_message(message) action = message.delete :action Task.new(action, message) end def initialize(action, options = {}) @action = action @options = {:priority => 5}.merge(options) end protected # Infers a Processor's name from the action def processor Object.const_get(@action.to_s.camelize + 'Processor') end end end end diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 2f625eb..71db83c 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,192 +1,200 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) - #controller.before_filter(:capture_user_data) + # controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end + def capture_user_data begin - #unless App.current.theme.template.code == "snowball" - user = session[:facebook_session].user - key = "KT_" + Facebooker.api_key + "_" + user.id.to_s - if cookies[key].blank? - Kt::KtAnalytics.instance.send_user_data(user) - end - cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks - #end + user = session[:facebook_session].user + key = "KT_" + Facebooker.api_key + "_" + user.id.to_s + if cookies[key].blank? + Kt::KtAnalytics.instance.send_user_data(user) + end + cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end - # track install - if params.has_key? :installed and params[:installed] == "1" - Kt::KtAnalytics.instance.save_app_added(params) + if cookies[gen_kt_install_cookie_key()].nil? or cookies[gen_kt_install_cookie_key()].blank? + cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} + else + if cookies[gen_kt_install_cookie_key()] == "0" and params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" + Kt::KtAnalytics.instance.save_app_added(params, cookies) + cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} + end end - + short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click - Kt::KtAnalytics.instance.save_invite_click(params) + Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click - Kt::KtAnalytics.instance.save_notification_click(params) + Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification - Kt::KtAnalytics.instance.save_notification_email_click(params) + Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) when "fdp" - short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) + short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) else - end - # forward to the url without the kt_* params - f_url = get_stripped_kt_args_url(short_tag) - #puts "f_url \n\t #{f_url}" #xxx - redirect_to f_url - + if params[:kt_type] != "ins" + # forward to the url without the kt_* params + f_url = get_stripped_kt_args_url(short_tag) + #puts "f_url \n\t #{f_url}" #xxx + redirect_to f_url + else + return true + end else return true end end # handle_kontagent private + def gen_kt_install_cookie_key() + return "KT_"+Facebooker.api_key+"_installed" + end def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" - r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, + r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index 20ed61d..c8c7305 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,107 +1,125 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'cgi' +require 'ruby-debug' module Kt module Rails module KontagentHelpers def kt_get_page_text(campaign) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) return page_text end def kt_get_msg_text(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) return msg_text end + + def kt_get_msg_buttons(campaign, index) + msg_id, msg_buttons = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_button(campaign) + if msg_id.nil? + return "" + end + + if msg_buttons[index].nil? + return "" + else + msg_buttons[index] + end + end def kt_get_invite_post_link_vo(invite_post_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, uid, session['invite_uuid'], campaign) - session['invite_uuid'] = nil +# session['invite_uuid'] = nil end return url end + def kt_clear_invite_tag() + session['invite_uuid'] = nil + end + def kt_get_invite_content_link_vo(invite_content_link, campaign) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, uid, campaign) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, uid, session['invite_uuid'], campaign) - session['invite_uuid'] = nil + #session['invite_uuid'] = nil end return url end def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) - session['invite_uuid'] = nil + #session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) - session['invite_uuid'] = nil + #session['invite_uuid'] = nil end return url end def kt_track_page_view() uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end end end end diff --git a/lib/starling_ext.rb b/lib/starling_ext.rb index 2a41d03..3132ab4 100644 --- a/lib/starling_ext.rb +++ b/lib/starling_ext.rb @@ -1,7 +1,7 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER # An extension to the Starling class from Twitter's (www.twitter.com) starling (http://rubyforge.org/projects/starling) gem. class Starling def get(*args) super(*args) end end \ No newline at end of file
rmatei/kt
87537f8486083b67b7e382299da50525943c89be
fixed the over-counting problem with installs
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index dd36dec..408fa15 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,192 +1,200 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end + def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end - # track install - if params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" - Kt::KtAnalytics.instance.save_app_added(params, cookies) + if cookies[gen_kt_install_cookie_key()].nil? or cookies[gen_kt_install_cookie_key()].blank? + cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} + else + if cookies[gen_kt_install_cookie_key()] == "0" and params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" + Kt::KtAnalytics.instance.save_app_added(params, cookies) + cookies[gen_kt_install_cookie_key()] = {:value => params[:fb_sig_added], :expires => 1.minute.from_now} + end end - short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) else end if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private + def gen_kt_install_cookie_key() + return "KT_"+Facebooker.api_key+"_installed" + end + def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
e9b486f2c31f475b802e2bf5d456cc50175e5c27
Remove demographics filter
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index dd36dec..d709c67 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,192 +1,192 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) - controller.before_filter(:capture_user_data) + # controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" Kt::KtAnalytics.instance.save_app_added(params, cookies) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) else end if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
17eeb447818d4cf97f6147944a78efb5647c47b8
Adding instrumentation
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 278ce2a..9c6b91c 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -29,589 +29,596 @@ module Kt end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def gen_ut_cookie_key() return @m_kt_api_key + "_ut" end def gen_sut_cookie_key() return @m_kt_api_key + "_sut" end def store_ut_key_in_cookie(cookies, ut) cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } end def store_sut_key_in_cookie(cookies, sut) cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params, cookies) # has_direction = false # if request_params[:d] != nil # has_direction = true # end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if not cookies[gen_ut_cookie_key()].blank? arg_hash['u'] = cookies[gen_ut_cookie_key()] cookies.delete gen_ut_cookie_key() kt_outbound_msg('apa', arg_hash) elsif not cookies[gen_sut_cookie_key()].blank? arg_hash['su'] = cookies[gen_sut_cookie_key()] cookies.delete gen_sut_cookie_key() kt_outbound_msg('apa', arg_hash) else kt_outbound_msg('apa', arg_hash) end # if has_direction == true and request_params[:d] == @@S_directed_val # arg_hash['u'] = request_params[:ut] # kt_outbound_msg('apa', arg_hash) # elsif has_direction == true and request_params[:d] == @@S_undirected_val # arg_hash['su'] = request_params[:sut] # kt_outbound_msg('apa', arg_hash) # else # no viral # kt_outbound_msg('apa', arg_hash) # end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end + begin + require "#{RAILS_ROOT}/vendor/plugins/rpm/init" + add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' + rescue + puts "Failed to add New Relic instrumentation to Kontagent." + end + # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
4825b87275c1aa328c03c2872c8493d4aaa37e86
use cookies to track install tracking tags
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 7b8fb65..278ce2a 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,585 +1,617 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end + + def gen_ut_cookie_key() + return @m_kt_api_key + "_ut" + end + + def gen_sut_cookie_key() + return @m_kt_api_key + "_sut" + end + + def store_ut_key_in_cookie(cookies, ut) + cookies[gen_ut_cookie_key()] = {:value => ut, :expires => 10.minutes.from_now } + end + def store_sut_key_in_cookie(cookies, sut) + cookies[gen_sut_cookie_key()] = {:value => sut, :expired => 10.minutes.from_now } + end + def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) if @use_ab @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end - def save_app_added(request_params) - has_direction = false - if request_params[:d] != nil - has_direction = true - end + def save_app_added(request_params, cookies) +# has_direction = false +# if request_params[:d] != nil +# has_direction = true +# end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') - if has_direction == true and request_params[:d] == @@S_directed_val - arg_hash['u'] = request_params[:ut] + if not cookies[gen_ut_cookie_key()].blank? + arg_hash['u'] = cookies[gen_ut_cookie_key()] + cookies.delete gen_ut_cookie_key() + kt_outbound_msg('apa', arg_hash) + elsif not cookies[gen_sut_cookie_key()].blank? + arg_hash['su'] = cookies[gen_sut_cookie_key()] + cookies.delete gen_sut_cookie_key() kt_outbound_msg('apa', arg_hash) - elsif has_direction == true and request_params[:d] == @@S_undirected_val - arg_hash['su'] = request_params[:sut] - kt_outbound_msg('apa', arg_hash) - else # no viral + else kt_outbound_msg('apa', arg_hash) end + +# if has_direction == true and request_params[:d] == @@S_directed_val +# arg_hash['u'] = request_params[:ut] +# kt_outbound_msg('apa', arg_hash) +# elsif has_direction == true and request_params[:d] == @@S_undirected_val +# arg_hash['su'] = request_params[:sut] +# kt_outbound_msg('apa', arg_hash) +# else # no viral +# kt_outbound_msg('apa', arg_hash) +# end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end - def save_invite_click(request_params) + def save_invite_click(request_params, cookies) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? + store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg('inr', arg_hash) end - def save_notification_click(request_params) + def save_notification_click(request_params, cookies) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) + store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end - def save_notification_email_click(request_params) + def save_notification_email_click(request_params, cookies) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) + store_ut_key_in_cookie(cookies, request_params[:kt_ut]) kt_outbound_msg(msg_type, arg_hash) end - def save_undirected_comm_click(request_params) + def save_undirected_comm_click(request_params, cookies) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') + store_sut_key_in_cookie(cookies, short_tag) kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 219008e..dd36dec 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,192 +1,192 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install - if params.has_key? :installed and params[:installed] == "1" - Kt::KtAnalytics.instance.save_app_added(params) + if params.has_key? :fb_sig_added and params[:fb_sig_added] == "1" + Kt::KtAnalytics.instance.save_app_added(params, cookies) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click - Kt::KtAnalytics.instance.save_invite_click(params) + Kt::KtAnalytics.instance.save_invite_click(params, cookies) when "nt" # notification click - Kt::KtAnalytics.instance.save_notification_click(params) + Kt::KtAnalytics.instance.save_notification_click(params, cookies) when "nte" # email notification - Kt::KtAnalytics.instance.save_notification_email_click(params) + Kt::KtAnalytics.instance.save_notification_email_click(params, cookies) when "fdp" - short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) + short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params, cookies) else end if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
30fed59da94b4070d135e0fce8d5570b2c683c2f
Rescue nil error in kontagent param adding
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 4031a2f..b214b4d 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,578 +1,578 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 end end end public def format_kt_st1(st1_str) return "aB_"+st1_str end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else - return original_url + "?" + query_str + return original_url + "?" + query_str rescue "" end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # debugging RAILS_DEFAULT_LOGGER.warn "kt demographics - birthday: #{user.birthday.inspect} => #{arg_hash['b']}" if arg_hash['b'].length < 4 # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
bb3bfb5d326abbb1e27607a4198ad505a58df844
Removing Kontagent demographics
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 672a947..37105de 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,192 +1,192 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) - controller.before_filter(:capture_user_data) + #controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin #unless App.current.theme.template.code == "snowball" user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks #end rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
2f45fd98c1cd76df9c2759c2a02c6a7d8ce7ce36
fixed a minor bug
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index a684c76..219008e 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,192 +1,192 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end - - if params[:kt_type] != "in" + + if params[:kt_type] != "ins" # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
baeafe6b1539cd86b853655bce80d275540d3add
Enabling tracking for Snowball
diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index 8550409..acb1dc5 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,138 +1,138 @@ # Kontagent facebooker version 0.2.0 #require 'socket' require 'net/http' require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port if @m_host == "api.geo.kontagent.net" @m_ip = fetch_ip() else @m_ip = host end end def _fetch_ip_helper(host_name_str, port) ip_lst = Socket.getaddrinfo(host_name_str, 'http') ip_lst.sort_by{ rand } selected_ip = nil ip_lst.each do |ip_info| ip_str = ip_info[3] socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(port, ip_str) status = -1 timeout(2) do status = socket.connect(sockaddr) end if status == 0 selected_ip = ip_str break end end #loop return selected_ip end # _fetch_ip_helper def fetch_ip() selected_ip = _fetch_ip_helper(@m_host, @m_port) if selected_ip.nil? selected_ip = _fetch_ip_helper("api.global.kontagent.net", 80) end return selected_ip end public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(@m_port, @m_ip) connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN connected = false - puts "Errno::EISCONN!!" + #puts "Errno::EISCONN!!" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" buf << "Host:" + @m_ip + ":" + @m_port.to_s + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test #comm = Kontagent::Kt_Comm.new('67.102.65.65') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'}) diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index a72e384..672a947 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,192 +1,192 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin - unless App.current.theme.template.code == "snowball" + #unless App.current.theme.template.code == "snowball" user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks - end + #end rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
fc6b87454cd9c173630ecde1c795c12378df27ba
don't strip kt_params and do a redirect for invite click. It messes up params[:ids]
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 1b71e84..a684c76 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,190 +1,192 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else - end - - # forward to the url without the kt_* params - f_url = get_stripped_kt_args_url(short_tag) - #puts "f_url \n\t #{f_url}" #xxx - redirect_to f_url + if params[:kt_type] != "in" + # forward to the url without the kt_* params + f_url = get_stripped_kt_args_url(short_tag) + #puts "f_url \n\t #{f_url}" #xxx + redirect_to f_url + else + return true + end else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
6f06bcd15f701d341ac9750c389d92f435fa698a
added a more descriptive instruction on kontagent.yml
diff --git a/kontagent.yml.tpl b/kontagent.yml.tpl index f819baf..b2a8f69 100644 --- a/kontagent.yml.tpl +++ b/kontagent.yml.tpl @@ -1,138 +1,140 @@ # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note -# that this value must start with a '/'. +# that this value must start with a '/'. However, if your callback URL +# is simply www.example.com/, this value should be left blank. +# # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net # Parameter : use_ab # # Description: Set use_ab to true to enable ab_testing. You also need to be granted permissions in order # to have ab testing fully functional. # use_ab: false diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index b84da3c..b4a33cc 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,211 +1,214 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' require 'ruby-debug' module Kt class AB_Testing_Manager @@URL_PREFIX = "/abtest/campaign_info"; public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" if force == true url_str += "?f=1" end url = URI.parse(url_str) if url.query.nil? url_str = url.path else url_str = url.path + "?" + url.query end req = Net::HTTP::Get.new(url_str) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true msg_lst = json_obj["messages"] msg_weight_array = [] curr_idx = 0 # process message list msg_lst.each do |m| w = m[1] w.times { msg_weight_array << curr_idx } curr_idx += 1 end # process page list page_lst = json_obj['pages'] page_weight_array = [] curr_idx = 0 page_lst.each do |p| w = p[1] w.times { page_weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['msg_weight'] = msg_weight_array store_dict['page_weight'] = page_weight_array r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end public def get_ab_testing_campaign_handle_index(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] return json_obj['handle_index'] end end public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end public def get_selected_msg_info(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[2] end end def get_selected_msg_info_button(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[3] end end def get_selected_page_info(campaign) page_info = @m_selected_msg_page_pair_dict[campaign]['page'] if page_info.nil? return nil else return page_info[0], page_info[2] end end private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module -# mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', -# 'http://kthq.dyndns.org', 9999) -# #mgr.fetch_ab_testing_data('hello') -# puts mgr.get_ab_testing_message('hello') +#mgr = Kt::AB_Testing_Manager.new('56956a4098794fdc98e582f052205b1b', '03df281d926f4e5a9e409cd14f31c060', +# 'http://www.kontagent.com', 80) +#mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', +# 'http://www.kontagent.com', 80) +# 'http://kthq.dyndns.org', 9999) +# mgr.fetch_ab_testing_data('hello') +#puts mgr.get_ab_testing_message('test_u2u_notif') # puts mgr.get_ab_testing_page('hello')
rmatei/kt
afef0bd66bae0a371e6bcf2fc360a267f9764db1
clean up
diff --git a/init.rb b/init.rb index e494bea..410fc51 100644 --- a/init.rb +++ b/init.rb @@ -1,57 +1,57 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER puts "loading kt..." require 'facebook/session' require 'kt/rails/helpers' require 'facebooker/rails/publisher' require 'facebook/rails/publisher' #require 'facebooker/rails/controller' require 'facebook/rails/controller' require 'kt/rails/controller' config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") if config['mode'] == 'async' require 'starling' require 'starling_ext' require 'kt/queue/queue' require 'kt/queue/processor' require 'kt/queue/task' # Load app applicable Kontagent::Queue::Processor subclasses from app/processors Dir[RAILS_ROOT + '/app/processors/*.rb'].each do |file| require file end end module ::ActionController class Base def self.inherited_with_kt(subclass) inherited_without_kt(subclass) if subclass.to_s == "ApplicationController" subclass.class_eval do subclass.send(:include,Kt::Rails::Controller) end end end #def class << self alias_method_chain :inherited, :kt end end end ActionView::Base.send :include, Kt::Rails::KontagentHelpers diff --git a/install.rb b/install.rb index 570c7f9..aaaf2d0 100644 --- a/install.rb +++ b/install.rb @@ -1,20 +1,20 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER # Install hook code here require 'fileutils' require 'rubygems' #require 'ruby-debug' #xxx if ARGV.size != 2 puts "Failure: you need to pass in the controller_name" else controller_name = ARGV[1] handle_iframe_html_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.html.erb") handle_iframe_fbml_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.fbml.erb") kontagent_yml_dst = File.join(RAILS_ROOT, "config", "kontagent.yml") puts "copying kontagent.yml.erb to #{kontagent_yml_dst}" FileUtils.cp( File.join(RAILS_ROOT, "vendor", "plugins", "kt", 'kontagent.yml.tpl'), kontagent_yml_dst ) unless File.exists?( kontagent_yml_dst ) end diff --git a/kontagent.yml.tpl b/kontagent.yml.tpl index 4d2b5c5..f819baf 100644 --- a/kontagent.yml.tpl +++ b/kontagent.yml.tpl @@ -1,130 +1,138 @@ # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false + ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net + +# Parameter : use_ab +# +# Description: Set use_ab to true to enable ab_testing. You also need to be granted permissions in order +# to have ab testing fully functional. +# +use_ab: false diff --git a/kontagent.yml.tpl.multi b/kontagent.yml.tpl.multi index fcfa395..31ea44e 100644 --- a/kontagent.yml.tpl.multi +++ b/kontagent.yml.tpl.multi @@ -1,131 +1,138 @@ <FACEBOOK_API_KEY>: # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false + # Parameter : use_ab + # + # Description: Set use_ab to true to enable ab_testing. You also need to be granted permissions in order + # to have ab testing fully functional. + # + use_ab: false + ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb index e6a35ef..b4e6ff4 100644 --- a/lib/facebook/rails/controller.rb +++ b/lib/facebook/rails/controller.rb @@ -1,25 +1,25 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' module Facebooker module Rails module Controller def application_is_not_installed_by_facebook_user_with_kontagent if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") redirect_to session[:facebook_session].install_url else local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") end end #application_is_not_installed_by_facebook_user_with_kontagent alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent end #module Controller end end diff --git a/lib/facebook/rails/publisher.rb b/lib/facebook/rails/publisher.rb index 150e15e..e7a20b0 100644 --- a/lib/facebook/rails/publisher.rb +++ b/lib/facebook/rails/publisher.rb @@ -1,62 +1,68 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER + module Facebooker module Rails class Publisher def template(arg) @template = arg end def subtype1(arg) @subtype1 = arg end def subtype2(arg) @subtype2 = arg end + def campaign(arg) + @campaign = arg + end def send_message_with_kontagent(method) @recipients = @recipients.is_a?(Array) ? @recipients : [@recipients] if from.nil? and @recipients.size==1 and ! announcement_notification?(from,_body) @from = @recipients.first end # notifications can # omit the from address raise InvalidSender.new("Sender must be a Facebooker::User") unless from.is_a?(Facebooker::User) || announcement_notification?(from,_body) case _body when Facebooker::Feed::TemplatizedAction,Facebooker::Feed::Action from.publish_action(_body) when Facebooker::Feed::Story @recipients.each {|r| r.publish_story(_body)} when Notification - (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, @template, @subtype1, @subtype2) + (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, + @template, @subtype1, @subtype2, @campaign) when Email from.session.send_email(@recipients, _body.title, _body.text, _body.fbml, @template, @subtype1, - @subtype2) + @subtype2, + @campaign) when Profile # If recipient and from aren't the same person, create a new user object using the # userid from recipient and the session from from if @from != @recipients.first @from = Facebooker::User.new(Facebooker::User.cast_to_facebook_id(@recipients.first),from.session) end from.set_profile_fbml(_body.profile, _body.mobile_profile, _body.profile_action, _body.profile_main) when Ref @from.session.server_cache.set_ref_handle(_body.handle,_body.fbml) when UserAction - @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general) + @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general, @subtype1, @subtype2, @campaign) else raise UnspecifiedBodyType.new("You must specify a valid send_as") end end alias_method_chain :send_message, :kontagent end end end diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb index e60c59a..55bf432 100644 --- a/lib/facebook/session.rb +++ b/lib/facebook/session.rb @@ -1,93 +1,149 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' +require 'ruby-debug' module Facebooker class Session - def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil) - uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) + def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) + + if !campaign.nil? + # ab testing + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nt, nil, campaign, msg_id, page_id, msg_txt) + else + uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) + end + r = send_notification_without_kontagent(user_ids, fbml, email_fbml) if !r.blank? arg_hash = { - #'s' => @user.id.to_s, 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } if source_user.nil? arg_hash['s'] = 0.to_s else arg_hash['s'] = source_user.id.to_s end arg_hash['t'] = template_id.to_s unless template_id.nil? + if !campaign.nil? + arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) + arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) + arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) + else + arg_hash['st1'] = st1 + arg_hash['st2'] = st2 + end + Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) end end - def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil) - if fbml != nil - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, - template_id, st1, st2) + def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) + if !campaign.nil? + # ab testing + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + if fbml != nil + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nte, nil, campaign, msg_id, page_id, msg_txt) + else + uuid = Kt::KtAnalytics.instance.gen_long_uuid + end else - uuid = Kt::KtAnalytics.instance.gen_long_uuid + if fbml != nil + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, template_id, st1, st2, st3) + else + uuid = Kt::KtAnalytics.instance.gen_long_uuid + end end r = send_email_without_kontagent(user_ids, subject, text, fbml) if !r.blank? arg_hash = { 's' => @user.id.to_s , 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } + arg_hash['t'] = template_id.to_s unless template_id.nil? + if !campaign.nil? + arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) + arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) + arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) + else + arg_hash['st1'] = st1 + arg_hash['st2'] = st2 + end Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) end end - def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil) + # if st2 is set to m{d} and st3 is set to p{d}, we'll assume that it's using ab_testing data. + def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil, campaign=nil) + if !campaign.nil? + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + st1 = campaign + st2 = msg_id + st3 = page_id + end + if(data != nil) data.each_pair do |key,value | if key == :image - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, - bundle_id, st1, st2) + if !campaign.nil? + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(value[:href], :fdp, + bundle_id, st1, st2, st3, campaign) + else + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, + bundle_id, st1, st2) + end value[:href] = fbml data[key] = value # do we even need this line? elsif key == :flash elsif key == :mp3 - Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) + #Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) elsif key == :video - else - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) + if !campaign.nil? + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href_vo(value, :fdp, bundle_id, st1, st2, st3) + else + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) + end data[key] = fbml end end end - + + data['KT_AB_MSG'] = msg_txt if !campaign.nil? + r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) - + if !r.blank? arg_hash = { 'pt' => 4, 's' => @user.id.to_s, 't' => bundle_id } Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) end end alias_method_chain :send_notification, :kontagent alias_method_chain :send_email, :kontagent alias_method_chain :publish_user_action, :kontagent end end diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index d0d6209..7b8fb65 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,580 +1,585 @@ # Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] + @use_ab = true elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] + @use_ab = true end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end - + ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? - if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' + if (app_config_map.has_key? 'use_ab' and app_config_map['use_ab'] == true) or (@config.has_key? 'use_ab' and @config['use_ab'] == true) @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 + @use_ab = true end end end public # assumption : st1_str is set to the campaign_name def format_kt_st1(st1_str) handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) if !handle_index.nil? if handle_index > 0 return "aB_"+ st1_str + handle_index.to_s else return "aB_"+st1_str end else return "aB_" end end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) - @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, - @m_ab_testing_host, - @m_ab_testing_port) #TODO: get rid of the hardcoding stuff + if @use_ab + @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, + @m_ab_testing_host, + @m_ab_testing_port) #TODO: get rid of the hardcoding stuff + end end - + def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() begin CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/queue/processor.rb b/lib/kt/queue/processor.rb index 429a710..46cc124 100644 --- a/lib/kt/queue/processor.rb +++ b/lib/kt/queue/processor.rb @@ -1,84 +1,84 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER module Kt module Queue LOST_CONNECTION_ERROR_MESSAGES = [ "Server shutdown in progress", "Broken pipe", "Lost connection to MySQL server during query", "MySQL server has gone away" ] # An object not found proxy exception. This is used inside our generated getter methods # to rescue ActiveRecord::RecordNotFound class NotFound < Exception; end class Processor def options @task.options end # Takes a class name and returns and creates an accessor method and instance # variable for it. If the class responds to find (i.e. ActiveRecord objects), then # it tries to call it with the value of name_id extracted from the Task. # If not, it creates a new instaces of the class, sets an instance variable with that name # and returns it. def self.processes(name) name = name.to_s define_method(name) do ivar = instance_variable_get("@#{name}") return ivar unless ivar.blank? object = Object.const_get(name.camelize) value = if object.respond_to?(:find) begin object.find(@task.options["#{name}_id".intern]) # We provide automatic ActiveRecord::RecordNotFound protection because this method # useless without a correct instance of the model. rescue ActiveRecord::RecordNotFound => rnf raise Kt::NotFound, rnf.message end else Object.const_get(name.camelize).send('new') end instance_variable_set("@#{name}", value) value end end # Runs the process method defined in the Processor subclass (in app/processors). # Any error that is fatal should be rescued to avoid re-entry in to the queue. As a default, we rescue # ActiveRecord::RecordNotFound (record not found). # Subclasses of Processor should rescue any fatal errors specific to them in their own process method. def process!(task) @task = task tries = 0 begin process rescue ActiveRecord::StatementInvalid => sti lost_connection = false LOST_CONNECTION_ERROR_MESSAGES.each do |error| lost_connection = true if sti.message =~ /#{error}/ end if lost_connection && tries == 0 tries += 1 ActiveRecord::Base.connection.reconnect! retry end task.enqueue_with_error(sti) rescue Kt::Queue::NotFound => notfound rescue Exception => e task.enqueue_with_error(e) end end end end end diff --git a/lib/kt/queue/queue.rb b/lib/kt/queue/queue.rb index 2fb380e..e56ed5a 100644 --- a/lib/kt/queue/queue.rb +++ b/lib/kt/queue/queue.rb @@ -1,183 +1,183 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'starling' module Kt module Queue class Queue attr_reader :connection # Max number of reconnection attempts to starling MAX_TRIES = 1 class << self def queue @queue ||= Queue.new end def enqueue(priority, message) queue.enqueue(priority, message) end def process! queue.process! end def stop! queue.stop! end # Statictics methods def count_permanently_failed queue.connection.sizeof("#{queue.config['canvas_page_name']}_p_0") end def count queue.connection.sizeof(:all).inject(0){|c, (k, v)| c+= v} end # Use this method to see what's in the queue def peek(priority, iterate = 1) messages = [] iterate.times do message = queue.connection.get("#{queue.config['canvas_page_name']}_p_#{priority}") enqueue(priority, message) messages << message end messages end # You can use this method to define an external Proc (usually a lambda) that # is sent a notification when a task fails more than the max allowed times. # The lambda is passed the Kt::Queue::Task object, and the last Exception object. # For example: # Kt::Queue::Queue.failure_notification_observer = lambda {|task, error| # Mailer.deliver_exception_mail(...) # } attr_accessor :failure_notification_observer end def initialize self.connect! end def enqueue(priority, message) if message[:action].blank? error = "Tried to queue a task with an empty action. The message being queued was: #{message.inspect}" Kt::Queue::Queue.log(error, true) end @current_message = message value_with_retries do @connection.set("#{config['canvas_page_name']}_p_#{priority}", message) end end def dequeue(priority) @current_message = nil value_with_retries do @connection.get("#{config['canvas_page_name']}_p_#{priority}") end end # Loads the config file def config @config ||= YAML.load_file("#{RAILS_ROOT}/config/kontagent.yml") end # Gets the next_item in the Queue def next_item result = nil 10.times do |i| result = dequeue(i+1) break unless result.blank? end result end def flush 10.times do |i| result = @connection.flush("#{config['canvas_page_name']}_p_#{i+1}") end end # The main loop. It goes like this: # 1. Calls process which: # * calls next_item (returns nil or a task from the queue) # * process returns false if next_item is nil # * process creates a new task and calls process! on it # 2. The loop continues def process! @running = true while @running result = process unless result puts "Waiting..." if RAILS_ENV == "development" GC.enable GC.start sleep 3 end sleep 1 end end def stop! @running = false end def self.log(message, force=false) RAILS_DEFAULT_LOGGER.send(force ? :error : :debug, message) end protected def connect! Kt::Queue::Queue.log "Connecting on #{config['queue_address']}, canvas_page_name: #{config['canvas_page_name']}" @connection = Starling.new(config['queue_address']) end # Gets an item from the queue if there is one, creates a task, and runs process! on it def process task = next_item Kt::Queue::Queue.log "Running #{task.inspect}..." task.blank? ? false : Kt::Queue::Task.from_message(task).process! end def value_with_retries(&block) tries = 0 result = nil begin result = yield rescue MemCache::MemCacheError => e Kt::Queue::Queue.log "Try ##{tries} - Starling Error: #{e.class} -> #{e}" connect! # If we can't connect to the server at all, we just put a line in the log file. # This can be parsed later to write back to the queue if desired if (tries += 1) > MAX_TRIES unless @current_message.blank? Kt::Queue::Queue.log("+++ #{Time.now.to_i} #{@current_message.inspect}", true) if Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(@current_message, e) end end return nil end retry end return result end end end end diff --git a/lib/kt/queue/task.rb b/lib/kt/queue/task.rb index e7d8370..fbf46cc 100644 --- a/lib/kt/queue/task.rb +++ b/lib/kt/queue/task.rb @@ -1,76 +1,76 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/queue/processor' require 'kt/kt_comm_layer' class RecordProcessor < Kt::Queue::Processor def process op = options qtype = op[:qtype] if qtype == :kt_outbound m_comm = Kt::KtComm.instance(op[:kt_call_back_host], op[:kt_call_back_port]) m_comm.api_call_method(op[:kt_url], op[:v], op[:kt_api_key], op[:kt_secret_key], op[:ctype], op[:arg_hash]) elsif qtype == :capture_user_data Kt::KtAnalytics.instance.send_user_data_impl(Marshal.load(op[:user])) end end end module Kt module Queue class Task MAX_ERRORS = 3 attr_reader :options def process! processor.new.process!(self) end # Puts a failed Task back in the Queue with the lowest priority. # If a task fails MAX_ERRORS times, it is put in Queue 0 which is never processed. def enqueue_with_error(e) @options[:failures] = @options[:failures].to_i + 1 @options[:errors] ||= [] @options[:priority] = (@options[:failures] < MAX_ERRORS) ? 10 : 0 Kt::Queue::Queue.enqueue(@options[:priority], @options.merge!({ :action => @action, :errors => @options[:errors] << {:class => e.class.to_s, :message => e.message} })) Kt::Queue::Queue.log("Action '#{@action}' failed #{@options[:failures]} time(s).") # Send failure notification if a notification observer is defined if @options[:priority] == 0 && Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(self, e) end end # Puts actions in the Queue. Priority defaults to 5 def self.publish(action, options={}) priority = options[:priority] || 5 options.merge!({:action => action}) Kt::Queue::Queue.enqueue(priority, options) end # Creates a Task from a message def self.from_message(message) action = message.delete :action Task.new(action, message) end def initialize(action, options = {}) @action = action @options = {:priority => 5}.merge(options) end protected # Infers a Processor's name from the action def processor Object.const_get(@action.to_s.camelize + 'Processor') end end end end diff --git a/lib/starling_ext.rb b/lib/starling_ext.rb index 6655041..3132ab4 100644 --- a/lib/starling_ext.rb +++ b/lib/starling_ext.rb @@ -1,7 +1,7 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER # An extension to the Starling class from Twitter's (www.twitter.com) starling (http://rubyforge.org/projects/starling) gem. class Starling def get(*args) super(*args) end end \ No newline at end of file
rmatei/kt
894894e6609a886fcb77e9afd46f0c9f0d596774
copying files over from svn repo.
diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb new file mode 100644 index 0000000..b84da3c --- /dev/null +++ b/lib/kt/kt_ab_testing.rb @@ -0,0 +1,211 @@ +require 'rubygems' #xxx +require 'memcache' +require 'net/http' +require 'uri' +require 'json' +require 'ruby-debug' + +module Kt + class AB_Testing_Manager + + @@URL_PREFIX = "/abtest/campaign_info"; + + public + def initialize(kt_api_key, kt_secret_key, + kt_ab_backend_host, kt_ab_backend_port) + @m_backend_api_key = kt_api_key + @m_backend_secret_key = kt_secret_key + + @m_ab_backend_host = kt_ab_backend_host + @m_ab_backend_port = kt_ab_backend_port + + if @m_ab_backend_port != 80 + @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s + else + @m_ab_backend = @m_ab_backend_host + end + + @m_memcached_server = MemCache.new '127.0.0.1' + @m_selected_msg_page_pair_dict = {} + end + + private + def fetch_ab_testing_data(campaign, force=false) + begin + url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" + if force == true + url_str += "?f=1" + end + + url = URI.parse(url_str) + if url.query.nil? + url_str = url.path + else + url_str = url.path + "?" + url.query + end + req = Net::HTTP::Get.new(url_str) + res = Net::HTTP.start(url.host, url.port) {|http| + http.request(req) + } + json_obj = JSON.parse(res.body) + + if json_obj["changed"] == true + msg_lst = json_obj["messages"] + msg_weight_array = [] + curr_idx = 0 + + # process message list + msg_lst.each do |m| + w = m[1] + w.times { msg_weight_array << curr_idx } + curr_idx += 1 + end + + # process page list + page_lst = json_obj['pages'] + page_weight_array = [] + curr_idx = 0 + page_lst.each do |p| + w = p[1] + w.times { page_weight_array << curr_idx } + curr_idx += 1 + end + + store_dict = {} + store_dict['json'] = json_obj + store_dict['msg_weight'] = msg_weight_array + store_dict['page_weight'] = page_weight_array + + r = store_dict + @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) + @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) + else + # no change + @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) + end + + rescue Errno::ECONNREFUSED + # TODO fall back on some default value + end + + + return r + end + + private + def get_ab_helper(campaign) + fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) + if fake_key_is_valid.nil? + # The real key should have a valid json object. + # If not, invoke fetch_ab_testin_data with force = true + serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) + if serialized_campaign_str.nil? + r = fetch_ab_testing_data(campaign, true) # force it + else + r = fetch_ab_testing_data(campaign) + end + else + # Likewise, the real key should have a valid json object. + # If not, invoke fetch_ab_testin_data with force = true + serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) + if serialized_campaign_str.nil? + r = fetch_ab_testing_data(campaign, true) # force it + else + r = Marshal.load( serialized_campaign_str ) + end + end + return r + end + + + public + def get_ab_testing_campaign_handle_index(campaign) + dict = get_ab_helper(campaign) + if dict.nil? + return nil + else + json_obj = dict['json'] + return json_obj['handle_index'] + end + end + + public + def get_ab_testing_message(campaign) + dict = get_ab_helper(campaign) + if dict.nil? + return nil + else + json_obj = dict['json'] + msg_lst = json_obj['messages'] + weight_array = dict['msg_weight'] + index = weight_array[rand(weight_array.size)] + return msg_lst[index] + end + end + + public + def get_ab_testing_page(campaign) + dict = get_ab_helper(campaign) + if dict.nil? + return nil + else + json_obj = dict['json'] + page_lst = json_obj['pages'] + weight_array = dict['page_weight'] + index = weight_array[rand(weight_array.size)] + return page_lst[index] + end + end + + public + def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) + @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} + end + + public + def get_selected_msg_info(campaign) + msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] + if msg_info.nil? + return nil + else + return msg_info[0], msg_info[2] + end + end + + def get_selected_msg_info_button(campaign) + msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] + if msg_info.nil? + return nil + else + return msg_info[0], msg_info[3] + end + end + + def get_selected_page_info(campaign) + page_info = @m_selected_msg_page_pair_dict[campaign]['page'] + if page_info.nil? + return nil + else + return page_info[0], page_info[2] + end + end + + private + def gen_memcache_fake_key(campaign) + return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" + end + + private + def gen_memcache_key(campaign) + return "kt_"+@m_backend_api_key+"_"+campaign + end + + end + +end # module + +# mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', +# 'http://kthq.dyndns.org', 9999) +# #mgr.fetch_ab_testing_data('hello') +# puts mgr.get_ab_testing_message('hello') +# puts mgr.get_ab_testing_page('hello') diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 9ef6db1..d0d6209 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,459 +1,580 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_comm_layer' +require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' -#require 'ruby-debug' +require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls + @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil - - attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url + + attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end - + if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i + + ##### possibly overriding ab_testing_host/port with some testing host port ##### + if app_config_map.has_key? 'ab_testing_host' + @m_ab_testing_host = app_config_map['ab_testing_host'] + elsif @config.has_key? 'ab_testing_host' + @m_ab_testing_host = @config['ab_testing_host'] + end + + if app_config_map.has_key? 'ab_testing_port' + @m_ab_testing_port = app_config_map['ab_testing_port'] + elsif @config.has_key? 'ab_testing_port' + @m_ab_testing_port = @config['ab_testing_port'] + end + + ##### the normal ab_testing_host/port ##### + if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? + if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' + @m_ab_testing_host = 'http://www.kontagent.com' + @m_ab_testing_port = 80 + end + end end - + public - def init() - init_from_conf() + # assumption : st1_str is set to the campaign_name + def format_kt_st1(st1_str) + handle_index = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_campaign_handle_index(st1_str) + if !handle_index.nil? + if handle_index > 0 + return "aB_"+ st1_str + handle_index.to_s + else + return "aB_"+st1_str + end + else + return "aB_" + end + end + + def format_kt_st2(st2_str) + return "m"+st2_str.to_s + end + + def format_kt_st3(st3_str) + return "p"+st3_str.to_s + end + + def init(custom_conf = nil) + init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) + @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, + @m_ab_testing_host, + @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id - @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) - return url, uuid + return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end + def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) + uuid = gen_long_uuid + url = get_invite_post_link_vo(post_link, uid, uuid, campaign) + return url , uuid + end + + def get_invite_post_link_vo(post_link, uid, uuid, campaign) + arg_hash = {} + arg_hash['kt_uid'] = uid + arg_hash['kt_ut'] = uuid + arg_hash['kt_type'] = 'ins' + arg_hash['kt_d'] = @@S_directed_val + + arg_hash['kt_st1'] = format_kt_st1(campaign) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + arg_hash['kt_st2'] = format_kt_st2(msg_id) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + arg_hash['kt_st3'] = format_kt_st3(page_id) + + r_url = append_kt_query_str(post_link, arg_hash.to_query) + return r_url + end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end - + def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end + def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) + uuid = gen_long_uuid + url = get_invite_post_link_vo(content_link, uid, uuid, campaign) + return url, uuid + end + + def get_invite_content_link_vo(content_link, uid, uuid, campaign) + arg_hash = {} + arg_hash['kt_uid'] = uid + arg_hash['kt_ut'] = uuid + arg_hash['kt_type'] = 'in' + arg_hash['kt_d'] = @@S_directed_val + + arg_hash['kt_st1'] = format_kt_st1(campaign) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + arg_hash['kt_st2'] = format_kt_st2(msg_id) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + arg_hash['kt_st3'] = format_kt_st3(page_id) + + r_url = append_kt_query_str(content_link, arg_hash.to_query) + return r_url + end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) - uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } + return uuid,input_txt end #gen_kt_comm_link + + def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) + uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, + format_kt_st1(campaign), + format_kt_st2(msg_id), + format_kt_st3(page_id)) + input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| + if $1.nil? + input_txt + else + append_kt_query_str($1, query_str) + end + } + input_txt = input_txt.gsub(@@KT_AB_MSG){|match| + msg_txt + } + return uuid, input_txt + end + def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) - uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href + def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, + format_kt_st1(campaign), + format_kt_st2(msg_id), + format_kt_st3(page_id)) + input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| + if $1.nil? + input_txt + else + append_kt_query_str($1, query_str) + end + } + return uuid, input_txt + end + def send_user_data_impl(user) arg_hash = {} - + arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' - arg_hash['b'] = user.birthday + arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' - arg_hash['g'] = user.sex + arg_hash['g'] = user.sex[0,1] end - if !user.current_location.city.blank? &&user.current_location.city != '' - arg_hash['ly'] = user.current_location.city - end - if !user.current_location.state.blank? && user.current_location.state != '' - arg_hash['ls'] = user.current_location.state - end - if !user.current_location.country.blank? && user.current_location.country != '' - arg_hash['lc'] = user.current_location.country - end - if !user.current_location.zip.blank? && user.current_location.zip != '' - arg_hash['lp'] = user.current_location.zip - end + # if !user.current_location.city.blank? &&user.current_location.city != '' + # arg_hash['ly'] = user.current_location.city + # end + # if !user.current_location.state.blank? && user.current_location.state != '' + # arg_hash['ls'] = user.current_location.state + # end + # if !user.current_location.country.blank? && user.current_location.country != '' + # arg_hash['lc'] = user.current_location.country + # end + # if !user.current_location.zip.blank? && user.current_location.zip != '' + # arg_hash['lp'] = user.current_location.zip + # end - if !user.hometown_location.city.blank? &&user.hometown_location.city != '' - arg_hash['ly'] = user.hometown_location.city - end - if !user.hometown_location.state.blank? && user.hometown_location.state != '' - arg_hash['ls'] = user.hometown_location.state - end - if !user.hometown_location.country.blank? && user.hometown_location.country != '' - arg_hash['lc'] = user.hometown_location.country - end - if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' - arg_hash['lp'] = user.hometown_location.zip - end + # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' + # arg_hash['ly'] = user.hometown_location.city + # end + # if !user.hometown_location.state.blank? && user.hometown_location.state != '' + # arg_hash['ls'] = user.hometown_location.state + # end + # if !user.hometown_location.country.blank? && user.hometown_location.country != '' + # arg_hash['lc'] = user.hometown_location.country + # end + # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' + # arg_hash['lp'] = user.hometown_location.zip + # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end - + def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end - + end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] - if request_params['kt_t'] != nil - arg_hash['t'] = request_params[:kt_t] - end + + arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? + arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? + arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? + arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? + kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' - if request_params[:kt_t] != nil - arg_hash['t'] = request_params[:kt_t] - end - if request_params[:kt_st1] != nil - arg_hash['st1'] = request_params[:kt_st1] - end - if request_params[:kt_st2] != nil - arg_hash['st2'] = request_params[:kt_st2] - end + arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? + arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? + arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? + arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? + kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil + arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() - CGI::Session.generate_unique_id('kontagent') + begin + CGI::Session.generate_unique_id('kontagent') + rescue + # Rails 2.3 fix + ActiveSupport::SecureRandom.hex(16) + end end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end - if request_params.has_key? 'kt_t' - arg_hash['t'] = request_params[:kt_t] - end - if request_params.has_key? 'kt_st1' - arg_hash['st1'] = request_params[:kt_st1] - end - if request_params.has_key? 'kt_st2' - arg_hash['st2'] = request_params[:kt_st2] - end + + arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' + arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' + arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' + arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' + uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end - def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end - if template_id != nil - param_array[:kt_t] = template_id.to_s - end - - if subtype1 != nil - param_array[:kt_st1] = subtype1 - end - - if subtype2 != nil - param_array[:kt_st2] = subtype2 - end + param_array[:kt_t] = template_id.to_s if !template_id.nil? + param_array[:kt_st1] = subtype1 if !subtype1.nil? + param_array[:kt_st2] = subtype2 if !subtype2.nil? + param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index 4fd292e..8f0600c 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,143 +1,138 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER #require 'socket' require 'net/http' -#require 'timeout' +require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port + + if @m_host == "api.geo.kontagent.net" + @m_ip = fetch_ip() + else + @m_ip = host + end end + + def _fetch_ip_helper(host_name_str, port) + ip_lst = Socket.getaddrinfo(host_name_str, 'http') + ip_lst.sort_by{ rand } + selected_ip = nil + + ip_lst.each do |ip_info| + ip_str = ip_info[3] + socket = Socket.new(AF_INET, SOCK_STREAM, 0) + sockaddr = Socket.sockaddr_in(port, ip_str) + status = -1 + timeout(2) do + status = socket.connect(sockaddr) + end + if status == 0 + selected_ip = ip_str + break + end + end #loop + return selected_ip + end # _fetch_ip_helper + + def fetch_ip() + selected_ip = _fetch_ip_helper(@m_host, @m_port) + if selected_ip.nil? + selected_ip = _fetch_ip_helper("api.global.kontagent.net", 80) + end + + return selected_ip + end + public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end + # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) -# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) -# url_path = "http://"+@m_host+":"+@m_port.to_s+url_path -# uri = URI.parse(url_path) -# Net::HTTP.get(uri) socket = Socket.new(AF_INET, SOCK_STREAM, 0) - sockaddr = Socket.sockaddr_in(@m_port, @m_host) - + sockaddr = Socket.sockaddr_in(@m_port, @m_ip) + connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN connected = false puts "Errno::EISCONN!!" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" - buf << "Host:" + @m_host + "\r\n" + buf << "Host:" + @m_ip + ":" + @m_port.to_s + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected -# socket = nil - -# puts @m_host -# begin -# timeout(2) do -# #socket = TCPSocket::new(@m_host, 80) #uncomment this -# socket = TCPSocket::new(@m_host, @m_port) -# end -# rescue Timeout::Error -# puts "timeout!!!" -# return -# rescue -# puts "tcp error!!!!" -# return -# end - -# if socket != nil -# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) -# #puts "url_path: #{url_path}" #xxx - -# buf = "GET " + url_path + " HTTP/1.1\r\n" -# buf << "Host:" + @m_host + "\r\n" -# buf << "Content-type: application/x-www-form-urlencoded\r\n" -# buf << "Accept: */*\r\n" -# buf << "\r\n" -# buf << "\r\n" -# socket.write buf -# socket.close -# end - - # old code - # socket.write("GET " + url_path + " HTTP/1.1\r\n") - # socket.write("Host:" + @m_host + "\r\n") - # socket.write("Content-type: application/x-www-form-urlencoded\r\n") - # socket.write("Accept: */*\r\n") - # socket.write("\r\n") - # socket.write("\r\n") - # socket.close - #end end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test #comm = Kontagent::Kt_Comm.new('67.102.65.65') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'}) diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 6656301..1b71e84 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,179 +1,190 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'facebooker' -#require 'ruby-debug' +require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) + controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end + def set_ab_testing_page(campaign) + page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) + msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) + Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) + end + # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end + def store_user_id + $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? + return true + end + def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params - $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? - + # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index c802583..c8c7305 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,60 +1,125 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version KONTAGENT_VERSION_NUMBER require 'kt/kt_analytics' require 'cgi' +require 'ruby-debug' module Kt module Rails module KontagentHelpers + def kt_get_page_text(campaign) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + return page_text + end + + def kt_get_msg_text(campaign) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + return msg_text + end + def kt_get_msg_buttons(campaign, index) + msg_id, msg_buttons = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info_button(campaign) + if msg_id.nil? + return "" + end + + if msg_buttons[index].nil? + return "" + else + msg_buttons[index] + end + end + + def kt_get_invite_post_link_vo(invite_post_link, campaign) + url = nil + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + + if session['invite_uuid'].nil? + url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, + uid, + campaign) + session['invite_uuid'] = uuid + else + url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, + uid, + session['invite_uuid'], + campaign) +# session['invite_uuid'] = nil + end + return url + end + + def kt_clear_invite_tag() + session['invite_uuid'] = nil + end + + def kt_get_invite_content_link_vo(invite_content_link, campaign) + url = nil + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + + if session['invite_uuid'].nil? + url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, + uid, + campaign) + session['invite_uuid'] = uuid + else + url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, + uid, + session['invite_uuid'], + campaign) + #session['invite_uuid'] = nil + end + return url + end + def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - if session['invite_uuid'] == nil + if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) - session['invite_uuid'] = nil + #session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - if session['invite_uuid'] == nil + if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) - session['invite_uuid'] = nil + #session['invite_uuid'] = nil end return url end def kt_track_page_view() uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end end end end
rmatei/kt
4098e43f6b1ceb95690b47b8b019fd7c46f0758d
fix demographics
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 7ef77fe..4031a2f 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,580 +1,578 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 end end end public def format_kt_st1(st1_str) return "aB_"+st1_str end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} - + arg_hash['s'] = user.id if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # debugging - RAILS_DEFAULT_LOGGER.warn "kt demographics - birthday: #{arg_hash['b'].inspect}" - RAILS_DEFAULT_LOGGER.warn "kt demographics - gender: #{arg_hash['g'].inspect}" - + RAILS_DEFAULT_LOGGER.warn "kt demographics - birthday: #{user.birthday.inspect} => #{arg_hash['b']}" if arg_hash['b'].length < 4 # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
761c963bc64b8f17b45a9389860dd5cd7d6e899f
grepable logging
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index c3b86b3..0abc81b 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,579 +1,579 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 end end end public def format_kt_st1(st1_str) return "aB_"+st1_str end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end # debugging - RAILS_DEFAULT_LOGGER.warn arg_hash['b'].inspect - RAILS_DEFAULT_LOGGER.warn arg_hash['g'].inspect + RAILS_DEFAULT_LOGGER.warn "kt demographics - birthday: #{arg_hash['b'].inspect}" + RAILS_DEFAULT_LOGGER.warn "kt demographics - gender: #{arg_hash['g'].inspect}" # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
727fd4ef5015059bd87c15ed396e83f2a955ddfc
add logging for demographics debugging
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index ddc7502..c3b86b3 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,575 +1,579 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 end end end public def format_kt_st1(st1_str) return "aB_"+st1_str end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex[0,1] end + # debugging + RAILS_DEFAULT_LOGGER.warn arg_hash['b'].inspect + RAILS_DEFAULT_LOGGER.warn arg_hash['g'].inspect + # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
63473f670528e54fc4a29642fae42bda9be118cb
fix demographics and turn them back on outside of snowball
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index e8205d7..ddc7502 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,575 +1,575 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 end end end public def format_kt_st1(st1_str) return "aB_"+st1_str end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init(custom_conf = nil) init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} if !user.birthday.blank? && user.birthday != '' - arg_hash['b'] = user.birthday + arg_hash['b'] = user.birthday.split(" ")[-1] end if !user.sex.blank? && user.sex != '' - arg_hash['g'] = user.sex + arg_hash['g'] = user.sex[0,1] end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index fadc9e4..a72e384 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,192 +1,192 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin - unless true or App.current.theme.template.code == "snowball" + unless App.current.theme.template.code == "snowball" user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks end rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
1dac953395adb44e281427380502e5f2af292506
better rescue
diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index 89eb1ef..cb821c2 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,187 +1,189 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' require 'ruby-debug' module Kt class AB_Testing_Manager @@URL_PREFIX = "/abtest/campaign_info"; public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} rescue Exception => e + # LOCAL - to save our tests... puts "Failed to initialize KT A/B testing: #{e.message}" + RAILS_DEFAULT_LOGGER.warn "Failed to initialize KT A/B testing: #{e.message}" end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" if force == true url_str += "?f=1" end url = URI.parse(url_str) req = Net::HTTP::Get.new(url.path+"?"+url.query) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true msg_lst = json_obj["messages"] msg_weight_array = [] curr_idx = 0 # process message list msg_lst.each do |m| w = m[1] w.times { msg_weight_array << curr_idx } curr_idx += 1 end # process page list page_lst = json_obj['pages'] page_weight_array = [] curr_idx = 0 page_lst.each do |p| w = p[1] w.times { page_weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['msg_weight'] = msg_weight_array store_dict['page_weight'] = page_weight_array r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end public def get_selected_msg_info(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[2] end end def get_selected_page_info(campaign) page_info = @m_selected_msg_page_pair_dict[campaign]['page'] if page_info.nil? return nil else return page_info[0], page_info[2] end end private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module # mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', # 'http://kthq.dyndns.org', 9999) # #mgr.fetch_ab_testing_data('hello') # puts mgr.get_ab_testing_message('hello') # puts mgr.get_ab_testing_page('hello')
rmatei/kt
aafd4bfecf26cdff14a5900e2b84dd14e97886cd
turn demographics off across the board
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index dfad403..fadc9e4 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,190 +1,192 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin - user = session[:facebook_session].user - key = "KT_" + Facebooker.api_key + "_" + user.id.to_s - if cookies[key].blank? - Kt::KtAnalytics.instance.send_user_data(user) + unless true or App.current.theme.template.code == "snowball" + user = session[:facebook_session].user + key = "KT_" + Facebooker.api_key + "_" + user.id.to_s + if cookies[key].blank? + Kt::KtAnalytics.instance.send_user_data(user) + end + cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks end - cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
14185e179e0b03e759eb7aaa1a10c3813fb0527a
adding rescue for A/B testing initialization
diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb index f95cd61..89eb1ef 100644 --- a/lib/kt/kt_ab_testing.rb +++ b/lib/kt/kt_ab_testing.rb @@ -1,185 +1,187 @@ require 'rubygems' #xxx require 'memcache' require 'net/http' require 'uri' require 'json' require 'ruby-debug' module Kt class AB_Testing_Manager @@URL_PREFIX = "/abtest/campaign_info"; public def initialize(kt_api_key, kt_secret_key, kt_ab_backend_host, kt_ab_backend_port) @m_backend_api_key = kt_api_key @m_backend_secret_key = kt_secret_key @m_ab_backend_host = kt_ab_backend_host @m_ab_backend_port = kt_ab_backend_port if @m_ab_backend_port != 80 @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s else @m_ab_backend = @m_ab_backend_host end @m_memcached_server = MemCache.new '127.0.0.1' @m_selected_msg_page_pair_dict = {} + rescue Exception => e + puts "Failed to initialize KT A/B testing: #{e.message}" end private def fetch_ab_testing_data(campaign, force=false) begin url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" if force == true url_str += "?f=1" end url = URI.parse(url_str) req = Net::HTTP::Get.new(url.path+"?"+url.query) res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) } json_obj = JSON.parse(res.body) if json_obj["changed"] == true msg_lst = json_obj["messages"] msg_weight_array = [] curr_idx = 0 # process message list msg_lst.each do |m| w = m[1] w.times { msg_weight_array << curr_idx } curr_idx += 1 end # process page list page_lst = json_obj['pages'] page_weight_array = [] curr_idx = 0 page_lst.each do |p| w = p[1] w.times { page_weight_array << curr_idx } curr_idx += 1 end store_dict = {} store_dict['json'] = json_obj store_dict['msg_weight'] = msg_weight_array store_dict['page_weight'] = page_weight_array r = store_dict @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) else # no change @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) end rescue Errno::ECONNREFUSED # TODO fall back on some default value end return r end private def get_ab_helper(campaign) fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) if fake_key_is_valid.nil? # The real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = fetch_ab_testing_data(campaign) end else # Likewise, the real key should have a valid json object. # If not, invoke fetch_ab_testin_data with force = true serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) if serialized_campaign_str.nil? r = fetch_ab_testing_data(campaign, true) # force it else r = Marshal.load( serialized_campaign_str ) end end return r end public def get_ab_testing_message(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] msg_lst = json_obj['messages'] weight_array = dict['msg_weight'] index = weight_array[rand(weight_array.size)] return msg_lst[index] end end public def get_ab_testing_page(campaign) dict = get_ab_helper(campaign) if dict.nil? return nil else json_obj = dict['json'] page_lst = json_obj['pages'] weight_array = dict['page_weight'] index = weight_array[rand(weight_array.size)] return page_lst[index] end end public def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} end public def get_selected_msg_info(campaign) msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] if msg_info.nil? return nil else return msg_info[0], msg_info[2] end end def get_selected_page_info(campaign) page_info = @m_selected_msg_page_pair_dict[campaign]['page'] if page_info.nil? return nil else return page_info[0], page_info[2] end end private def gen_memcache_fake_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" end private def gen_memcache_key(campaign) return "kt_"+@m_backend_api_key+"_"+campaign end end end # module # mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', # 'http://kthq.dyndns.org', 9999) # #mgr.fetch_ab_testing_data('hello') # puts mgr.get_ab_testing_message('hello') # puts mgr.get_ab_testing_page('hello')
rmatei/kt
0e987e29e097f4097d7bbcd0b1228b155b70a2ae
Monkey patching undefined method or variable error
diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb index b1568bd..e4c8cd5 100644 --- a/lib/facebook/session.rb +++ b/lib/facebook/session.rb @@ -1,150 +1,150 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'ruby-debug' module Facebooker class Session def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) if !campaign.nil? # ab testing msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nt, nil, campaign, msg_id, page_id, msg_txt) else uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) end r = send_notification_without_kontagent(user_ids, fbml, email_fbml) if !r.blank? arg_hash = { 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } if source_user.nil? arg_hash['s'] = 0.to_s else arg_hash['s'] = source_user.id.to_s end arg_hash['t'] = template_id.to_s unless template_id.nil? if !campaign.nil? arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) else arg_hash['st1'] = st1 arg_hash['st2'] = st2 - arg_hash['st3'] = st3 + arg_hash['st3'] = st3 rescue nil end Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) end end def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) if !campaign.nil? # ab testing msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) if fbml != nil uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nte, nil, campaign, msg_id, page_id, msg_txt) else uuid = Kt::KtAnalytics.instance.gen_long_uuid end else if fbml != nil uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, template_id, st1, st2, st3) else uuid = Kt::KtAnalytics.instance.gen_long_uuid end end r = send_email_without_kontagent(user_ids, subject, text, fbml) if !r.blank? arg_hash = { 's' => @user.id.to_s , 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } arg_hash['t'] = template_id.to_s unless template_id.nil? if !campaign.nil? arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) else arg_hash['st1'] = st1 arg_hash['st2'] = st2 end Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) end end # if st2 is set to m{d} and st3 is set to p{d}, we'll assume that it's using ab_testing data. def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil, campaign=nil) if !campaign.nil? msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) st1 = campaign st2 = msg_id st3 = page_id end if(data != nil) data.each_pair do |key,value | if key == :image if !campaign.nil? uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(value[:href], :fdp, bundle_id, st1, st2, st3, campaign) else uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, bundle_id, st1, st2) end value[:href] = fbml data[key] = value # do we even need this line? elsif key == :flash elsif key == :mp3 #Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) elsif key == :video else if !campaign.nil? uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href_vo(value, :fdp, bundle_id, st1, st2, st3) else uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) end data[key] = fbml end end end data['KT_AB_MSG'] = msg_txt if !campaign.nil? r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) if !r.blank? arg_hash = { 'pt' => 4, 's' => @user.id.to_s, 't' => bundle_id } Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) end end alias_method_chain :send_notification, :kontagent alias_method_chain :send_email, :kontagent alias_method_chain :publish_user_action, :kontagent end end
rmatei/kt
8b9188548f1c6bea3f08549b0ad593b52b231726
allow dynamic configs again
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 33baf86..e8205d7 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,575 +1,575 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 end end end public def format_kt_st1(st1_str) return "aB_"+st1_str end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end - def init() - init_from_conf() + def init(custom_conf = nil) + init_from_conf(custom_conf) # to allow use of dynamic configs that aren't in the YML @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index e63aea9..dfad403 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,190 +1,190 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" - r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, + r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
2dc47d1c0636b9582c5dffcc1cfe6622de7974ee
adding New Relic instrumentation to version 2
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 1c613d8..33baf86 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,568 +1,575 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 end end end public def format_kt_st1(st1_str) return "aB_"+st1_str end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init() init_from_conf() @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end + begin + require "#{RAILS_ROOT}/vendor/plugins/rpm/init" + add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' + rescue + puts "Failed to add New Relic instrumentation to Kontagent." + end + # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') rescue # Rails 2.3 fix ActiveSupport::SecureRandom.hex(16) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
8e4178ba625e5cfd2dc7c3249448ea528f48edde
Rails 2.3 fix for unique ID
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 328328b..1c613d8 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,565 +1,568 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i ##### possibly overriding ab_testing_host/port with some testing host port ##### if app_config_map.has_key? 'ab_testing_host' @m_ab_testing_host = app_config_map['ab_testing_host'] elsif @config.has_key? 'ab_testing_host' @m_ab_testing_host = @config['ab_testing_host'] end if app_config_map.has_key? 'ab_testing_port' @m_ab_testing_port = app_config_map['ab_testing_port'] elsif @config.has_key? 'ab_testing_port' @m_ab_testing_port = @config['ab_testing_port'] end ##### the normal ab_testing_host/port ##### if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' @m_ab_testing_host = 'http://www.kontagent.com' @m_ab_testing_port = 80 end end end public def format_kt_st1(st1_str) return "aB_"+st1_str end def format_kt_st2(st2_str) return "m"+st2_str.to_s end def format_kt_st3(st3_str) return "p"+st3_str.to_s end def init() init_from_conf() @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, @m_ab_testing_host, @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(post_link, uid, uuid, campaign) return url , uuid end def get_invite_post_link_vo(post_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'ins' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) uuid = gen_long_uuid url = get_invite_post_link_vo(content_link, uid, uuid, campaign) return url, uuid end def get_invite_content_link_vo(content_link, uid, uuid, campaign) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val arg_hash['kt_st1'] = format_kt_st1(campaign) msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) arg_hash['kt_st2'] = format_kt_st2(msg_id) page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) arg_hash['kt_st3'] = format_kt_st3(page_id) r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } input_txt = input_txt.gsub(@@KT_AB_MSG){|match| msg_txt } return uuid, input_txt end def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, format_kt_st1(campaign), format_kt_st2(msg_id), format_kt_st3(page_id)) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end def send_user_data_impl(user) arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') + rescue + # Rails 2.3 fix + ActiveSupport::SecureRandom.hex(16) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end param_array[:kt_t] = template_id.to_s if !template_id.nil? param_array[:kt_st1] = subtype1 if !subtype1.nil? param_array[:kt_st2] = subtype2 if !subtype2.nil? param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
5418f5ac59ac4e8b25b560b4ec2600a3e7d0319e
import version 0.2.0
diff --git a/init.rb b/init.rb index e494bea..9cc816c 100644 --- a/init.rb +++ b/init.rb @@ -1,57 +1,57 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 puts "loading kt..." require 'facebook/session' require 'kt/rails/helpers' require 'facebooker/rails/publisher' require 'facebook/rails/publisher' #require 'facebooker/rails/controller' require 'facebook/rails/controller' require 'kt/rails/controller' config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") if config['mode'] == 'async' require 'starling' require 'starling_ext' require 'kt/queue/queue' require 'kt/queue/processor' require 'kt/queue/task' # Load app applicable Kontagent::Queue::Processor subclasses from app/processors Dir[RAILS_ROOT + '/app/processors/*.rb'].each do |file| require file end end module ::ActionController class Base def self.inherited_with_kt(subclass) inherited_without_kt(subclass) if subclass.to_s == "ApplicationController" subclass.class_eval do subclass.send(:include,Kt::Rails::Controller) end end end #def class << self alias_method_chain :inherited, :kt end end end ActionView::Base.send :include, Kt::Rails::KontagentHelpers diff --git a/install.rb b/install.rb index 570c7f9..906cff2 100644 --- a/install.rb +++ b/install.rb @@ -1,20 +1,20 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 # Install hook code here require 'fileutils' require 'rubygems' #require 'ruby-debug' #xxx if ARGV.size != 2 puts "Failure: you need to pass in the controller_name" else controller_name = ARGV[1] handle_iframe_html_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.html.erb") handle_iframe_fbml_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.fbml.erb") kontagent_yml_dst = File.join(RAILS_ROOT, "config", "kontagent.yml") puts "copying kontagent.yml.erb to #{kontagent_yml_dst}" FileUtils.cp( File.join(RAILS_ROOT, "vendor", "plugins", "kt", 'kontagent.yml.tpl'), kontagent_yml_dst ) unless File.exists?( kontagent_yml_dst ) end diff --git a/kontagent.yml.tpl b/kontagent.yml.tpl index 4d2b5c5..846c73c 100644 --- a/kontagent.yml.tpl +++ b/kontagent.yml.tpl @@ -1,130 +1,131 @@ # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false + ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb index e6a35ef..fe5991d 100644 --- a/lib/facebook/rails/controller.rb +++ b/lib/facebook/rails/controller.rb @@ -1,25 +1,25 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' module Facebooker module Rails module Controller def application_is_not_installed_by_facebook_user_with_kontagent if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") redirect_to session[:facebook_session].install_url else local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") end end #application_is_not_installed_by_facebook_user_with_kontagent alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent end #module Controller end end diff --git a/lib/facebook/rails/publisher.rb b/lib/facebook/rails/publisher.rb index 150e15e..dee9cc1 100644 --- a/lib/facebook/rails/publisher.rb +++ b/lib/facebook/rails/publisher.rb @@ -1,62 +1,68 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 + module Facebooker module Rails class Publisher def template(arg) @template = arg end def subtype1(arg) @subtype1 = arg end def subtype2(arg) @subtype2 = arg end + def campaign(arg) + @campaign = arg + end def send_message_with_kontagent(method) @recipients = @recipients.is_a?(Array) ? @recipients : [@recipients] if from.nil? and @recipients.size==1 and ! announcement_notification?(from,_body) @from = @recipients.first end # notifications can # omit the from address raise InvalidSender.new("Sender must be a Facebooker::User") unless from.is_a?(Facebooker::User) || announcement_notification?(from,_body) case _body when Facebooker::Feed::TemplatizedAction,Facebooker::Feed::Action from.publish_action(_body) when Facebooker::Feed::Story @recipients.each {|r| r.publish_story(_body)} when Notification - (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, @template, @subtype1, @subtype2) + (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, + @template, @subtype1, @subtype2, @campaign) when Email from.session.send_email(@recipients, _body.title, _body.text, _body.fbml, @template, @subtype1, - @subtype2) + @subtype2, + @campaign) when Profile # If recipient and from aren't the same person, create a new user object using the # userid from recipient and the session from from if @from != @recipients.first @from = Facebooker::User.new(Facebooker::User.cast_to_facebook_id(@recipients.first),from.session) end from.set_profile_fbml(_body.profile, _body.mobile_profile, _body.profile_action, _body.profile_main) when Ref @from.session.server_cache.set_ref_handle(_body.handle,_body.fbml) when UserAction - @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general) + @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general, @subtype1, @subtype2, @campaign) else raise UnspecifiedBodyType.new("You must specify a valid send_as") end end alias_method_chain :send_message, :kontagent end end end diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb index bb4263c..b1568bd 100644 --- a/lib/facebook/session.rb +++ b/lib/facebook/session.rb @@ -1,94 +1,150 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' +require 'ruby-debug' module Facebooker class Session - def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil) - uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) + def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) + + if !campaign.nil? + # ab testing + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nt, nil, campaign, msg_id, page_id, msg_txt) + else + uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) + end r = send_notification_without_kontagent(user_ids, fbml, email_fbml) if !r.blank? arg_hash = { - #'s' => @user.id.to_s, 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } if source_user.nil? arg_hash['s'] = 0.to_s else arg_hash['s'] = source_user.id.to_s end arg_hash['t'] = template_id.to_s unless template_id.nil? - Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) unless App.current.theme.template.code == "snowball" + if !campaign.nil? + arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) + arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) + arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) + else + arg_hash['st1'] = st1 + arg_hash['st2'] = st2 + arg_hash['st3'] = st3 + end + + Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) end end - def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil) - if fbml != nil - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, - template_id, st1, st2) + def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) + if !campaign.nil? + # ab testing + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + if fbml != nil + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nte, nil, campaign, msg_id, page_id, msg_txt) + else + uuid = Kt::KtAnalytics.instance.gen_long_uuid + end else - uuid = Kt::KtAnalytics.instance.gen_long_uuid + if fbml != nil + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, template_id, st1, st2, st3) + else + uuid = Kt::KtAnalytics.instance.gen_long_uuid + end end r = send_email_without_kontagent(user_ids, subject, text, fbml) if !r.blank? arg_hash = { 's' => @user.id.to_s , 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } + arg_hash['t'] = template_id.to_s unless template_id.nil? + if !campaign.nil? + arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) + arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) + arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) + else + arg_hash['st1'] = st1 + arg_hash['st2'] = st2 + end Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) end end - def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil) + # if st2 is set to m{d} and st3 is set to p{d}, we'll assume that it's using ab_testing data. + def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil, campaign=nil) + if !campaign.nil? + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + st1 = campaign + st2 = msg_id + st3 = page_id + end + if(data != nil) data.each_pair do |key,value | if key == :image - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, - bundle_id, st1, st2) + if !campaign.nil? + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(value[:href], :fdp, + bundle_id, st1, st2, st3, campaign) + else + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, + bundle_id, st1, st2) + end value[:href] = fbml data[key] = value # do we even need this line? elsif key == :flash elsif key == :mp3 - Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) + #Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) elsif key == :video - else - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) + if !campaign.nil? + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href_vo(value, :fdp, bundle_id, st1, st2, st3) + else + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) + end data[key] = fbml end end end + data['KT_AB_MSG'] = msg_txt if !campaign.nil? + r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) - + if !r.blank? arg_hash = { 'pt' => 4, 's' => @user.id.to_s, 't' => bundle_id } - Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) unless App.current.theme.template.code == "snowball" + Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) end end alias_method_chain :send_notification, :kontagent alias_method_chain :send_email, :kontagent alias_method_chain :publish_user_action, :kontagent end end diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index a66602e..328328b 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,475 +1,565 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' +require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' -#require 'ruby-debug' +require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls + @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil - - attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url + + attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end - + if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i + + ##### possibly overriding ab_testing_host/port with some testing host port ##### + if app_config_map.has_key? 'ab_testing_host' + @m_ab_testing_host = app_config_map['ab_testing_host'] + elsif @config.has_key? 'ab_testing_host' + @m_ab_testing_host = @config['ab_testing_host'] + end + + if app_config_map.has_key? 'ab_testing_port' + @m_ab_testing_port = app_config_map['ab_testing_port'] + elsif @config.has_key? 'ab_testing_port' + @m_ab_testing_port = @config['ab_testing_port'] + end + + ##### the normal ab_testing_host/port ##### + if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? + if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' + @m_ab_testing_host = 'http://www.kontagent.com' + @m_ab_testing_port = 80 + end + end end - + public - def init(custom_conf = nil) - init_from_conf(custom_conf) + def format_kt_st1(st1_str) + return "aB_"+st1_str + end + + def format_kt_st2(st2_str) + return "m"+st2_str.to_s + end + + def format_kt_st3(st3_str) + return "p"+st3_str.to_s + end + + def init() + init_from_conf() @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) + @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, + @m_ab_testing_host, + @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id - @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) - return url, uuid + return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end + def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) + uuid = gen_long_uuid + url = get_invite_post_link_vo(post_link, uid, uuid, campaign) + return url , uuid + end + + def get_invite_post_link_vo(post_link, uid, uuid, campaign) + arg_hash = {} + arg_hash['kt_uid'] = uid + arg_hash['kt_ut'] = uuid + arg_hash['kt_type'] = 'ins' + arg_hash['kt_d'] = @@S_directed_val + + arg_hash['kt_st1'] = format_kt_st1(campaign) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + arg_hash['kt_st2'] = format_kt_st2(msg_id) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + arg_hash['kt_st3'] = format_kt_st3(page_id) + + r_url = append_kt_query_str(post_link, arg_hash.to_query) + return r_url + end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end - + def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end + def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) + uuid = gen_long_uuid + url = get_invite_post_link_vo(content_link, uid, uuid, campaign) + return url, uuid + end + + def get_invite_content_link_vo(content_link, uid, uuid, campaign) + arg_hash = {} + arg_hash['kt_uid'] = uid + arg_hash['kt_ut'] = uuid + arg_hash['kt_type'] = 'in' + arg_hash['kt_d'] = @@S_directed_val + + arg_hash['kt_st1'] = format_kt_st1(campaign) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + arg_hash['kt_st2'] = format_kt_st2(msg_id) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + arg_hash['kt_st3'] = format_kt_st3(page_id) + + r_url = append_kt_query_str(content_link, arg_hash.to_query) + return r_url + end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) - uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } + return uuid,input_txt end #gen_kt_comm_link + + def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) + uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, + format_kt_st1(campaign), + format_kt_st2(msg_id), + format_kt_st3(page_id)) + input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| + if $1.nil? + input_txt + else + append_kt_query_str($1, query_str) + end + } + input_txt = input_txt.gsub(@@KT_AB_MSG){|match| + msg_txt + } + return uuid, input_txt + end + def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) - uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href - def send_user_data_impl(user) - time("making API calls for Kontagent user data") do - arg_hash = {} - - if !user.birthday.blank? && user.birthday != '' - arg_hash['b'] = user.birthday - end - if !user.sex.blank? && user.sex != '' - arg_hash['g'] = user.sex + def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, + format_kt_st1(campaign), + format_kt_st2(msg_id), + format_kt_st3(page_id)) + input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| + if $1.nil? + input_txt + else + append_kt_query_str($1, query_str) end + } + return uuid, input_txt + end + + def send_user_data_impl(user) + arg_hash = {} - # if !user.current_location.city.blank? &&user.current_location.city != '' - # arg_hash['ly'] = user.current_location.city - # end - # if !user.current_location.state.blank? && user.current_location.state != '' - # arg_hash['ls'] = user.current_location.state - # end - # if !user.current_location.country.blank? && user.current_location.country != '' - # arg_hash['lc'] = user.current_location.country - # end - # if !user.current_location.zip.blank? && user.current_location.zip != '' - # arg_hash['lp'] = user.current_location.zip - # end - # - # - # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' - # arg_hash['ly'] = user.hometown_location.city - # end - # if !user.hometown_location.state.blank? && user.hometown_location.state != '' - # arg_hash['ls'] = user.hometown_location.state - # end - # if !user.hometown_location.country.blank? && user.hometown_location.country != '' - # arg_hash['lc'] = user.hometown_location.country - # end - # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' - # arg_hash['lp'] = user.hometown_location.zip - # end - - arg_hash['f'] = user.friends.size.to_s - # RAILS_DEFAULT_LOGGER.warn arg_hash.inspect # LOCAL + if !user.birthday.blank? && user.birthday != '' + arg_hash['b'] = user.birthday + end + if !user.sex.blank? && user.sex != '' + arg_hash['g'] = user.sex end +# if !user.current_location.city.blank? &&user.current_location.city != '' +# arg_hash['ly'] = user.current_location.city +# end +# if !user.current_location.state.blank? && user.current_location.state != '' +# arg_hash['ls'] = user.current_location.state +# end +# if !user.current_location.country.blank? && user.current_location.country != '' +# arg_hash['lc'] = user.current_location.country +# end +# if !user.current_location.zip.blank? && user.current_location.zip != '' +# arg_hash['lp'] = user.current_location.zip +# end + + +# if !user.hometown_location.city.blank? &&user.hometown_location.city != '' +# arg_hash['ly'] = user.hometown_location.city +# end +# if !user.hometown_location.state.blank? && user.hometown_location.state != '' +# arg_hash['ls'] = user.hometown_location.state +# end +# if !user.hometown_location.country.blank? && user.hometown_location.country != '' +# arg_hash['lc'] = user.hometown_location.country +# end +# if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' +# arg_hash['lp'] = user.hometown_location.zip +# end + + arg_hash['f'] = user.friends.size.to_s + kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] - if request_params['kt_t'] != nil - arg_hash['t'] = request_params[:kt_t] - end + + arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? + arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? + arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? + arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? + kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' - if request_params[:kt_t] != nil - arg_hash['t'] = request_params[:kt_t] - end - if request_params[:kt_st1] != nil - arg_hash['st1'] = request_params[:kt_st1] - end - if request_params[:kt_st2] != nil - arg_hash['st2'] = request_params[:kt_st2] - end + arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? + arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? + arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? + arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? + kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil + arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) - time("sending Kontagent message (#{arg_hash.inspect})") do - if @m_mode == :async - #timeout(@m_timeout) do - data_hash = { - :qtype => :kt_outbound, - :ctype => type, - :v => 'v1', - :kt_api_key => @m_kt_api_key, - :kt_secret_key => @m_kt_secret_key, - :kt_call_back_host => @m_kt_host, - :kt_call_back_port => @m_kt_host_port, - :kt_url => @m_kt_url, - :arg_hash => arg_hash, - } - Kt::Queue::Task.publish :record, data_hash - #end - else - @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) - end + if @m_mode == :async + #timeout(@m_timeout) do + data_hash = { + :qtype => :kt_outbound, + :ctype => type, + :v => 'v1', + :kt_api_key => @m_kt_api_key, + :kt_secret_key => @m_kt_secret_key, + :kt_call_back_host => @m_kt_host, + :kt_call_back_port => @m_kt_host_port, + :kt_url => @m_kt_url, + :arg_hash => arg_hash, + } + Kt::Queue::Task.publish :record, data_hash + #end + else + @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end - # New Relic tracking of API calls - begin - require "#{RAILS_ROOT}/vendor/plugins/rpm/init" - add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' - rescue - puts "Failed to add New Relic instrumentation to Kontagent." - end - # It's more secure to have 32 characters def gen_long_uuid() - CGI::Session.generate_unique_id('kontagent') - rescue - # Rails 2.3 - ActiveSupport::SecureRandom.hex(16) + CGI::Session.generate_unique_id('kontagent') end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end - if request_params.has_key? 'kt_t' - arg_hash['t'] = request_params[:kt_t] - end - if request_params.has_key? 'kt_st1' - arg_hash['st1'] = request_params[:kt_st1] - end - if request_params.has_key? 'kt_st2' - arg_hash['st2'] = request_params[:kt_st2] - end + + arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' + arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' + arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' + arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' + uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end - def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end - if template_id != nil - param_array[:kt_t] = template_id.to_s - end - - if subtype1 != nil - param_array[:kt_st1] = subtype1 - end - - if subtype2 != nil - param_array[:kt_st2] = subtype2 - end + param_array[:kt_t] = template_id.to_s if !template_id.nil? + param_array[:kt_st1] = subtype1 if !subtype1.nil? + param_array[:kt_st2] = subtype2 if !subtype2.nil? + param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index 173f548..8550409 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,143 +1,138 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 #require 'socket' require 'net/http' -#require 'timeout' +require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port + + if @m_host == "api.geo.kontagent.net" + @m_ip = fetch_ip() + else + @m_ip = host + end end + + def _fetch_ip_helper(host_name_str, port) + ip_lst = Socket.getaddrinfo(host_name_str, 'http') + ip_lst.sort_by{ rand } + selected_ip = nil + + ip_lst.each do |ip_info| + ip_str = ip_info[3] + socket = Socket.new(AF_INET, SOCK_STREAM, 0) + sockaddr = Socket.sockaddr_in(port, ip_str) + status = -1 + timeout(2) do + status = socket.connect(sockaddr) + end + if status == 0 + selected_ip = ip_str + break + end + end #loop + return selected_ip + end # _fetch_ip_helper + + def fetch_ip() + selected_ip = _fetch_ip_helper(@m_host, @m_port) + if selected_ip.nil? + selected_ip = _fetch_ip_helper("api.global.kontagent.net", 80) + end + + return selected_ip + end + public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end + # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) -# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) -# url_path = "http://"+@m_host+":"+@m_port.to_s+url_path -# uri = URI.parse(url_path) -# Net::HTTP.get(uri) socket = Socket.new(AF_INET, SOCK_STREAM, 0) - sockaddr = Socket.sockaddr_in(@m_port, @m_host) - + sockaddr = Socket.sockaddr_in(@m_port, @m_ip) + connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN connected = false - # puts "Errno::EISCONN!!" + puts "Errno::EISCONN!!" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" - buf << "Host:" + @m_host + "\r\n" + buf << "Host:" + @m_ip + ":" + @m_port.to_s + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected -# socket = nil - -# puts @m_host -# begin -# timeout(2) do -# #socket = TCPSocket::new(@m_host, 80) #uncomment this -# socket = TCPSocket::new(@m_host, @m_port) -# end -# rescue Timeout::Error -# puts "timeout!!!" -# return -# rescue -# puts "tcp error!!!!" -# return -# end - -# if socket != nil -# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) -# #puts "url_path: #{url_path}" #xxx - -# buf = "GET " + url_path + " HTTP/1.1\r\n" -# buf << "Host:" + @m_host + "\r\n" -# buf << "Content-type: application/x-www-form-urlencoded\r\n" -# buf << "Accept: */*\r\n" -# buf << "\r\n" -# buf << "\r\n" -# socket.write buf -# socket.close -# end - - # old code - # socket.write("GET " + url_path + " HTTP/1.1\r\n") - # socket.write("Host:" + @m_host + "\r\n") - # socket.write("Content-type: application/x-www-form-urlencoded\r\n") - # socket.write("Accept: */*\r\n") - # socket.write("\r\n") - # socket.write("\r\n") - # socket.close - #end end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test #comm = Kontagent::Kt_Comm.new('67.102.65.65') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'}) diff --git a/lib/kt/queue/processor.rb b/lib/kt/queue/processor.rb index 429a710..1cef858 100644 --- a/lib/kt/queue/processor.rb +++ b/lib/kt/queue/processor.rb @@ -1,84 +1,84 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 module Kt module Queue LOST_CONNECTION_ERROR_MESSAGES = [ "Server shutdown in progress", "Broken pipe", "Lost connection to MySQL server during query", "MySQL server has gone away" ] # An object not found proxy exception. This is used inside our generated getter methods # to rescue ActiveRecord::RecordNotFound class NotFound < Exception; end class Processor def options @task.options end # Takes a class name and returns and creates an accessor method and instance # variable for it. If the class responds to find (i.e. ActiveRecord objects), then # it tries to call it with the value of name_id extracted from the Task. # If not, it creates a new instaces of the class, sets an instance variable with that name # and returns it. def self.processes(name) name = name.to_s define_method(name) do ivar = instance_variable_get("@#{name}") return ivar unless ivar.blank? object = Object.const_get(name.camelize) value = if object.respond_to?(:find) begin object.find(@task.options["#{name}_id".intern]) # We provide automatic ActiveRecord::RecordNotFound protection because this method # useless without a correct instance of the model. rescue ActiveRecord::RecordNotFound => rnf raise Kt::NotFound, rnf.message end else Object.const_get(name.camelize).send('new') end instance_variable_set("@#{name}", value) value end end # Runs the process method defined in the Processor subclass (in app/processors). # Any error that is fatal should be rescued to avoid re-entry in to the queue. As a default, we rescue # ActiveRecord::RecordNotFound (record not found). # Subclasses of Processor should rescue any fatal errors specific to them in their own process method. def process!(task) @task = task tries = 0 begin process rescue ActiveRecord::StatementInvalid => sti lost_connection = false LOST_CONNECTION_ERROR_MESSAGES.each do |error| lost_connection = true if sti.message =~ /#{error}/ end if lost_connection && tries == 0 tries += 1 ActiveRecord::Base.connection.reconnect! retry end task.enqueue_with_error(sti) rescue Kt::Queue::NotFound => notfound rescue Exception => e task.enqueue_with_error(e) end end end end end diff --git a/lib/kt/queue/queue.rb b/lib/kt/queue/queue.rb index 2fb380e..9e434b1 100644 --- a/lib/kt/queue/queue.rb +++ b/lib/kt/queue/queue.rb @@ -1,183 +1,183 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'starling' module Kt module Queue class Queue attr_reader :connection # Max number of reconnection attempts to starling MAX_TRIES = 1 class << self def queue @queue ||= Queue.new end def enqueue(priority, message) queue.enqueue(priority, message) end def process! queue.process! end def stop! queue.stop! end # Statictics methods def count_permanently_failed queue.connection.sizeof("#{queue.config['canvas_page_name']}_p_0") end def count queue.connection.sizeof(:all).inject(0){|c, (k, v)| c+= v} end # Use this method to see what's in the queue def peek(priority, iterate = 1) messages = [] iterate.times do message = queue.connection.get("#{queue.config['canvas_page_name']}_p_#{priority}") enqueue(priority, message) messages << message end messages end # You can use this method to define an external Proc (usually a lambda) that # is sent a notification when a task fails more than the max allowed times. # The lambda is passed the Kt::Queue::Task object, and the last Exception object. # For example: # Kt::Queue::Queue.failure_notification_observer = lambda {|task, error| # Mailer.deliver_exception_mail(...) # } attr_accessor :failure_notification_observer end def initialize self.connect! end def enqueue(priority, message) if message[:action].blank? error = "Tried to queue a task with an empty action. The message being queued was: #{message.inspect}" Kt::Queue::Queue.log(error, true) end @current_message = message value_with_retries do @connection.set("#{config['canvas_page_name']}_p_#{priority}", message) end end def dequeue(priority) @current_message = nil value_with_retries do @connection.get("#{config['canvas_page_name']}_p_#{priority}") end end # Loads the config file def config @config ||= YAML.load_file("#{RAILS_ROOT}/config/kontagent.yml") end # Gets the next_item in the Queue def next_item result = nil 10.times do |i| result = dequeue(i+1) break unless result.blank? end result end def flush 10.times do |i| result = @connection.flush("#{config['canvas_page_name']}_p_#{i+1}") end end # The main loop. It goes like this: # 1. Calls process which: # * calls next_item (returns nil or a task from the queue) # * process returns false if next_item is nil # * process creates a new task and calls process! on it # 2. The loop continues def process! @running = true while @running result = process unless result puts "Waiting..." if RAILS_ENV == "development" GC.enable GC.start sleep 3 end sleep 1 end end def stop! @running = false end def self.log(message, force=false) RAILS_DEFAULT_LOGGER.send(force ? :error : :debug, message) end protected def connect! Kt::Queue::Queue.log "Connecting on #{config['queue_address']}, canvas_page_name: #{config['canvas_page_name']}" @connection = Starling.new(config['queue_address']) end # Gets an item from the queue if there is one, creates a task, and runs process! on it def process task = next_item Kt::Queue::Queue.log "Running #{task.inspect}..." task.blank? ? false : Kt::Queue::Task.from_message(task).process! end def value_with_retries(&block) tries = 0 result = nil begin result = yield rescue MemCache::MemCacheError => e Kt::Queue::Queue.log "Try ##{tries} - Starling Error: #{e.class} -> #{e}" connect! # If we can't connect to the server at all, we just put a line in the log file. # This can be parsed later to write back to the queue if desired if (tries += 1) > MAX_TRIES unless @current_message.blank? Kt::Queue::Queue.log("+++ #{Time.now.to_i} #{@current_message.inspect}", true) if Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(@current_message, e) end end return nil end retry end return result end end end end diff --git a/lib/kt/queue/task.rb b/lib/kt/queue/task.rb index e7d8370..58b186f 100644 --- a/lib/kt/queue/task.rb +++ b/lib/kt/queue/task.rb @@ -1,76 +1,76 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/queue/processor' require 'kt/kt_comm_layer' class RecordProcessor < Kt::Queue::Processor def process op = options qtype = op[:qtype] if qtype == :kt_outbound m_comm = Kt::KtComm.instance(op[:kt_call_back_host], op[:kt_call_back_port]) m_comm.api_call_method(op[:kt_url], op[:v], op[:kt_api_key], op[:kt_secret_key], op[:ctype], op[:arg_hash]) elsif qtype == :capture_user_data Kt::KtAnalytics.instance.send_user_data_impl(Marshal.load(op[:user])) end end end module Kt module Queue class Task MAX_ERRORS = 3 attr_reader :options def process! processor.new.process!(self) end # Puts a failed Task back in the Queue with the lowest priority. # If a task fails MAX_ERRORS times, it is put in Queue 0 which is never processed. def enqueue_with_error(e) @options[:failures] = @options[:failures].to_i + 1 @options[:errors] ||= [] @options[:priority] = (@options[:failures] < MAX_ERRORS) ? 10 : 0 Kt::Queue::Queue.enqueue(@options[:priority], @options.merge!({ :action => @action, :errors => @options[:errors] << {:class => e.class.to_s, :message => e.message} })) Kt::Queue::Queue.log("Action '#{@action}' failed #{@options[:failures]} time(s).") # Send failure notification if a notification observer is defined if @options[:priority] == 0 && Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(self, e) end end # Puts actions in the Queue. Priority defaults to 5 def self.publish(action, options={}) priority = options[:priority] || 5 options.merge!({:action => action}) Kt::Queue::Queue.enqueue(priority, options) end # Creates a Task from a message def self.from_message(message) action = message.delete :action Task.new(action, message) end def initialize(action, options = {}) @action = action @options = {:priority => 5}.merge(options) end protected # Infers a Processor's name from the action def processor Object.const_get(@action.to_s.camelize + 'Processor') end end end end diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 94663c2..e63aea9 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,183 +1,190 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'facebooker' -#require 'ruby-debug' +require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) - #controller.before_filter(:capture_user_data) + controller.before_filter(:store_user_id) + controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) - #controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) + controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) + end + + def set_ab_testing_page(campaign) + page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) + msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) + Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end + def store_user_id + $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? + return true + end + def capture_user_data - time(" capture user data") do - begin - user = session[:facebook_session].user - key = "KT_" + Facebooker.api_key + "_" + user.id.to_s - if cookies[key].blank? - Kt::KtAnalytics.instance.send_user_data(user) - end - cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks - rescue - # invalid session key. + begin + user = session[:facebook_session].user + key = "KT_" + Facebooker.api_key + "_" + user.id.to_s + if cookies[key].blank? + Kt::KtAnalytics.instance.send_user_data(user) end + cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks + rescue + # invalid session key. end - return true + return true end def handle_kontagent - unless App.current.nil? or App.current.theme.template.code == "snowball" - time("Handle kontagent") do - get_params = params - $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? - - # trace uninstall - if params.has_key? :fb_sig_uninstall - Kt::KtAnalytics.instance.save_app_removed(params) - return true - end + get_params = params + + # trace uninstall + if params.has_key? :fb_sig_uninstall + Kt::KtAnalytics.instance.save_app_removed(params) + return true + end - # track install - if params.has_key? :installed and params[:installed] == "1" - Kt::KtAnalytics.instance.save_app_added(params) - end + # track install + if params.has_key? :installed and params[:installed] == "1" + Kt::KtAnalytics.instance.save_app_added(params) + end - short_tag=nil - if params.has_key? :kt_type - # handle kontagent related parameters - case params[:kt_type] - when "ins" # invite sent - Kt::KtAnalytics.instance.save_invite_send(params) - when "in" # invite click - Kt::KtAnalytics.instance.save_invite_click(params) - when "nt" # notification click - Kt::KtAnalytics.instance.save_notification_click(params) - when "nte" # email notification - Kt::KtAnalytics.instance.save_notification_email_click(params) - when "fdp" - short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) - else + short_tag=nil + if params.has_key? :kt_type + # handle kontagent related parameters + case params[:kt_type] + when "ins" # invite sent + Kt::KtAnalytics.instance.save_invite_send(params) + when "in" # invite click + Kt::KtAnalytics.instance.save_invite_click(params) + when "nt" # notification click + Kt::KtAnalytics.instance.save_notification_click(params) + when "nte" # email notification + Kt::KtAnalytics.instance.save_notification_email_click(params) + when "fdp" + short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) + else - end - - # forward to the url without the kt_* params - f_url = get_stripped_kt_args_url(short_tag) - #puts "f_url \n\t #{f_url}" #xxx - redirect_to f_url - else - return true - end end + + # forward to the url without the kt_* params + f_url = get_stripped_kt_args_url(short_tag) + #puts "f_url \n\t #{f_url}" #xxx + redirect_to f_url + + else + return true end + end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index c802583..c11f69b 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,60 +1,107 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'cgi' module Kt module Rails module KontagentHelpers + def kt_get_page_text(campaign) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + return page_text + end + def kt_get_msg_text(campaign) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + return msg_text + end + + def kt_get_invite_post_link_vo(invite_post_link, campaign) + url = nil + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + + if session['invite_uuid'].nil? + url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, + uid, + campaign) + session['invite_uuid'] = uuid + else + url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, + uid, + session['invite_uuid'], + campaign) + session['invite_uuid'] = nil + end + return url + end + + def kt_get_invite_content_link_vo(invite_content_link, campaign) + url = nil + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + + if session['invite_uuid'].nil? + url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, + uid, + campaign) + session['invite_uuid'] = uuid + else + url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, + uid, + session['invite_uuid'], + campaign) + session['invite_uuid'] = nil + end + return url + end + def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - if session['invite_uuid'] == nil + if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - if session['invite_uuid'] == nil + if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) session['invite_uuid'] = nil end return url end def kt_track_page_view() uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end end end end diff --git a/lib/starling_ext.rb b/lib/starling_ext.rb index 6655041..2a41d03 100644 --- a/lib/starling_ext.rb +++ b/lib/starling_ext.rb @@ -1,7 +1,7 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 # An extension to the Starling class from Twitter's (www.twitter.com) starling (http://rubyforge.org/projects/starling) gem. class Starling def get(*args) super(*args) end end \ No newline at end of file
rmatei/kt
eb15bc7915b043f419df68d28cb66ed86ccbf5b2
Turning kontagent back on for dw
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index b6eca9e..94663c2 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,183 +1,183 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_analytics' require 'facebooker' #require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) #controller.before_filter(:capture_user_data) - #controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) + controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) #controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def capture_user_data time(" capture user data") do begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end end return true end def handle_kontagent unless App.current.nil? or App.current.theme.template.code == "snowball" time("Handle kontagent") do get_params = params $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
d0b90af7bcae5cf021afdb41b533261817eac4cd
formatting
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 484a4d2..b6eca9e 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,183 +1,183 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_analytics' require 'facebooker' #require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) #controller.before_filter(:capture_user_data) - # controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) - # controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) - end + #controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) + #controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) + end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def capture_user_data time(" capture user data") do begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end end return true end def handle_kontagent unless App.current.nil? or App.current.theme.template.code == "snowball" time("Handle kontagent") do get_params = params $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
caaf35d7f9cf9eadc09fefbd2110fcdb7fdeb673
fix for 2.3
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 84ebd49..a66602e 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,472 +1,475 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_comm_layer' require 'kt/queue/task' require 'digest/md5' #require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i end public def init(custom_conf = nil) init_from_conf(custom_conf) @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url, uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def send_user_data_impl(user) time("making API calls for Kontagent user data") do arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # # # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s # RAILS_DEFAULT_LOGGER.warn arg_hash.inspect # LOCAL end kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] if request_params['kt_t'] != nil arg_hash['t'] = request_params[:kt_t] end kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' if request_params[:kt_t] != nil arg_hash['t'] = request_params[:kt_t] end if request_params[:kt_st1] != nil arg_hash['st1'] = request_params[:kt_st1] end if request_params[:kt_st2] != nil arg_hash['st2'] = request_params[:kt_st2] end kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) time("sending Kontagent message (#{arg_hash.inspect})") do if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end end # New Relic tracking of API calls begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() - CGI::Session.generate_unique_id('kontagent') + CGI::Session.generate_unique_id('kontagent') + rescue + # Rails 2.3 + ActiveSupport::SecureRandom.hex(16) end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end if request_params.has_key? 'kt_t' arg_hash['t'] = request_params[:kt_t] end if request_params.has_key? 'kt_st1' arg_hash['st1'] = request_params[:kt_st1] end if request_params.has_key? 'kt_st2' arg_hash['st2'] = request_params[:kt_st2] end uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end if template_id != nil param_array[:kt_t] = template_id.to_s end if subtype1 != nil param_array[:kt_st1] = subtype1 end if subtype2 != nil param_array[:kt_st2] = subtype2 end return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
a879af21fb0288fe8ae17a0d69e2a2a51452dc0e
fixed kt to work w/ savvyapp
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 320345c..35c9c9d 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,183 +1,183 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_analytics' require 'facebooker' #require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) #controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def capture_user_data time(" capture user data") do begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end end return true end def handle_kontagent - unless App.current.theme.template.code == "snowball" + unless App.current.nil? or App.current.theme.template.code == "snowball" time("Handle kontagent") do get_params = params $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
11dd78cbb613d9f55a47e34d876ac66db6330493
take out whining
diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index 4fd292e..173f548 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,143 +1,143 @@ # Kontagent facebooker version 0.1.6 #require 'socket' require 'net/http' #require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port end public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) # url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) # url_path = "http://"+@m_host+":"+@m_port.to_s+url_path # uri = URI.parse(url_path) # Net::HTTP.get(uri) socket = Socket.new(AF_INET, SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(@m_port, @m_host) connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN connected = false - puts "Errno::EISCONN!!" + # puts "Errno::EISCONN!!" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" buf << "Host:" + @m_host + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected # socket = nil # puts @m_host # begin # timeout(2) do # #socket = TCPSocket::new(@m_host, 80) #uncomment this # socket = TCPSocket::new(@m_host, @m_port) # end # rescue Timeout::Error # puts "timeout!!!" # return # rescue # puts "tcp error!!!!" # return # end # if socket != nil # url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) # #puts "url_path: #{url_path}" #xxx # buf = "GET " + url_path + " HTTP/1.1\r\n" # buf << "Host:" + @m_host + "\r\n" # buf << "Content-type: application/x-www-form-urlencoded\r\n" # buf << "Accept: */*\r\n" # buf << "\r\n" # buf << "\r\n" # socket.write buf # socket.close # end # old code # socket.write("GET " + url_path + " HTTP/1.1\r\n") # socket.write("Host:" + @m_host + "\r\n") # socket.write("Content-type: application/x-www-form-urlencoded\r\n") # socket.write("Accept: */*\r\n") # socket.write("\r\n") # socket.write("\r\n") # socket.close #end end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test #comm = Kontagent::Kt_Comm.new('67.102.65.65') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'})
rmatei/kt
08f3f08f055926e5437a1b170fd37314b1ff3087
Took outbound_msg out for snowball
diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb index 4e28dd5..bb4263c 100644 --- a/lib/facebook/session.rb +++ b/lib/facebook/session.rb @@ -1,94 +1,94 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_analytics' module Facebooker class Session def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil) uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) r = send_notification_without_kontagent(user_ids, fbml, email_fbml) if !r.blank? arg_hash = { #'s' => @user.id.to_s, 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } if source_user.nil? arg_hash['s'] = 0.to_s else arg_hash['s'] = source_user.id.to_s end arg_hash['t'] = template_id.to_s unless template_id.nil? - Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) + Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) unless App.current.theme.template.code == "snowball" end end def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil) if fbml != nil uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, template_id, st1, st2) else uuid = Kt::KtAnalytics.instance.gen_long_uuid end r = send_email_without_kontagent(user_ids, subject, text, fbml) if !r.blank? arg_hash = { 's' => @user.id.to_s , 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } arg_hash['t'] = template_id.to_s unless template_id.nil? Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) end end def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil) if(data != nil) data.each_pair do |key,value | if key == :image uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, bundle_id, st1, st2) value[:href] = fbml data[key] = value # do we even need this line? elsif key == :flash elsif key == :mp3 Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) elsif key == :video else uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) data[key] = fbml end end end r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) if !r.blank? arg_hash = { 'pt' => 4, 's' => @user.id.to_s, 't' => bundle_id } - Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) + Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) unless App.current.theme.template.code == "snowball" end end alias_method_chain :send_notification, :kontagent alias_method_chain :send_email, :kontagent alias_method_chain :publish_user_action, :kontagent end end
rmatei/kt
c3efaef293ec9b645d8f2179dfd19b6b5be23755
adding new relic instrumentation
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 184ef00..84ebd49 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,464 +1,472 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_comm_layer' require 'kt/queue/task' require 'digest/md5' #require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i end public def init(custom_conf = nil) init_from_conf(custom_conf) @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url, uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def send_user_data_impl(user) time("making API calls for Kontagent user data") do arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # # # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s # RAILS_DEFAULT_LOGGER.warn arg_hash.inspect # LOCAL end kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] if request_params['kt_t'] != nil arg_hash['t'] = request_params[:kt_t] end kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' if request_params[:kt_t] != nil arg_hash['t'] = request_params[:kt_t] end if request_params[:kt_st1] != nil arg_hash['st1'] = request_params[:kt_st1] end if request_params[:kt_st2] != nil arg_hash['st2'] = request_params[:kt_st2] end kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) time("sending Kontagent message (#{arg_hash.inspect})") do if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end end + # New Relic tracking of API calls + begin + require "#{RAILS_ROOT}/vendor/plugins/rpm/init" + add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' + rescue + puts "Failed to add New Relic instrumentation to Kontagent." + end + # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end if request_params.has_key? 'kt_t' arg_hash['t'] = request_params[:kt_t] end if request_params.has_key? 'kt_st1' arg_hash['st1'] = request_params[:kt_st1] end if request_params.has_key? 'kt_st2' arg_hash['st2'] = request_params[:kt_st2] end uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end if template_id != nil param_array[:kt_t] = template_id.to_s end if subtype1 != nil param_array[:kt_st1] = subtype1 end if subtype2 != nil param_array[:kt_st2] = subtype2 end return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
62fe07fbe0b223bc7281296a5181cc1bd0791ca6
force revert to 0.1.6
diff --git a/init.rb b/init.rb index 9cc816c..e494bea 100644 --- a/init.rb +++ b/init.rb @@ -1,57 +1,57 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 puts "loading kt..." require 'facebook/session' require 'kt/rails/helpers' require 'facebooker/rails/publisher' require 'facebook/rails/publisher' #require 'facebooker/rails/controller' require 'facebook/rails/controller' require 'kt/rails/controller' config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") if config['mode'] == 'async' require 'starling' require 'starling_ext' require 'kt/queue/queue' require 'kt/queue/processor' require 'kt/queue/task' # Load app applicable Kontagent::Queue::Processor subclasses from app/processors Dir[RAILS_ROOT + '/app/processors/*.rb'].each do |file| require file end end module ::ActionController class Base def self.inherited_with_kt(subclass) inherited_without_kt(subclass) if subclass.to_s == "ApplicationController" subclass.class_eval do subclass.send(:include,Kt::Rails::Controller) end end end #def class << self alias_method_chain :inherited, :kt end end end ActionView::Base.send :include, Kt::Rails::KontagentHelpers diff --git a/install.rb b/install.rb index 906cff2..570c7f9 100644 --- a/install.rb +++ b/install.rb @@ -1,20 +1,20 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 # Install hook code here require 'fileutils' require 'rubygems' #require 'ruby-debug' #xxx if ARGV.size != 2 puts "Failure: you need to pass in the controller_name" else controller_name = ARGV[1] handle_iframe_html_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.html.erb") handle_iframe_fbml_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.fbml.erb") kontagent_yml_dst = File.join(RAILS_ROOT, "config", "kontagent.yml") puts "copying kontagent.yml.erb to #{kontagent_yml_dst}" FileUtils.cp( File.join(RAILS_ROOT, "vendor", "plugins", "kt", 'kontagent.yml.tpl'), kontagent_yml_dst ) unless File.exists?( kontagent_yml_dst ) end diff --git a/kontagent.yml.tpl b/kontagent.yml.tpl index 846c73c..4d2b5c5 100644 --- a/kontagent.yml.tpl +++ b/kontagent.yml.tpl @@ -1,131 +1,130 @@ # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false - ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb index fe5991d..e6a35ef 100644 --- a/lib/facebook/rails/controller.rb +++ b/lib/facebook/rails/controller.rb @@ -1,25 +1,25 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 require 'kt/kt_analytics' module Facebooker module Rails module Controller def application_is_not_installed_by_facebook_user_with_kontagent if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") redirect_to session[:facebook_session].install_url else local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") end end #application_is_not_installed_by_facebook_user_with_kontagent alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent end #module Controller end end diff --git a/lib/facebook/rails/publisher.rb b/lib/facebook/rails/publisher.rb index dee9cc1..150e15e 100644 --- a/lib/facebook/rails/publisher.rb +++ b/lib/facebook/rails/publisher.rb @@ -1,68 +1,62 @@ -# Kontagent facebooker version 0.2.0 - +# Kontagent facebooker version 0.1.6 module Facebooker module Rails class Publisher def template(arg) @template = arg end def subtype1(arg) @subtype1 = arg end def subtype2(arg) @subtype2 = arg end - def campaign(arg) - @campaign = arg - end def send_message_with_kontagent(method) @recipients = @recipients.is_a?(Array) ? @recipients : [@recipients] if from.nil? and @recipients.size==1 and ! announcement_notification?(from,_body) @from = @recipients.first end # notifications can # omit the from address raise InvalidSender.new("Sender must be a Facebooker::User") unless from.is_a?(Facebooker::User) || announcement_notification?(from,_body) case _body when Facebooker::Feed::TemplatizedAction,Facebooker::Feed::Action from.publish_action(_body) when Facebooker::Feed::Story @recipients.each {|r| r.publish_story(_body)} when Notification - (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, - @template, @subtype1, @subtype2, @campaign) + (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, @template, @subtype1, @subtype2) when Email from.session.send_email(@recipients, _body.title, _body.text, _body.fbml, @template, @subtype1, - @subtype2, - @campaign) + @subtype2) when Profile # If recipient and from aren't the same person, create a new user object using the # userid from recipient and the session from from if @from != @recipients.first @from = Facebooker::User.new(Facebooker::User.cast_to_facebook_id(@recipients.first),from.session) end from.set_profile_fbml(_body.profile, _body.mobile_profile, _body.profile_action, _body.profile_main) when Ref @from.session.server_cache.set_ref_handle(_body.handle,_body.fbml) when UserAction - @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general, @subtype1, @subtype2, @campaign) + @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general) else raise UnspecifiedBodyType.new("You must specify a valid send_as") end end alias_method_chain :send_message, :kontagent end end end diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb index b1568bd..4e28dd5 100644 --- a/lib/facebook/session.rb +++ b/lib/facebook/session.rb @@ -1,150 +1,94 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 require 'kt/kt_analytics' -require 'ruby-debug' module Facebooker class Session - def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) - - if !campaign.nil? - # ab testing - msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) - page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) - uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nt, nil, campaign, msg_id, page_id, msg_txt) - else - uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) - end + def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil) + uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) r = send_notification_without_kontagent(user_ids, fbml, email_fbml) if !r.blank? arg_hash = { + #'s' => @user.id.to_s, 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } if source_user.nil? arg_hash['s'] = 0.to_s else arg_hash['s'] = source_user.id.to_s end arg_hash['t'] = template_id.to_s unless template_id.nil? - if !campaign.nil? - arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) - arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) - arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) - else - arg_hash['st1'] = st1 - arg_hash['st2'] = st2 - arg_hash['st3'] = st3 - end - Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) end end - def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) - if !campaign.nil? - # ab testing - msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) - page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) - if fbml != nil - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nte, nil, campaign, msg_id, page_id, msg_txt) - else - uuid = Kt::KtAnalytics.instance.gen_long_uuid - end + def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil) + if fbml != nil + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, + template_id, st1, st2) else - if fbml != nil - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, template_id, st1, st2, st3) - else - uuid = Kt::KtAnalytics.instance.gen_long_uuid - end + uuid = Kt::KtAnalytics.instance.gen_long_uuid end r = send_email_without_kontagent(user_ids, subject, text, fbml) if !r.blank? arg_hash = { 's' => @user.id.to_s , 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } - arg_hash['t'] = template_id.to_s unless template_id.nil? - if !campaign.nil? - arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) - arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) - arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) - else - arg_hash['st1'] = st1 - arg_hash['st2'] = st2 - end Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) end end - # if st2 is set to m{d} and st3 is set to p{d}, we'll assume that it's using ab_testing data. - def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil, campaign=nil) - if !campaign.nil? - msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) - page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) - st1 = campaign - st2 = msg_id - st3 = page_id - end - + def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil) if(data != nil) data.each_pair do |key,value | if key == :image - if !campaign.nil? - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(value[:href], :fdp, - bundle_id, st1, st2, st3, campaign) - else - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, - bundle_id, st1, st2) - end + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, + bundle_id, st1, st2) value[:href] = fbml data[key] = value # do we even need this line? elsif key == :flash elsif key == :mp3 - #Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) + Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) elsif key == :video + else - if !campaign.nil? - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href_vo(value, :fdp, bundle_id, st1, st2, st3) - else - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) - end + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) data[key] = fbml end end end - data['KT_AB_MSG'] = msg_txt if !campaign.nil? - r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) - + if !r.blank? arg_hash = { 'pt' => 4, 's' => @user.id.to_s, 't' => bundle_id } Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) end end alias_method_chain :send_notification, :kontagent alias_method_chain :send_email, :kontagent alias_method_chain :publish_user_action, :kontagent end end diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 9684bdb..184ef00 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,573 +1,464 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 require 'kt/kt_comm_layer' -require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' -require 'ruby-debug' +#require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls - @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil - - attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr + + attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end - + if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i - - ##### possibly overriding ab_testing_host/port with some testing host port ##### - if app_config_map.has_key? 'ab_testing_host' - @m_ab_testing_host = app_config_map['ab_testing_host'] - elsif @config.has_key? 'ab_testing_host' - @m_ab_testing_host = @config['ab_testing_host'] - end - - if app_config_map.has_key? 'ab_testing_port' - @m_ab_testing_port = app_config_map['ab_testing_port'] - elsif @config.has_key? 'ab_testing_port' - @m_ab_testing_port = @config['ab_testing_port'] - end - - ##### the normal ab_testing_host/port ##### - if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? - if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' - @m_ab_testing_host = 'http://www.kontagent.com' - @m_ab_testing_port = 80 - end - end - end - - public - def format_kt_st1(st1_str) - return "aB_"+st1_str - end - - def format_kt_st2(st2_str) - return "m"+st2_str.to_s - end - - def format_kt_st3(st3_str) - return "p"+st3_str.to_s end - def init() - init_from_conf() + public + def init(custom_conf = nil) + init_from_conf(custom_conf) @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) - @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, - @m_ab_testing_host, - @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id + @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) - return url , uuid + return url, uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end - def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) - uuid = gen_long_uuid - url = get_invite_post_link_vo(post_link, uid, uuid, campaign) - return url , uuid - end - - def get_invite_post_link_vo(post_link, uid, uuid, campaign) - arg_hash = {} - arg_hash['kt_uid'] = uid - arg_hash['kt_ut'] = uuid - arg_hash['kt_type'] = 'ins' - arg_hash['kt_d'] = @@S_directed_val - - arg_hash['kt_st1'] = format_kt_st1(campaign) - msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) - arg_hash['kt_st2'] = format_kt_st2(msg_id) - page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) - arg_hash['kt_st3'] = format_kt_st3(page_id) - - r_url = append_kt_query_str(post_link, arg_hash.to_query) - return r_url - end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end - + def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end - def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) - uuid = gen_long_uuid - url = get_invite_post_link_vo(content_link, uid, uuid, campaign) - return url, uuid - end - - def get_invite_content_link_vo(content_link, uid, uuid, campaign) - arg_hash = {} - arg_hash['kt_uid'] = uid - arg_hash['kt_ut'] = uuid - arg_hash['kt_type'] = 'in' - arg_hash['kt_d'] = @@S_directed_val - - arg_hash['kt_st1'] = format_kt_st1(campaign) - msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) - arg_hash['kt_st2'] = format_kt_st2(msg_id) - page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) - arg_hash['kt_st3'] = format_kt_st3(page_id) - - r_url = append_kt_query_str(content_link, arg_hash.to_query) - return r_url - end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) - uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } - return uuid,input_txt end #gen_kt_comm_link - - def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) - uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, - format_kt_st1(campaign), - format_kt_st2(msg_id), - format_kt_st3(page_id)) - input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| - if $1.nil? - input_txt - else - append_kt_query_str($1, query_str) - end - } - input_txt = input_txt.gsub(@@KT_AB_MSG){|match| - msg_txt - } - return uuid, input_txt - end - def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) - uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href - def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) - uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, - format_kt_st1(campaign), - format_kt_st2(msg_id), - format_kt_st3(page_id)) - input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| - if $1.nil? - input_txt - else - append_kt_query_str($1, query_str) - end - } - return uuid, input_txt - end - def send_user_data_impl(user) - arg_hash = {} + time("making API calls for Kontagent user data") do + arg_hash = {} - if !user.birthday.blank? && user.birthday != '' - arg_hash['b'] = user.birthday - end - if !user.sex.blank? && user.sex != '' - arg_hash['g'] = user.sex - end - -# if !user.current_location.city.blank? &&user.current_location.city != '' -# arg_hash['ly'] = user.current_location.city -# end -# if !user.current_location.state.blank? && user.current_location.state != '' -# arg_hash['ls'] = user.current_location.state -# end -# if !user.current_location.country.blank? && user.current_location.country != '' -# arg_hash['lc'] = user.current_location.country -# end -# if !user.current_location.zip.blank? && user.current_location.zip != '' -# arg_hash['lp'] = user.current_location.zip -# end - - -# if !user.hometown_location.city.blank? &&user.hometown_location.city != '' -# arg_hash['ly'] = user.hometown_location.city -# end -# if !user.hometown_location.state.blank? && user.hometown_location.state != '' -# arg_hash['ls'] = user.hometown_location.state -# end -# if !user.hometown_location.country.blank? && user.hometown_location.country != '' -# arg_hash['lc'] = user.hometown_location.country -# end -# if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' -# arg_hash['lp'] = user.hometown_location.zip -# end + if !user.birthday.blank? && user.birthday != '' + arg_hash['b'] = user.birthday + end + if !user.sex.blank? && user.sex != '' + arg_hash['g'] = user.sex + end - arg_hash['f'] = user.friends.size.to_s + # if !user.current_location.city.blank? &&user.current_location.city != '' + # arg_hash['ly'] = user.current_location.city + # end + # if !user.current_location.state.blank? && user.current_location.state != '' + # arg_hash['ls'] = user.current_location.state + # end + # if !user.current_location.country.blank? && user.current_location.country != '' + # arg_hash['lc'] = user.current_location.country + # end + # if !user.current_location.zip.blank? && user.current_location.zip != '' + # arg_hash['lp'] = user.current_location.zip + # end + # + # + # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' + # arg_hash['ly'] = user.hometown_location.city + # end + # if !user.hometown_location.state.blank? && user.hometown_location.state != '' + # arg_hash['ls'] = user.hometown_location.state + # end + # if !user.hometown_location.country.blank? && user.hometown_location.country != '' + # arg_hash['lc'] = user.hometown_location.country + # end + # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' + # arg_hash['lp'] = user.hometown_location.zip + # end + + arg_hash['f'] = user.friends.size.to_s + # RAILS_DEFAULT_LOGGER.warn arg_hash.inspect # LOCAL + end kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] - - arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? - arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? - arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? - arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? - + if request_params['kt_t'] != nil + arg_hash['t'] = request_params[:kt_t] + end kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' - arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? - arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? - arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? - arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? - + if request_params[:kt_t] != nil + arg_hash['t'] = request_params[:kt_t] + end + if request_params[:kt_st1] != nil + arg_hash['st1'] = request_params[:kt_st1] + end + if request_params[:kt_st2] != nil + arg_hash['st2'] = request_params[:kt_st2] + end kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil - arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) - if @m_mode == :async - #timeout(@m_timeout) do - data_hash = { - :qtype => :kt_outbound, - :ctype => type, - :v => 'v1', - :kt_api_key => @m_kt_api_key, - :kt_secret_key => @m_kt_secret_key, - :kt_call_back_host => @m_kt_host, - :kt_call_back_port => @m_kt_host_port, - :kt_url => @m_kt_url, - :arg_hash => arg_hash, - } - Kt::Queue::Task.publish :record, data_hash - #end - else - @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) + time("sending Kontagent message (#{arg_hash.inspect})") do + if @m_mode == :async + #timeout(@m_timeout) do + data_hash = { + :qtype => :kt_outbound, + :ctype => type, + :v => 'v1', + :kt_api_key => @m_kt_api_key, + :kt_secret_key => @m_kt_secret_key, + :kt_call_back_host => @m_kt_host, + :kt_call_back_port => @m_kt_host_port, + :kt_url => @m_kt_url, + :arg_hash => arg_hash, + } + Kt::Queue::Task.publish :record, data_hash + #end + else + @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) + end end end - # New Relic tracking of API calls - begin - require "#{RAILS_ROOT}/vendor/plugins/rpm/init" - add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' - rescue - puts "Failed to add New Relic instrumentation to Kontagent." - end - # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end - - arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' - arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' - arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' - arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' - + if request_params.has_key? 'kt_t' + arg_hash['t'] = request_params[:kt_t] + end + if request_params.has_key? 'kt_st1' + arg_hash['st1'] = request_params[:kt_st1] + end + if request_params.has_key? 'kt_st2' + arg_hash['st2'] = request_params[:kt_st2] + end uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end - def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) + def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end - param_array[:kt_t] = template_id.to_s if !template_id.nil? - param_array[:kt_st1] = subtype1 if !subtype1.nil? - param_array[:kt_st2] = subtype2 if !subtype2.nil? - param_array[:kt_st3] = subtype3 if !subtype3.nil? + if template_id != nil + param_array[:kt_t] = template_id.to_s + end + + if subtype1 != nil + param_array[:kt_st1] = subtype1 + end + + if subtype2 != nil + param_array[:kt_st2] = subtype2 + end return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index 8550409..4fd292e 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,138 +1,143 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 #require 'socket' require 'net/http' -require 'timeout' +#require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port - - if @m_host == "api.geo.kontagent.net" - @m_ip = fetch_ip() - else - @m_ip = host - end end - - def _fetch_ip_helper(host_name_str, port) - ip_lst = Socket.getaddrinfo(host_name_str, 'http') - ip_lst.sort_by{ rand } - selected_ip = nil - - ip_lst.each do |ip_info| - ip_str = ip_info[3] - socket = Socket.new(AF_INET, SOCK_STREAM, 0) - sockaddr = Socket.sockaddr_in(port, ip_str) - status = -1 - timeout(2) do - status = socket.connect(sockaddr) - end - if status == 0 - selected_ip = ip_str - break - end - end #loop - return selected_ip - end # _fetch_ip_helper - - def fetch_ip() - selected_ip = _fetch_ip_helper(@m_host, @m_port) - if selected_ip.nil? - selected_ip = _fetch_ip_helper("api.global.kontagent.net", 80) - end - - return selected_ip - end - public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end - # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) +# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) +# url_path = "http://"+@m_host+":"+@m_port.to_s+url_path +# uri = URI.parse(url_path) +# Net::HTTP.get(uri) socket = Socket.new(AF_INET, SOCK_STREAM, 0) - sockaddr = Socket.sockaddr_in(@m_port, @m_ip) - + sockaddr = Socket.sockaddr_in(@m_port, @m_host) + connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN connected = false puts "Errno::EISCONN!!" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" - buf << "Host:" + @m_ip + ":" + @m_port.to_s + "\r\n" + buf << "Host:" + @m_host + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected +# socket = nil + +# puts @m_host +# begin +# timeout(2) do +# #socket = TCPSocket::new(@m_host, 80) #uncomment this +# socket = TCPSocket::new(@m_host, @m_port) +# end +# rescue Timeout::Error +# puts "timeout!!!" +# return +# rescue +# puts "tcp error!!!!" +# return +# end + +# if socket != nil +# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) +# #puts "url_path: #{url_path}" #xxx + +# buf = "GET " + url_path + " HTTP/1.1\r\n" +# buf << "Host:" + @m_host + "\r\n" +# buf << "Content-type: application/x-www-form-urlencoded\r\n" +# buf << "Accept: */*\r\n" +# buf << "\r\n" +# buf << "\r\n" +# socket.write buf +# socket.close +# end + + # old code + # socket.write("GET " + url_path + " HTTP/1.1\r\n") + # socket.write("Host:" + @m_host + "\r\n") + # socket.write("Content-type: application/x-www-form-urlencoded\r\n") + # socket.write("Accept: */*\r\n") + # socket.write("\r\n") + # socket.write("\r\n") + # socket.close + #end end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test #comm = Kontagent::Kt_Comm.new('67.102.65.65') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'}) diff --git a/lib/kt/queue/processor.rb b/lib/kt/queue/processor.rb index 1cef858..429a710 100644 --- a/lib/kt/queue/processor.rb +++ b/lib/kt/queue/processor.rb @@ -1,84 +1,84 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 module Kt module Queue LOST_CONNECTION_ERROR_MESSAGES = [ "Server shutdown in progress", "Broken pipe", "Lost connection to MySQL server during query", "MySQL server has gone away" ] # An object not found proxy exception. This is used inside our generated getter methods # to rescue ActiveRecord::RecordNotFound class NotFound < Exception; end class Processor def options @task.options end # Takes a class name and returns and creates an accessor method and instance # variable for it. If the class responds to find (i.e. ActiveRecord objects), then # it tries to call it with the value of name_id extracted from the Task. # If not, it creates a new instaces of the class, sets an instance variable with that name # and returns it. def self.processes(name) name = name.to_s define_method(name) do ivar = instance_variable_get("@#{name}") return ivar unless ivar.blank? object = Object.const_get(name.camelize) value = if object.respond_to?(:find) begin object.find(@task.options["#{name}_id".intern]) # We provide automatic ActiveRecord::RecordNotFound protection because this method # useless without a correct instance of the model. rescue ActiveRecord::RecordNotFound => rnf raise Kt::NotFound, rnf.message end else Object.const_get(name.camelize).send('new') end instance_variable_set("@#{name}", value) value end end # Runs the process method defined in the Processor subclass (in app/processors). # Any error that is fatal should be rescued to avoid re-entry in to the queue. As a default, we rescue # ActiveRecord::RecordNotFound (record not found). # Subclasses of Processor should rescue any fatal errors specific to them in their own process method. def process!(task) @task = task tries = 0 begin process rescue ActiveRecord::StatementInvalid => sti lost_connection = false LOST_CONNECTION_ERROR_MESSAGES.each do |error| lost_connection = true if sti.message =~ /#{error}/ end if lost_connection && tries == 0 tries += 1 ActiveRecord::Base.connection.reconnect! retry end task.enqueue_with_error(sti) rescue Kt::Queue::NotFound => notfound rescue Exception => e task.enqueue_with_error(e) end end end end end diff --git a/lib/kt/queue/queue.rb b/lib/kt/queue/queue.rb index 9e434b1..2fb380e 100644 --- a/lib/kt/queue/queue.rb +++ b/lib/kt/queue/queue.rb @@ -1,183 +1,183 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 require 'starling' module Kt module Queue class Queue attr_reader :connection # Max number of reconnection attempts to starling MAX_TRIES = 1 class << self def queue @queue ||= Queue.new end def enqueue(priority, message) queue.enqueue(priority, message) end def process! queue.process! end def stop! queue.stop! end # Statictics methods def count_permanently_failed queue.connection.sizeof("#{queue.config['canvas_page_name']}_p_0") end def count queue.connection.sizeof(:all).inject(0){|c, (k, v)| c+= v} end # Use this method to see what's in the queue def peek(priority, iterate = 1) messages = [] iterate.times do message = queue.connection.get("#{queue.config['canvas_page_name']}_p_#{priority}") enqueue(priority, message) messages << message end messages end # You can use this method to define an external Proc (usually a lambda) that # is sent a notification when a task fails more than the max allowed times. # The lambda is passed the Kt::Queue::Task object, and the last Exception object. # For example: # Kt::Queue::Queue.failure_notification_observer = lambda {|task, error| # Mailer.deliver_exception_mail(...) # } attr_accessor :failure_notification_observer end def initialize self.connect! end def enqueue(priority, message) if message[:action].blank? error = "Tried to queue a task with an empty action. The message being queued was: #{message.inspect}" Kt::Queue::Queue.log(error, true) end @current_message = message value_with_retries do @connection.set("#{config['canvas_page_name']}_p_#{priority}", message) end end def dequeue(priority) @current_message = nil value_with_retries do @connection.get("#{config['canvas_page_name']}_p_#{priority}") end end # Loads the config file def config @config ||= YAML.load_file("#{RAILS_ROOT}/config/kontagent.yml") end # Gets the next_item in the Queue def next_item result = nil 10.times do |i| result = dequeue(i+1) break unless result.blank? end result end def flush 10.times do |i| result = @connection.flush("#{config['canvas_page_name']}_p_#{i+1}") end end # The main loop. It goes like this: # 1. Calls process which: # * calls next_item (returns nil or a task from the queue) # * process returns false if next_item is nil # * process creates a new task and calls process! on it # 2. The loop continues def process! @running = true while @running result = process unless result puts "Waiting..." if RAILS_ENV == "development" GC.enable GC.start sleep 3 end sleep 1 end end def stop! @running = false end def self.log(message, force=false) RAILS_DEFAULT_LOGGER.send(force ? :error : :debug, message) end protected def connect! Kt::Queue::Queue.log "Connecting on #{config['queue_address']}, canvas_page_name: #{config['canvas_page_name']}" @connection = Starling.new(config['queue_address']) end # Gets an item from the queue if there is one, creates a task, and runs process! on it def process task = next_item Kt::Queue::Queue.log "Running #{task.inspect}..." task.blank? ? false : Kt::Queue::Task.from_message(task).process! end def value_with_retries(&block) tries = 0 result = nil begin result = yield rescue MemCache::MemCacheError => e Kt::Queue::Queue.log "Try ##{tries} - Starling Error: #{e.class} -> #{e}" connect! # If we can't connect to the server at all, we just put a line in the log file. # This can be parsed later to write back to the queue if desired if (tries += 1) > MAX_TRIES unless @current_message.blank? Kt::Queue::Queue.log("+++ #{Time.now.to_i} #{@current_message.inspect}", true) if Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(@current_message, e) end end return nil end retry end return result end end end end diff --git a/lib/kt/queue/task.rb b/lib/kt/queue/task.rb index 58b186f..e7d8370 100644 --- a/lib/kt/queue/task.rb +++ b/lib/kt/queue/task.rb @@ -1,76 +1,76 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 require 'kt/queue/processor' require 'kt/kt_comm_layer' class RecordProcessor < Kt::Queue::Processor def process op = options qtype = op[:qtype] if qtype == :kt_outbound m_comm = Kt::KtComm.instance(op[:kt_call_back_host], op[:kt_call_back_port]) m_comm.api_call_method(op[:kt_url], op[:v], op[:kt_api_key], op[:kt_secret_key], op[:ctype], op[:arg_hash]) elsif qtype == :capture_user_data Kt::KtAnalytics.instance.send_user_data_impl(Marshal.load(op[:user])) end end end module Kt module Queue class Task MAX_ERRORS = 3 attr_reader :options def process! processor.new.process!(self) end # Puts a failed Task back in the Queue with the lowest priority. # If a task fails MAX_ERRORS times, it is put in Queue 0 which is never processed. def enqueue_with_error(e) @options[:failures] = @options[:failures].to_i + 1 @options[:errors] ||= [] @options[:priority] = (@options[:failures] < MAX_ERRORS) ? 10 : 0 Kt::Queue::Queue.enqueue(@options[:priority], @options.merge!({ :action => @action, :errors => @options[:errors] << {:class => e.class.to_s, :message => e.message} })) Kt::Queue::Queue.log("Action '#{@action}' failed #{@options[:failures]} time(s).") # Send failure notification if a notification observer is defined if @options[:priority] == 0 && Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(self, e) end end # Puts actions in the Queue. Priority defaults to 5 def self.publish(action, options={}) priority = options[:priority] || 5 options.merge!({:action => action}) Kt::Queue::Queue.enqueue(priority, options) end # Creates a Task from a message def self.from_message(message) action = message.delete :action Task.new(action, message) end def initialize(action, options = {}) @action = action @options = {:priority => 5}.merge(options) end protected # Infers a Processor's name from the action def processor Object.const_get(@action.to_s.camelize + 'Processor') end end end end diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index bac354e..320345c 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,196 +1,183 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 require 'kt/kt_analytics' require 'facebooker' -require 'ruby-debug' +#require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) - controller.before_filter(:store_user_id) - controller.before_filter(:capture_user_data) + #controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end - def set_ab_testing_page(campaign) - page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) - msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) - Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) - end - # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end - def store_user_id - $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? - return true - end - def capture_user_data - begin - user = session[:facebook_session].user - key = "KT_" + Facebooker.api_key + "_" + user.id.to_s - if cookies[key].blank? - Kt::KtAnalytics.instance.send_user_data(user) + time(" capture user data") do + begin + user = session[:facebook_session].user + key = "KT_" + Facebooker.api_key + "_" + user.id.to_s + if cookies[key].blank? + Kt::KtAnalytics.instance.send_user_data(user) + end + cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks + rescue + # invalid session key. end - cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks - rescue - # invalid session key. end - return true + return true end def handle_kontagent - get_params = params - - # trace uninstall - if params.has_key? :fb_sig_uninstall - Kt::KtAnalytics.instance.save_app_removed(params) - return true - end + unless App.current.theme.template.code == "snowball" + time("Handle kontagent") do + get_params = params + $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? - # track install - if params.has_key? :installed and params[:installed] == "1" - Kt::KtAnalytics.instance.save_app_added(params) - end + # trace uninstall + if params.has_key? :fb_sig_uninstall + Kt::KtAnalytics.instance.save_app_removed(params) + return true + end + + # track install + if params.has_key? :installed and params[:installed] == "1" + Kt::KtAnalytics.instance.save_app_added(params) + end - short_tag=nil - if params.has_key? :kt_type - # handle kontagent related parameters - case params[:kt_type] - when "ins" # invite sent - Kt::KtAnalytics.instance.save_invite_send(params) - when "in" # invite click - Kt::KtAnalytics.instance.save_invite_click(params) - when "nt" # notification click - Kt::KtAnalytics.instance.save_notification_click(params) - when "nte" # email notification - Kt::KtAnalytics.instance.save_notification_email_click(params) - when "fdp" - short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) - else + short_tag=nil + if params.has_key? :kt_type + # handle kontagent related parameters + case params[:kt_type] + when "ins" # invite sent + Kt::KtAnalytics.instance.save_invite_send(params) + when "in" # invite click + Kt::KtAnalytics.instance.save_invite_click(params) + when "nt" # notification click + Kt::KtAnalytics.instance.save_notification_click(params) + when "nte" # email notification + Kt::KtAnalytics.instance.save_notification_email_click(params) + when "fdp" + short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) + else - end + end - # forward to the url without the kt_* params - f_url = get_stripped_kt_args_url(short_tag) - #puts "f_url \n\t #{f_url}" #xxx - redirect_to f_url - - else - return true + # forward to the url without the kt_* params + f_url = get_stripped_kt_args_url(short_tag) + #puts "f_url \n\t #{f_url}" #xxx + redirect_to f_url + else + return true + end + end end - end # handle_kontagent - - - # New Relic tracking of API calls - # require "#{RAILS_ROOT}/vendor/plugins/rpm/lib/new_relic/agent/method_tracer" - # add_method_tracer :capture_user_data, 'Custom/Kontagent/CaptureUserData' - # add_method_tracer :handle_kontagent, 'Custom/Kontagent/HandleKontagent' - + private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index c11f69b..c802583 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,107 +1,60 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 require 'kt/kt_analytics' require 'cgi' module Kt module Rails module KontagentHelpers - def kt_get_page_text(campaign) - page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) - return page_text - end - def kt_get_msg_text(campaign) - msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) - return msg_text - end - - def kt_get_invite_post_link_vo(invite_post_link, campaign) - url = nil - uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - - if session['invite_uuid'].nil? - url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, - uid, - campaign) - session['invite_uuid'] = uuid - else - url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, - uid, - session['invite_uuid'], - campaign) - session['invite_uuid'] = nil - end - return url - end - - def kt_get_invite_content_link_vo(invite_content_link, campaign) - url = nil - uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - - if session['invite_uuid'].nil? - url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, - uid, - campaign) - session['invite_uuid'] = uuid - else - url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, - uid, - session['invite_uuid'], - campaign) - session['invite_uuid'] = nil - end - return url - end - def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - if session['invite_uuid'].nil? + if session['invite_uuid'] == nil url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - if session['invite_uuid'].nil? + if session['invite_uuid'] == nil url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) session['invite_uuid'] = nil end return url end def kt_track_page_view() uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end end end end diff --git a/lib/starling_ext.rb b/lib/starling_ext.rb index 2a41d03..6655041 100644 --- a/lib/starling_ext.rb +++ b/lib/starling_ext.rb @@ -1,7 +1,7 @@ -# Kontagent facebooker version 0.2.0 +# Kontagent facebooker version 0.1.6 # An extension to the Starling class from Twitter's (www.twitter.com) starling (http://rubyforge.org/projects/starling) gem. class Starling def get(*args) super(*args) end end \ No newline at end of file
rmatei/kt
051cec5a20d5bf1d78e6587e75709b923d86ac11
adding New Relic instrumentation
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 184ef00..84ebd49 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,464 +1,472 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_comm_layer' require 'kt/queue/task' require 'digest/md5' #require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i end public def init(custom_conf = nil) init_from_conf(custom_conf) @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url, uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def send_user_data_impl(user) time("making API calls for Kontagent user data") do arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # # # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s # RAILS_DEFAULT_LOGGER.warn arg_hash.inspect # LOCAL end kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] if request_params['kt_t'] != nil arg_hash['t'] = request_params[:kt_t] end kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' if request_params[:kt_t] != nil arg_hash['t'] = request_params[:kt_t] end if request_params[:kt_st1] != nil arg_hash['st1'] = request_params[:kt_st1] end if request_params[:kt_st2] != nil arg_hash['st2'] = request_params[:kt_st2] end kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) time("sending Kontagent message (#{arg_hash.inspect})") do if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end end + # New Relic tracking of API calls + begin + require "#{RAILS_ROOT}/vendor/plugins/rpm/init" + add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/kt_outbound_msg' + rescue + puts "Failed to add New Relic instrumentation to Kontagent." + end + # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end if request_params.has_key? 'kt_t' arg_hash['t'] = request_params[:kt_t] end if request_params.has_key? 'kt_st1' arg_hash['st1'] = request_params[:kt_st1] end if request_params.has_key? 'kt_st2' arg_hash['st2'] = request_params[:kt_st2] end uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end if template_id != nil param_array[:kt_t] = template_id.to_s end if subtype1 != nil param_array[:kt_st1] = subtype1 end if subtype2 != nil param_array[:kt_st2] = subtype2 end return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
a62817552051823364711eac5dcc4669ba3cbc86
fixing instrumentation of outbound calls
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 94605ec..c2f03c0 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,472 +1,472 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_comm_layer' require 'kt/queue/task' require 'digest/md5' #require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i end public def init(custom_conf = nil) init_from_conf(custom_conf) @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url, uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def send_user_data_impl(user) time("making API calls for Kontagent user data") do arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # # # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s # RAILS_DEFAULT_LOGGER.warn arg_hash.inspect # LOCAL end kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] if request_params['kt_t'] != nil arg_hash['t'] = request_params[:kt_t] end kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' if request_params[:kt_t] != nil arg_hash['t'] = request_params[:kt_t] end if request_params[:kt_st1] != nil arg_hash['st1'] = request_params[:kt_st1] end if request_params[:kt_st2] != nil arg_hash['st2'] = request_params[:kt_st2] end kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) time("sending Kontagent message (#{arg_hash.inspect})") do if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end end # New Relic tracking of API calls begin require "#{RAILS_ROOT}/vendor/plugins/rpm/init" - add_method_tracer :post, 'Custom/Kontagent/OutboundMessage' + add_method_tracer :kt_outbound_msg, 'Custom/Kontagent/OutboundMessage' rescue puts "Failed to add New Relic instrumentation to Kontagent." end # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end if request_params.has_key? 'kt_t' arg_hash['t'] = request_params[:kt_t] end if request_params.has_key? 'kt_st1' arg_hash['st1'] = request_params[:kt_st1] end if request_params.has_key? 'kt_st2' arg_hash['st2'] = request_params[:kt_st2] end uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end if template_id != nil param_array[:kt_t] = template_id.to_s end if subtype1 != nil param_array[:kt_st1] = subtype1 end if subtype2 != nil param_array[:kt_st2] = subtype2 end return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
d34a9b807ad7605997294f1694e351fde57136ce
adding new relic tracking
diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 184ef00..94605ec 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,464 +1,472 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_comm_layer' require 'kt/queue/task' require 'digest/md5' #require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i end public def init(custom_conf = nil) init_from_conf(custom_conf) @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) return url, uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } return uuid,input_txt end #gen_kt_comm_link def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href def send_user_data_impl(user) time("making API calls for Kontagent user data") do arg_hash = {} if !user.birthday.blank? && user.birthday != '' arg_hash['b'] = user.birthday end if !user.sex.blank? && user.sex != '' arg_hash['g'] = user.sex end # if !user.current_location.city.blank? &&user.current_location.city != '' # arg_hash['ly'] = user.current_location.city # end # if !user.current_location.state.blank? && user.current_location.state != '' # arg_hash['ls'] = user.current_location.state # end # if !user.current_location.country.blank? && user.current_location.country != '' # arg_hash['lc'] = user.current_location.country # end # if !user.current_location.zip.blank? && user.current_location.zip != '' # arg_hash['lp'] = user.current_location.zip # end # # # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' # arg_hash['ly'] = user.hometown_location.city # end # if !user.hometown_location.state.blank? && user.hometown_location.state != '' # arg_hash['ls'] = user.hometown_location.state # end # if !user.hometown_location.country.blank? && user.hometown_location.country != '' # arg_hash['lc'] = user.hometown_location.country # end # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' # arg_hash['lp'] = user.hometown_location.zip # end arg_hash['f'] = user.friends.size.to_s # RAILS_DEFAULT_LOGGER.warn arg_hash.inspect # LOCAL end kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] if request_params['kt_t'] != nil arg_hash['t'] = request_params[:kt_t] end kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' if request_params[:kt_t] != nil arg_hash['t'] = request_params[:kt_t] end if request_params[:kt_st1] != nil arg_hash['st1'] = request_params[:kt_st1] end if request_params[:kt_st2] != nil arg_hash['st2'] = request_params[:kt_st2] end kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) time("sending Kontagent message (#{arg_hash.inspect})") do if @m_mode == :async #timeout(@m_timeout) do data_hash = { :qtype => :kt_outbound, :ctype => type, :v => 'v1', :kt_api_key => @m_kt_api_key, :kt_secret_key => @m_kt_secret_key, :kt_call_back_host => @m_kt_host, :kt_call_back_port => @m_kt_host_port, :kt_url => @m_kt_url, :arg_hash => arg_hash, } Kt::Queue::Task.publish :record, data_hash #end else @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end end + # New Relic tracking of API calls + begin + require "#{RAILS_ROOT}/vendor/plugins/rpm/init" + add_method_tracer :post, 'Custom/Kontagent/OutboundMessage' + rescue + puts "Failed to add New Relic instrumentation to Kontagent." + end + # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end if request_params.has_key? 'kt_t' arg_hash['t'] = request_params[:kt_t] end if request_params.has_key? 'kt_st1' arg_hash['st1'] = request_params[:kt_st1] end if request_params.has_key? 'kt_st2' arg_hash['st2'] = request_params[:kt_st2] end uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end if template_id != nil param_array[:kt_t] = template_id.to_s end if subtype1 != nil param_array[:kt_st1] = subtype1 end if subtype2 != nil param_array[:kt_st2] = subtype2 end return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule
rmatei/kt
817ebb2993e9052b688fc51fdf174a9a8dbb3b98
take out NR method tracer
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index f10f010..bac354e 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,194 +1,196 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end - # New Relic tracking of API calls - add_method_tracer :capture_user_data, 'Custom/Kontagent/CaptureUserData' - add_method_tracer :handle_kontagent, 'Custom/Kontagent/HandleKontagent' - def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end # handle_kontagent - + + + # New Relic tracking of API calls + # require "#{RAILS_ROOT}/vendor/plugins/rpm/lib/new_relic/agent/method_tracer" + # add_method_tracer :capture_user_data, 'Custom/Kontagent/CaptureUserData' + # add_method_tracer :handle_kontagent, 'Custom/Kontagent/HandleKontagent' + private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
283aa1e1f91a05eea7b91729949dad9a11c632ac
adding New Relic instrumentation
diff --git a/lib/kt/kt_ab_testing.rb b/lib/kt/kt_ab_testing.rb new file mode 100644 index 0000000..f95cd61 --- /dev/null +++ b/lib/kt/kt_ab_testing.rb @@ -0,0 +1,185 @@ +require 'rubygems' #xxx +require 'memcache' +require 'net/http' +require 'uri' +require 'json' +require 'ruby-debug' + +module Kt + class AB_Testing_Manager + + @@URL_PREFIX = "/abtest/campaign_info"; + + public + def initialize(kt_api_key, kt_secret_key, + kt_ab_backend_host, kt_ab_backend_port) + @m_backend_api_key = kt_api_key + @m_backend_secret_key = kt_secret_key + + @m_ab_backend_host = kt_ab_backend_host + @m_ab_backend_port = kt_ab_backend_port + + if @m_ab_backend_port != 80 + @m_ab_backend = @m_ab_backend_host + ":" + @m_ab_backend_port.to_s + else + @m_ab_backend = @m_ab_backend_host + end + + @m_memcached_server = MemCache.new '127.0.0.1' + @m_selected_msg_page_pair_dict = {} + end + + private + def fetch_ab_testing_data(campaign, force=false) + begin + url_str = @m_ab_backend + @@URL_PREFIX + "/" + @m_backend_api_key + "/" + campaign + "/" + if force == true + url_str += "?f=1" + end + + url = URI.parse(url_str) + req = Net::HTTP::Get.new(url.path+"?"+url.query) + res = Net::HTTP.start(url.host, url.port) {|http| + http.request(req) + } + json_obj = JSON.parse(res.body) + + if json_obj["changed"] == true + msg_lst = json_obj["messages"] + msg_weight_array = [] + curr_idx = 0 + + # process message list + msg_lst.each do |m| + w = m[1] + w.times { msg_weight_array << curr_idx } + curr_idx += 1 + end + + # process page list + page_lst = json_obj['pages'] + page_weight_array = [] + curr_idx = 0 + page_lst.each do |p| + w = p[1] + w.times { page_weight_array << curr_idx } + curr_idx += 1 + end + + store_dict = {} + store_dict['json'] = json_obj + store_dict['msg_weight'] = msg_weight_array + store_dict['page_weight'] = page_weight_array + + r = store_dict + @m_memcached_server.set( gen_memcache_key(campaign), Marshal.dump(r), 0) + @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) + else + # no change + @m_memcached_server.set( gen_memcache_fake_key(campaign), 1, 300 ) + end + + rescue Errno::ECONNREFUSED + # TODO fall back on some default value + end + + + return r + end + + private + def get_ab_helper(campaign) + fake_key_is_valid = @m_memcached_server.get( gen_memcache_fake_key(campaign) ) + if fake_key_is_valid.nil? + # The real key should have a valid json object. + # If not, invoke fetch_ab_testin_data with force = true + serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) + if serialized_campaign_str.nil? + r = fetch_ab_testing_data(campaign, true) # force it + else + r = fetch_ab_testing_data(campaign) + end + else + # Likewise, the real key should have a valid json object. + # If not, invoke fetch_ab_testin_data with force = true + serialized_campaign_str = @m_memcached_server.get( gen_memcache_key(campaign) ) + if serialized_campaign_str.nil? + r = fetch_ab_testing_data(campaign, true) # force it + else + r = Marshal.load( serialized_campaign_str ) + end + end + return r + end + + public + def get_ab_testing_message(campaign) + dict = get_ab_helper(campaign) + if dict.nil? + return nil + else + json_obj = dict['json'] + msg_lst = json_obj['messages'] + weight_array = dict['msg_weight'] + index = weight_array[rand(weight_array.size)] + return msg_lst[index] + end + end + + public + def get_ab_testing_page(campaign) + dict = get_ab_helper(campaign) + if dict.nil? + return nil + else + json_obj = dict['json'] + page_lst = json_obj['pages'] + weight_array = dict['page_weight'] + index = weight_array[rand(weight_array.size)] + return page_lst[index] + end + end + + public + def cache_ab_testing_msg_and_page(campaign, msg_info, page_info) + @m_selected_msg_page_pair_dict[campaign] = {'page'=>page_info, 'msg'=>msg_info} + end + + public + def get_selected_msg_info(campaign) + msg_info = @m_selected_msg_page_pair_dict[campaign]['msg'] + if msg_info.nil? + return nil + else + return msg_info[0], msg_info[2] + end + end + + def get_selected_page_info(campaign) + page_info = @m_selected_msg_page_pair_dict[campaign]['page'] + if page_info.nil? + return nil + else + return page_info[0], page_info[2] + end + end + + private + def gen_memcache_fake_key(campaign) + return "kt_"+@m_backend_api_key+"_"+campaign+"_fake" + end + + private + def gen_memcache_key(campaign) + return "kt_"+@m_backend_api_key+"_"+campaign + end + + end + +end # module + +# mgr = Kt::AB_Testing_Manager.new('ea04b006c8174440a264ab4ab5b1e4e0', '45237b3a91184c389a4c12f38e7fe755', +# 'http://kthq.dyndns.org', 9999) +# #mgr.fetch_ab_testing_data('hello') +# puts mgr.get_ab_testing_message('hello') +# puts mgr.get_ab_testing_page('hello') diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index e63aea9..f10f010 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,190 +1,194 @@ # Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'facebooker' require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter(:store_user_id) controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end + # New Relic tracking of API calls + add_method_tracer :capture_user_data, 'Custom/Kontagent/CaptureUserData' + add_method_tracer :handle_kontagent, 'Custom/Kontagent/HandleKontagent' + def set_ab_testing_page(campaign) page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def store_user_id $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? return true end - + def capture_user_data begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end return true end def handle_kontagent get_params = params # trace uninstall if params.has_key? :fb_sig_uninstall Kt::KtAnalytics.instance.save_app_removed(params) return true end # track install if params.has_key? :installed and params[:installed] == "1" Kt::KtAnalytics.instance.save_app_added(params) end short_tag=nil if params.has_key? :kt_type # handle kontagent related parameters case params[:kt_type] when "ins" # invite sent Kt::KtAnalytics.instance.save_invite_send(params) when "in" # invite click Kt::KtAnalytics.instance.save_invite_click(params) when "nt" # notification click Kt::KtAnalytics.instance.save_notification_click(params) when "nte" # email notification Kt::KtAnalytics.instance.save_notification_email_click(params) when "fdp" short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) else end # forward to the url without the kt_* params f_url = get_stripped_kt_args_url(short_tag) #puts "f_url \n\t #{f_url}" #xxx redirect_to f_url else return true end end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
efecf9a7f2abf8ee2e8865fff3da2f740084e5bb
version 0.2.0
diff --git a/init.rb b/init.rb index e494bea..9cc816c 100644 --- a/init.rb +++ b/init.rb @@ -1,57 +1,57 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 puts "loading kt..." require 'facebook/session' require 'kt/rails/helpers' require 'facebooker/rails/publisher' require 'facebook/rails/publisher' #require 'facebooker/rails/controller' require 'facebook/rails/controller' require 'kt/rails/controller' config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") if config['mode'] == 'async' require 'starling' require 'starling_ext' require 'kt/queue/queue' require 'kt/queue/processor' require 'kt/queue/task' # Load app applicable Kontagent::Queue::Processor subclasses from app/processors Dir[RAILS_ROOT + '/app/processors/*.rb'].each do |file| require file end end module ::ActionController class Base def self.inherited_with_kt(subclass) inherited_without_kt(subclass) if subclass.to_s == "ApplicationController" subclass.class_eval do subclass.send(:include,Kt::Rails::Controller) end end end #def class << self alias_method_chain :inherited, :kt end end end ActionView::Base.send :include, Kt::Rails::KontagentHelpers diff --git a/install.rb b/install.rb index 570c7f9..906cff2 100644 --- a/install.rb +++ b/install.rb @@ -1,20 +1,20 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 # Install hook code here require 'fileutils' require 'rubygems' #require 'ruby-debug' #xxx if ARGV.size != 2 puts "Failure: you need to pass in the controller_name" else controller_name = ARGV[1] handle_iframe_html_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.html.erb") handle_iframe_fbml_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.fbml.erb") kontagent_yml_dst = File.join(RAILS_ROOT, "config", "kontagent.yml") puts "copying kontagent.yml.erb to #{kontagent_yml_dst}" FileUtils.cp( File.join(RAILS_ROOT, "vendor", "plugins", "kt", 'kontagent.yml.tpl'), kontagent_yml_dst ) unless File.exists?( kontagent_yml_dst ) end diff --git a/kontagent.yml.tpl b/kontagent.yml.tpl index 4d2b5c5..846c73c 100644 --- a/kontagent.yml.tpl +++ b/kontagent.yml.tpl @@ -1,130 +1,131 @@ # Parameter: kt_api_key # # Description: App-specific Kontagent API key found in the "Account" section # of the Kontagent website. Must be unique for each application # that you want to track. (32 character hex number) # kt_api_key: 00000000000000000000000000000000 # Parameter: kt_secret_key # # Description: Kontagent secret key for the app you specified with the # KT_API_KEY parameter. The secret key is found in the same # location on the Kontagent website as the KT_API_KEY. (32 # character hex number). # kt_secret_key: 00000000000000000000000000000000 # Parameter: canvas_page_name # # Description: The canvas page name that you have specified on Facebook's # application configuration page. For example, if your # application's full canvas page URL is apps.facebook.com/yourapp, # this value should be set to 'yourapp'. # # Example: yourapp # canvas_page_name : # Parameter: call_back_host # # Description: The call_back_host value is the host name component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to # www.example.com. This value MUST start with 'http://'. # # Example: http://your.callback.host # call_back_host: # Parameter: call_back_req_uri # # Description: The call_back_req_uri value is the path component of your # application's callback URL. For example, if your callback URL is # www.example.com/myapp, this value should be set to '/myapp'. Note # that this value must start with a '/'. # # Example: /your_app_uri # call_back_req_uri: # Parameter: use_test_server # # Description: Kontagent has a test server that data can be sent to during the # initial instrumentation phase to verify that an application has # been instrumented properly. The Kontagent website provides an # interface to this test server, which shows the number of # different types of messages that have been received in the last # three hours and the parameters associated with the last 10 # messages received. This can be used to resolve any instrumentation # issues you may encounter. # # The test server can be accessed on the Kontagent website by # logging in and then clicking on "Support", "Tools", "Test Server". # # If it is set to true, kt_host_test will be used. If it's set to # false, kt_host, will be used. # ************************** IMPORTANT *************************** # The data sent to the test server IS NOT SAVED PERMANENTLY AND # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE # SERVER. The test server is merely intended as a test tool and # must be disabled to capture data that can later be viewed in the # regular dashboard. # ************************** IMPORTANT *************************** use_test_server: false + ############################################################################### # starling configuration # ############################################################################### # Parameter: mode # # Valid values: async, sync # # Description: Set the mode to to 'async' to use the starling queue for # outgoing Kontagent traffic. Set it to 'sync' to disable the use # of the starling queue. NOTE: see the documentation on # Kontagent's websites for instructions on how to install # starling, if necessary. # mode: sync # Parameter: queue_address # # Description: Set the [ip]:[port] used by your starling queue installation. # This value will be ignored if 'mode' is set to 'sync'. # # Example: 127.0.0.1:22122 # queue_address: ############################################################################### # DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # # SPECIFICALLY TOLD BY KONTAGENT TO DO SO # ############################################################################### # Parameter: kt_host # # Description: The name of the Kontagent API server to which data is sent. Do # NOT change this value. # kt_host: api.kontagent.com # Parameter: kt_url # # Description: The path on the Kontagent API server that is used to collect the # analytics data. Do NOT change this value. # kt_url: /api # Parameter: kt_host_test # # Description: The name of the Kontagent test server to which data is sent when # the test mode is enabled. Do NOT change this value. # kt_host_test: api.test.kontagent.net diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb index e6a35ef..fe5991d 100644 --- a/lib/facebook/rails/controller.rb +++ b/lib/facebook/rails/controller.rb @@ -1,25 +1,25 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' module Facebooker module Rails module Controller def application_is_not_installed_by_facebook_user_with_kontagent if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") redirect_to session[:facebook_session].install_url else local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") end end #application_is_not_installed_by_facebook_user_with_kontagent alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent end #module Controller end end diff --git a/lib/facebook/rails/publisher.rb b/lib/facebook/rails/publisher.rb index 150e15e..dee9cc1 100644 --- a/lib/facebook/rails/publisher.rb +++ b/lib/facebook/rails/publisher.rb @@ -1,62 +1,68 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 + module Facebooker module Rails class Publisher def template(arg) @template = arg end def subtype1(arg) @subtype1 = arg end def subtype2(arg) @subtype2 = arg end + def campaign(arg) + @campaign = arg + end def send_message_with_kontagent(method) @recipients = @recipients.is_a?(Array) ? @recipients : [@recipients] if from.nil? and @recipients.size==1 and ! announcement_notification?(from,_body) @from = @recipients.first end # notifications can # omit the from address raise InvalidSender.new("Sender must be a Facebooker::User") unless from.is_a?(Facebooker::User) || announcement_notification?(from,_body) case _body when Facebooker::Feed::TemplatizedAction,Facebooker::Feed::Action from.publish_action(_body) when Facebooker::Feed::Story @recipients.each {|r| r.publish_story(_body)} when Notification - (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, @template, @subtype1, @subtype2) + (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, + @template, @subtype1, @subtype2, @campaign) when Email from.session.send_email(@recipients, _body.title, _body.text, _body.fbml, @template, @subtype1, - @subtype2) + @subtype2, + @campaign) when Profile # If recipient and from aren't the same person, create a new user object using the # userid from recipient and the session from from if @from != @recipients.first @from = Facebooker::User.new(Facebooker::User.cast_to_facebook_id(@recipients.first),from.session) end from.set_profile_fbml(_body.profile, _body.mobile_profile, _body.profile_action, _body.profile_main) when Ref @from.session.server_cache.set_ref_handle(_body.handle,_body.fbml) when UserAction - @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general) + @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general, @subtype1, @subtype2, @campaign) else raise UnspecifiedBodyType.new("You must specify a valid send_as") end end alias_method_chain :send_message, :kontagent end end end diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb index 4e28dd5..b1568bd 100644 --- a/lib/facebook/session.rb +++ b/lib/facebook/session.rb @@ -1,94 +1,150 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' +require 'ruby-debug' module Facebooker class Session - def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil) - uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) + def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) + + if !campaign.nil? + # ab testing + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nt, nil, campaign, msg_id, page_id, msg_txt) + else + uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) + end r = send_notification_without_kontagent(user_ids, fbml, email_fbml) if !r.blank? arg_hash = { - #'s' => @user.id.to_s, 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } if source_user.nil? arg_hash['s'] = 0.to_s else arg_hash['s'] = source_user.id.to_s end arg_hash['t'] = template_id.to_s unless template_id.nil? + if !campaign.nil? + arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) + arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) + arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) + else + arg_hash['st1'] = st1 + arg_hash['st2'] = st2 + arg_hash['st3'] = st3 + end + Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) end end - def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil) - if fbml != nil - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, - template_id, st1, st2) + def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil, campaign = nil) + if !campaign.nil? + # ab testing + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + if fbml != nil + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(fbml, :nte, nil, campaign, msg_id, page_id, msg_txt) + else + uuid = Kt::KtAnalytics.instance.gen_long_uuid + end else - uuid = Kt::KtAnalytics.instance.gen_long_uuid + if fbml != nil + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, template_id, st1, st2, st3) + else + uuid = Kt::KtAnalytics.instance.gen_long_uuid + end end r = send_email_without_kontagent(user_ids, subject, text, fbml) if !r.blank? arg_hash = { 's' => @user.id.to_s , 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, 'u' => uuid } + arg_hash['t'] = template_id.to_s unless template_id.nil? + if !campaign.nil? + arg_hash['st1'] = Kt::KtAnalytics.instance.format_kt_st1(campaign) + arg_hash['st2'] = Kt::KtAnalytics.instance.format_kt_st2(msg_id) + arg_hash['st3'] = Kt::KtAnalytics.instance.format_kt_st3(page_id) + else + arg_hash['st1'] = st1 + arg_hash['st2'] = st2 + end Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) end end - def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil) + # if st2 is set to m{d} and st3 is set to p{d}, we'll assume that it's using ab_testing data. + def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil, campaign=nil) + if !campaign.nil? + msg_id, msg_txt = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + page_id, page_txt =Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + st1 = campaign + st2 = msg_id + st3 = page_id + end + if(data != nil) data.each_pair do |key,value | if key == :image - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, - bundle_id, st1, st2) + if !campaign.nil? + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_vo(value[:href], :fdp, + bundle_id, st1, st2, st3, campaign) + else + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, + bundle_id, st1, st2) + end value[:href] = fbml data[key] = value # do we even need this line? elsif key == :flash elsif key == :mp3 - Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) + #Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) elsif key == :video - else - uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) + if !campaign.nil? + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href_vo(value, :fdp, bundle_id, st1, st2, st3) + else + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) + end data[key] = fbml end end end + data['KT_AB_MSG'] = msg_txt if !campaign.nil? + r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) - + if !r.blank? arg_hash = { 'pt' => 4, 's' => @user.id.to_s, 't' => bundle_id } Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) end end alias_method_chain :send_notification, :kontagent alias_method_chain :send_email, :kontagent alias_method_chain :publish_user_action, :kontagent end end diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb index 184ef00..328328b 100644 --- a/lib/kt/kt_analytics.rb +++ b/lib/kt/kt_analytics.rb @@ -1,464 +1,565 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_comm_layer' +require 'kt/kt_ab_testing' require 'kt/queue/task' require 'digest/md5' -#require 'ruby-debug' +require 'ruby-debug' module Kt class KtAnalytics @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls + @@KT_AB_MSG = /\{\*KT_AB_MSG\*\}/ @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} @@S_directed_val = 'd'; @@S_undirected_val = 'u'; @@instance_obj = nil - - attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url + + attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url, :m_ab_testing_mgr def self.instance() if @@instance_obj == nil @@instance_obj = new @@instance_obj.init end return @@instance_obj end def self.kt_args?(arg) if @@S_kt_args.has_key? arg return true else return false end end def self.install_args?(arg) if @@S_install_args.has_key? arg return true else return false end end def get_fb_param(request_params, param_name) r = 0 if request_params.has_key?('fb_sig_' + param_name) r = request_params['fb_sig_'+param_name] elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) r = request_params[Facebooker.api_key+"_"+param_name] end return r end private def initialize() end def init_from_conf(custom_conf = nil) @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") @config.merge! custom_conf if custom_conf #figure out the port if @config.has_key? $CURR_API_KEY app_config_map = @config[$CURR_API_KEY] else app_config_map = @config end - + if app_config_map['use_test_server'] == true if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end else if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? @m_kt_host_port = 80 else @m_kt_host_port = @config['kt_host_port'] end end # figure out the host if app_config_map['use_test_server'] == true @m_kt_host = @config['kt_host_test'] else @m_kt_host = @config['kt_host'] end if @m_kt_host_port != 80 @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" else @m_kt_host_url = "#{@m_kt_host}" end @m_kt_url = @config['kt_url'] @m_kt_api_key = app_config_map['kt_api_key'].to_s @m_kt_secret_key = app_config_map['kt_secret_key'].to_s @m_canvas_name = app_config_map['canvas_page_name'] @m_call_back_req_uri = app_config_map['call_back_req_uri'] @m_call_back_host = app_config_map['call_back_host'] @m_mode = (@config['mode'] == 'async') ? :async : :sync @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i + + ##### possibly overriding ab_testing_host/port with some testing host port ##### + if app_config_map.has_key? 'ab_testing_host' + @m_ab_testing_host = app_config_map['ab_testing_host'] + elsif @config.has_key? 'ab_testing_host' + @m_ab_testing_host = @config['ab_testing_host'] + end + + if app_config_map.has_key? 'ab_testing_port' + @m_ab_testing_port = app_config_map['ab_testing_port'] + elsif @config.has_key? 'ab_testing_port' + @m_ab_testing_port = @config['ab_testing_port'] + end + + ##### the normal ab_testing_host/port ##### + if @m_ab_testing_host.nil? and @m_ab_testing_port.nil? + if app_config_map.has_key? 'use_ab' or @config.has_key? 'use_ab' + @m_ab_testing_host = 'http://www.kontagent.com' + @m_ab_testing_port = 80 + end + end end - + public - def init(custom_conf = nil) - init_from_conf(custom_conf) + def format_kt_st1(st1_str) + return "aB_"+st1_str + end + + def format_kt_st2(st2_str) + return "m"+st2_str.to_s + end + + def format_kt_st3(st3_str) + return "p"+st3_str.to_s + end + + def init() + init_from_conf() @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) + @m_ab_testing_mgr = Kt::AB_Testing_Manager.new(@m_kt_api_key, @m_kt_secret_key, + @m_ab_testing_host, + @m_ab_testing_port) #TODO: get rid of the hardcoding stuff end def append_kt_query_str(original_url, query_str) if original_url =~ /\?/ return original_url + "&" + query_str else if query_str == nil || query_str == "" return original_url else return original_url + "?" + query_str end end end def get_page_tracking_url(fb_user_id) arg_hash = {} arg_hash['s'] = fb_user_id - @m_comm.get_call_url(@m_kt_url, "v1", @m_kt_api_key, @m_kt_secret_key, "pgr", arg_hash) end def get_invite_post_link_and_uuid(post_link, uid, template_id) uuid = gen_long_uuid url = get_invite_post_link(post_link, uid, uuid, template_id) - return url, uuid + return url , uuid end def get_invite_post_link(post_link, uid, uuid, template_id) arg_hash = {} arg_hash['kt_ut'] = uuid arg_hash['kt_uid'] = uid arg_hash['kt_type'] = 'ins' if template_id != nil arg_hash['kt_t'] = template_id end r_url = append_kt_query_str(post_link, arg_hash.to_query) return r_url end + def get_invite_post_link_and_uuid_vo(post_link, uid, campaign) + uuid = gen_long_uuid + url = get_invite_post_link_vo(post_link, uid, uuid, campaign) + return url , uuid + end + + def get_invite_post_link_vo(post_link, uid, uuid, campaign) + arg_hash = {} + arg_hash['kt_uid'] = uid + arg_hash['kt_ut'] = uuid + arg_hash['kt_type'] = 'ins' + arg_hash['kt_d'] = @@S_directed_val + + arg_hash['kt_st1'] = format_kt_st1(campaign) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + arg_hash['kt_st2'] = format_kt_st2(msg_id) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + arg_hash['kt_st3'] = format_kt_st3(page_id) + + r_url = append_kt_query_str(post_link, arg_hash.to_query) + return r_url + end def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) arg_hash = {} arg_hash['kt_uid'] = uid arg_hash['kt_ut'] = uuid arg_hash['kt_type'] = 'in' arg_hash['kt_d'] = @@S_directed_val if template_id != nil arg_hash['kt_t'] = template_id end if subtype1 != nil arg_hash['kt_st1'] = subtype1 end if subtype2 != nil arg_hash['kt_st2'] = subtype2 end r_url = append_kt_query_str(content_link, arg_hash.to_query) return r_url end - + def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) uuid = gen_long_uuid url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) return url, uuid end + def get_invite_content_link_and_uuid_vo(content_link, uid, campaign) + uuid = gen_long_uuid + url = get_invite_post_link_vo(content_link, uid, uuid, campaign) + return url, uuid + end + + def get_invite_content_link_vo(content_link, uid, uuid, campaign) + arg_hash = {} + arg_hash['kt_uid'] = uid + arg_hash['kt_ut'] = uuid + arg_hash['kt_type'] = 'in' + arg_hash['kt_d'] = @@S_directed_val + + arg_hash['kt_st1'] = format_kt_st1(campaign) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + arg_hash['kt_st2'] = format_kt_st2(msg_id) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + arg_hash['kt_st3'] = format_kt_st3(page_id) + + r_url = append_kt_query_str(content_link, arg_hash.to_query) + return r_url + end def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) - uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| if $1.nil? append_kt_query_str($2, query_str) else $1 + append_kt_query_str($2, query_str) end } + return uuid,input_txt end #gen_kt_comm_link + + def gen_kt_comm_link_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id, msg_txt) + uuid, query_str = gen_kt_comm_query_str(comm_type, template_id, + format_kt_st1(campaign), + format_kt_st2(msg_id), + format_kt_st3(page_id)) + input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| + if $1.nil? + input_txt + else + append_kt_query_str($1, query_str) + end + } + input_txt = input_txt.gsub(@@KT_AB_MSG){|match| + msg_txt + } + return uuid, input_txt + end + def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) - uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, nil) input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| if $1.nil? input_txt else append_kt_query_str($1, query_str) end } return uuid, input_txt end #gen_kt_comm_link_no_href - def send_user_data_impl(user) - time("making API calls for Kontagent user data") do - arg_hash = {} - - if !user.birthday.blank? && user.birthday != '' - arg_hash['b'] = user.birthday - end - if !user.sex.blank? && user.sex != '' - arg_hash['g'] = user.sex + def gen_kt_comm_link_no_href_vo(input_txt, comm_type, template_id, campaign, msg_id, page_id) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, + format_kt_st1(campaign), + format_kt_st2(msg_id), + format_kt_st3(page_id)) + input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| + if $1.nil? + input_txt + else + append_kt_query_str($1, query_str) end + } + return uuid, input_txt + end + + def send_user_data_impl(user) + arg_hash = {} - # if !user.current_location.city.blank? &&user.current_location.city != '' - # arg_hash['ly'] = user.current_location.city - # end - # if !user.current_location.state.blank? && user.current_location.state != '' - # arg_hash['ls'] = user.current_location.state - # end - # if !user.current_location.country.blank? && user.current_location.country != '' - # arg_hash['lc'] = user.current_location.country - # end - # if !user.current_location.zip.blank? && user.current_location.zip != '' - # arg_hash['lp'] = user.current_location.zip - # end - # - # - # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' - # arg_hash['ly'] = user.hometown_location.city - # end - # if !user.hometown_location.state.blank? && user.hometown_location.state != '' - # arg_hash['ls'] = user.hometown_location.state - # end - # if !user.hometown_location.country.blank? && user.hometown_location.country != '' - # arg_hash['lc'] = user.hometown_location.country - # end - # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' - # arg_hash['lp'] = user.hometown_location.zip - # end - - arg_hash['f'] = user.friends.size.to_s - # RAILS_DEFAULT_LOGGER.warn arg_hash.inspect # LOCAL + if !user.birthday.blank? && user.birthday != '' + arg_hash['b'] = user.birthday end + if !user.sex.blank? && user.sex != '' + arg_hash['g'] = user.sex + end + +# if !user.current_location.city.blank? &&user.current_location.city != '' +# arg_hash['ly'] = user.current_location.city +# end +# if !user.current_location.state.blank? && user.current_location.state != '' +# arg_hash['ls'] = user.current_location.state +# end +# if !user.current_location.country.blank? && user.current_location.country != '' +# arg_hash['lc'] = user.current_location.country +# end +# if !user.current_location.zip.blank? && user.current_location.zip != '' +# arg_hash['lp'] = user.current_location.zip +# end + + +# if !user.hometown_location.city.blank? &&user.hometown_location.city != '' +# arg_hash['ly'] = user.hometown_location.city +# end +# if !user.hometown_location.state.blank? && user.hometown_location.state != '' +# arg_hash['ls'] = user.hometown_location.state +# end +# if !user.hometown_location.country.blank? && user.hometown_location.country != '' +# arg_hash['lc'] = user.hometown_location.country +# end +# if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' +# arg_hash['lp'] = user.hometown_location.zip +# end + + arg_hash['f'] = user.friends.size.to_s kt_outbound_msg('cpu', arg_hash) return true end def send_user_data(user) #sex', 'birthday', 'current_location', 'hometown_location if @m_mode == :async data_hash ={ :qtype => :capture_user_data, :user => Marshal.dump(user) } Kt::Queue::Task.publish :record, data_hash else send_user_data_impl(user) end end def save_app_removed(uid) arg_hash = {'s'=>uid} kt_outbound_msg('apr', arg_hash) end def save_app_added(request_params) has_direction = false if request_params[:d] != nil has_direction = true end arg_hash = {} arg_hash['s'] = get_fb_param(request_params, 'user') if has_direction == true and request_params[:d] == @@S_directed_val arg_hash['u'] = request_params[:ut] kt_outbound_msg('apa', arg_hash) elsif has_direction == true and request_params[:d] == @@S_undirected_val arg_hash['su'] = request_params[:sut] kt_outbound_msg('apa', arg_hash) else # no viral kt_outbound_msg('apa', arg_hash) end end def save_invite_send(request_params) arg_hash = {} arg_hash['s'] = request_params[:kt_uid] arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] arg_hash['u'] = request_params[:kt_ut] - if request_params['kt_t'] != nil - arg_hash['t'] = request_params[:kt_t] - end + + arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? + arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? + arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? + arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? + kt_outbound_msg('ins', arg_hash) end def save_invite_click(request_params) arg_hash = {} arg_hash['i'] = get_fb_param(request_params, 'added') arg_hash['u'] = request_params[:kt_ut] arg_hash['tu'] = 'inr' - if request_params[:kt_t] != nil - arg_hash['t'] = request_params[:kt_t] - end - if request_params[:kt_st1] != nil - arg_hash['st1'] = request_params[:kt_st1] - end - if request_params[:kt_st2] != nil - arg_hash['st2'] = request_params[:kt_st2] - end + arg_hash['t'] = request_params[:kt_t] if !request_params['kt_t'].nil? + arg_hash['st1'] = request_params[:kt_st1] if !request_params['kt_st1'].nil? + arg_hash['st2'] = request_params[:kt_st2] if !request_params['kt_st2'].nil? + arg_hash['st3'] = request_params[:kt_st3] if !request_params['kt_st3'].nil? + kt_outbound_msg('inr', arg_hash) end def save_notification_click(request_params) msg_type = 'ntr' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_notification_email_click(request_params) msg_type = 'nei' arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) kt_outbound_msg(msg_type, arg_hash) end def save_undirected_comm_click(request_params) msg_type = 'ucc' arg_hash = {} arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil + arg_hash['st3'] = request_params[:kt_st3] unless request_params[:kt_st3] == nil arg_hash['tu'] = request_params[:kt_type] arg_hash['s'] = get_fb_param(request_params, 'user') short_tag = gen_short_uuid arg_hash['su'] = short_tag arg_hash['i'] = get_fb_param(request_params, 'added') kt_outbound_msg(msg_type, arg_hash) return short_tag end def kt_outbound_msg(type, arg_hash) - time("sending Kontagent message (#{arg_hash.inspect})") do - if @m_mode == :async - #timeout(@m_timeout) do - data_hash = { - :qtype => :kt_outbound, - :ctype => type, - :v => 'v1', - :kt_api_key => @m_kt_api_key, - :kt_secret_key => @m_kt_secret_key, - :kt_call_back_host => @m_kt_host, - :kt_call_back_port => @m_kt_host_port, - :kt_url => @m_kt_url, - :arg_hash => arg_hash, - } - Kt::Queue::Task.publish :record, data_hash - #end - else - @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) - end + if @m_mode == :async + #timeout(@m_timeout) do + data_hash = { + :qtype => :kt_outbound, + :ctype => type, + :v => 'v1', + :kt_api_key => @m_kt_api_key, + :kt_secret_key => @m_kt_secret_key, + :kt_call_back_host => @m_kt_host, + :kt_call_back_port => @m_kt_host_port, + :kt_url => @m_kt_url, + :arg_hash => arg_hash, + } + Kt::Queue::Task.publish :record, data_hash + #end + else + @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) end end # It's more secure to have 32 characters def gen_long_uuid() CGI::Session.generate_unique_id('kontagent') end private def construct_arg_hash_for_click_event_helper(msg_type, request_params) arg_hash = {} arg_hash['tu'] = msg_type arg_hash['i'] = get_fb_param(request_params, 'added') if request_params.has_key? 'kt_ut' arg_hash['u'] = request_params[:kt_ut] end - if request_params.has_key? 'kt_t' - arg_hash['t'] = request_params[:kt_t] - end - if request_params.has_key? 'kt_st1' - arg_hash['st1'] = request_params[:kt_st1] - end - if request_params.has_key? 'kt_st2' - arg_hash['st2'] = request_params[:kt_st2] - end + + arg_hash['t'] = request_params[:kt_t] if request_params.has_key? 'kt_t' + arg_hash['st1'] = request_params[:kt_st1] if request_params.has_key? 'kt_st1' + arg_hash['st2'] = request_params[:kt_st2] if request_params.has_key? 'kt_st2' + arg_hash['st3'] = request_params[:kt_st3] if request_params.has_key? 'kt_st3' + uid = get_fb_param(request_params, 'user') if uid != 0 arg_hash['r'] = uid end return arg_hash end def gen_short_uuid() gen_long_uuid[0...8] end def directed_type?(comm_type) @@S_directed_types.has_key?(comm_type) end def undirected_type?(comm_type) @@S_undirected_types.has_key?(comm_type) end - def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2, subtype3) param_array = {} uuid = 0 if comm_type != nil if directed_type? comm_type dir_val = @@S_directed_val elsif undirected_type? comm_type dir_val = @@S_undirected_val else # profile? end end param_array[:kt_d] = dir_val param_array[:kt_type] = comm_type if dir_val == @@S_directed_val uuid = gen_long_uuid() param_array[:kt_ut] = uuid end - if template_id != nil - param_array[:kt_t] = template_id.to_s - end - - if subtype1 != nil - param_array[:kt_st1] = subtype1 - end - - if subtype2 != nil - param_array[:kt_st2] = subtype2 - end + param_array[:kt_t] = template_id.to_s if !template_id.nil? + param_array[:kt_st1] = subtype1 if !subtype1.nil? + param_array[:kt_st2] = subtype2 if !subtype2.nil? + param_array[:kt_st3] = subtype3 if !subtype3.nil? return uuid, param_array.to_query end #gen_kt_comm_query_str end #Kt_Analytics end#mdoule diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb index 4fd292e..8550409 100644 --- a/lib/kt/kt_comm_layer.rb +++ b/lib/kt/kt_comm_layer.rb @@ -1,143 +1,138 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 #require 'socket' require 'net/http' -#require 'timeout' +require 'timeout' require 'cgi' require 'uri' require 'digest/md5' #require 'benchmark' include Socket::Constants module Kt class KtComm @@instance_obj = nil private def initialize(host, port) puts "initializing KtComm" @m_host = host @m_port = port + + if @m_host == "api.geo.kontagent.net" + @m_ip = fetch_ip() + else + @m_ip = host + end end + + def _fetch_ip_helper(host_name_str, port) + ip_lst = Socket.getaddrinfo(host_name_str, 'http') + ip_lst.sort_by{ rand } + selected_ip = nil + + ip_lst.each do |ip_info| + ip_str = ip_info[3] + socket = Socket.new(AF_INET, SOCK_STREAM, 0) + sockaddr = Socket.sockaddr_in(port, ip_str) + status = -1 + timeout(2) do + status = socket.connect(sockaddr) + end + if status == 0 + selected_ip = ip_str + break + end + end #loop + return selected_ip + end # _fetch_ip_helper + + def fetch_ip() + selected_ip = _fetch_ip_helper(@m_host, @m_port) + if selected_ip.nil? + selected_ip = _fetch_ip_helper("api.global.kontagent.net", 80) + end + + return selected_ip + end + public def self.instance(host, port) if @@instance_obj == nil @@instance_obj = new(host, port) end return @@instance_obj end + # kt_api_url : excludes the host name. # version : example, v1, v2, etc. # api_key : kontagent's api key is used to uniquely identify the user. # secret_key : kontagent's secret key # api_func : example, ins for "invite sent", inr for "invite clicked", etc # arg_assoc_hash : an associative hash of argument list. def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) -# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) -# url_path = "http://"+@m_host+":"+@m_port.to_s+url_path -# uri = URI.parse(url_path) -# Net::HTTP.get(uri) socket = Socket.new(AF_INET, SOCK_STREAM, 0) - sockaddr = Socket.sockaddr_in(@m_port, @m_host) - + sockaddr = Socket.sockaddr_in(@m_port, @m_ip) + connected = true #puts Benchmark.measure{ begin socket.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS IO.select(nil, [socket]) begin socket.connect_nonblock(sockaddr) rescue Errno::EISCONN connected = false puts "Errno::EISCONN!!" end end #} if connected url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) buf = "GET " + url_path + " HTTP/1.1\r\n" - buf << "Host:" + @m_host + "\r\n" + buf << "Host:" + @m_ip + ":" + @m_port.to_s + "\r\n" buf << "Content-type: application/x-www-form-urlencoded\r\n" buf << "Accept: */*\r\n" buf << "\r\n" buf << "\r\n" socket.write_nonblock buf end socket.close return connected -# socket = nil - -# puts @m_host -# begin -# timeout(2) do -# #socket = TCPSocket::new(@m_host, 80) #uncomment this -# socket = TCPSocket::new(@m_host, @m_port) -# end -# rescue Timeout::Error -# puts "timeout!!!" -# return -# rescue -# puts "tcp error!!!!" -# return -# end - -# if socket != nil -# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) -# #puts "url_path: #{url_path}" #xxx - -# buf = "GET " + url_path + " HTTP/1.1\r\n" -# buf << "Host:" + @m_host + "\r\n" -# buf << "Content-type: application/x-www-form-urlencoded\r\n" -# buf << "Accept: */*\r\n" -# buf << "\r\n" -# buf << "\r\n" -# socket.write buf -# socket.close -# end - - # old code - # socket.write("GET " + url_path + " HTTP/1.1\r\n") - # socket.write("Host:" + @m_host + "\r\n") - # socket.write("Content-type: application/x-www-form-urlencoded\r\n") - # socket.write("Accept: */*\r\n") - # socket.write("\r\n") - # socket.write("\r\n") - # socket.close - #end end def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) sig = '' arg_assoc_hash['ts'] = Time.now.to_s # This is to get rid of null parameters. in the assoc array keys = arg_assoc_hash.keys.sort keys.each do |key| sig += key+"="+arg_assoc_hash[key].to_s end arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) query = arg_assoc_hash.to_query url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query end end end # test #comm = Kontagent::Kt_Comm.new('67.102.65.65') #comm = Kontagent::Kt_Comm.new('10.0.0.0') #comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'}) diff --git a/lib/kt/queue/processor.rb b/lib/kt/queue/processor.rb index 429a710..1cef858 100644 --- a/lib/kt/queue/processor.rb +++ b/lib/kt/queue/processor.rb @@ -1,84 +1,84 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 module Kt module Queue LOST_CONNECTION_ERROR_MESSAGES = [ "Server shutdown in progress", "Broken pipe", "Lost connection to MySQL server during query", "MySQL server has gone away" ] # An object not found proxy exception. This is used inside our generated getter methods # to rescue ActiveRecord::RecordNotFound class NotFound < Exception; end class Processor def options @task.options end # Takes a class name and returns and creates an accessor method and instance # variable for it. If the class responds to find (i.e. ActiveRecord objects), then # it tries to call it with the value of name_id extracted from the Task. # If not, it creates a new instaces of the class, sets an instance variable with that name # and returns it. def self.processes(name) name = name.to_s define_method(name) do ivar = instance_variable_get("@#{name}") return ivar unless ivar.blank? object = Object.const_get(name.camelize) value = if object.respond_to?(:find) begin object.find(@task.options["#{name}_id".intern]) # We provide automatic ActiveRecord::RecordNotFound protection because this method # useless without a correct instance of the model. rescue ActiveRecord::RecordNotFound => rnf raise Kt::NotFound, rnf.message end else Object.const_get(name.camelize).send('new') end instance_variable_set("@#{name}", value) value end end # Runs the process method defined in the Processor subclass (in app/processors). # Any error that is fatal should be rescued to avoid re-entry in to the queue. As a default, we rescue # ActiveRecord::RecordNotFound (record not found). # Subclasses of Processor should rescue any fatal errors specific to them in their own process method. def process!(task) @task = task tries = 0 begin process rescue ActiveRecord::StatementInvalid => sti lost_connection = false LOST_CONNECTION_ERROR_MESSAGES.each do |error| lost_connection = true if sti.message =~ /#{error}/ end if lost_connection && tries == 0 tries += 1 ActiveRecord::Base.connection.reconnect! retry end task.enqueue_with_error(sti) rescue Kt::Queue::NotFound => notfound rescue Exception => e task.enqueue_with_error(e) end end end end end diff --git a/lib/kt/queue/queue.rb b/lib/kt/queue/queue.rb index 2fb380e..9e434b1 100644 --- a/lib/kt/queue/queue.rb +++ b/lib/kt/queue/queue.rb @@ -1,183 +1,183 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'starling' module Kt module Queue class Queue attr_reader :connection # Max number of reconnection attempts to starling MAX_TRIES = 1 class << self def queue @queue ||= Queue.new end def enqueue(priority, message) queue.enqueue(priority, message) end def process! queue.process! end def stop! queue.stop! end # Statictics methods def count_permanently_failed queue.connection.sizeof("#{queue.config['canvas_page_name']}_p_0") end def count queue.connection.sizeof(:all).inject(0){|c, (k, v)| c+= v} end # Use this method to see what's in the queue def peek(priority, iterate = 1) messages = [] iterate.times do message = queue.connection.get("#{queue.config['canvas_page_name']}_p_#{priority}") enqueue(priority, message) messages << message end messages end # You can use this method to define an external Proc (usually a lambda) that # is sent a notification when a task fails more than the max allowed times. # The lambda is passed the Kt::Queue::Task object, and the last Exception object. # For example: # Kt::Queue::Queue.failure_notification_observer = lambda {|task, error| # Mailer.deliver_exception_mail(...) # } attr_accessor :failure_notification_observer end def initialize self.connect! end def enqueue(priority, message) if message[:action].blank? error = "Tried to queue a task with an empty action. The message being queued was: #{message.inspect}" Kt::Queue::Queue.log(error, true) end @current_message = message value_with_retries do @connection.set("#{config['canvas_page_name']}_p_#{priority}", message) end end def dequeue(priority) @current_message = nil value_with_retries do @connection.get("#{config['canvas_page_name']}_p_#{priority}") end end # Loads the config file def config @config ||= YAML.load_file("#{RAILS_ROOT}/config/kontagent.yml") end # Gets the next_item in the Queue def next_item result = nil 10.times do |i| result = dequeue(i+1) break unless result.blank? end result end def flush 10.times do |i| result = @connection.flush("#{config['canvas_page_name']}_p_#{i+1}") end end # The main loop. It goes like this: # 1. Calls process which: # * calls next_item (returns nil or a task from the queue) # * process returns false if next_item is nil # * process creates a new task and calls process! on it # 2. The loop continues def process! @running = true while @running result = process unless result puts "Waiting..." if RAILS_ENV == "development" GC.enable GC.start sleep 3 end sleep 1 end end def stop! @running = false end def self.log(message, force=false) RAILS_DEFAULT_LOGGER.send(force ? :error : :debug, message) end protected def connect! Kt::Queue::Queue.log "Connecting on #{config['queue_address']}, canvas_page_name: #{config['canvas_page_name']}" @connection = Starling.new(config['queue_address']) end # Gets an item from the queue if there is one, creates a task, and runs process! on it def process task = next_item Kt::Queue::Queue.log "Running #{task.inspect}..." task.blank? ? false : Kt::Queue::Task.from_message(task).process! end def value_with_retries(&block) tries = 0 result = nil begin result = yield rescue MemCache::MemCacheError => e Kt::Queue::Queue.log "Try ##{tries} - Starling Error: #{e.class} -> #{e}" connect! # If we can't connect to the server at all, we just put a line in the log file. # This can be parsed later to write back to the queue if desired if (tries += 1) > MAX_TRIES unless @current_message.blank? Kt::Queue::Queue.log("+++ #{Time.now.to_i} #{@current_message.inspect}", true) if Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(@current_message, e) end end return nil end retry end return result end end end end diff --git a/lib/kt/queue/task.rb b/lib/kt/queue/task.rb index e7d8370..58b186f 100644 --- a/lib/kt/queue/task.rb +++ b/lib/kt/queue/task.rb @@ -1,76 +1,76 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/queue/processor' require 'kt/kt_comm_layer' class RecordProcessor < Kt::Queue::Processor def process op = options qtype = op[:qtype] if qtype == :kt_outbound m_comm = Kt::KtComm.instance(op[:kt_call_back_host], op[:kt_call_back_port]) m_comm.api_call_method(op[:kt_url], op[:v], op[:kt_api_key], op[:kt_secret_key], op[:ctype], op[:arg_hash]) elsif qtype == :capture_user_data Kt::KtAnalytics.instance.send_user_data_impl(Marshal.load(op[:user])) end end end module Kt module Queue class Task MAX_ERRORS = 3 attr_reader :options def process! processor.new.process!(self) end # Puts a failed Task back in the Queue with the lowest priority. # If a task fails MAX_ERRORS times, it is put in Queue 0 which is never processed. def enqueue_with_error(e) @options[:failures] = @options[:failures].to_i + 1 @options[:errors] ||= [] @options[:priority] = (@options[:failures] < MAX_ERRORS) ? 10 : 0 Kt::Queue::Queue.enqueue(@options[:priority], @options.merge!({ :action => @action, :errors => @options[:errors] << {:class => e.class.to_s, :message => e.message} })) Kt::Queue::Queue.log("Action '#{@action}' failed #{@options[:failures]} time(s).") # Send failure notification if a notification observer is defined if @options[:priority] == 0 && Kt::Queue::Queue.failure_notification_observer Kt::Queue::Queue.failure_notification_observer.call(self, e) end end # Puts actions in the Queue. Priority defaults to 5 def self.publish(action, options={}) priority = options[:priority] || 5 options.merge!({:action => action}) Kt::Queue::Queue.enqueue(priority, options) end # Creates a Task from a message def self.from_message(message) action = message.delete :action Task.new(action, message) end def initialize(action, options = {}) @action = action @options = {:priority => 5}.merge(options) end protected # Infers a Processor's name from the action def processor Object.const_get(@action.to_s.camelize + 'Processor') end end end end diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index 320345c..e63aea9 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,183 +1,190 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'facebooker' -#require 'ruby-debug' +require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) - #controller.before_filter(:capture_user_data) + controller.before_filter(:store_user_id) + controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end + def set_ab_testing_page(campaign) + page_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_page(campaign) + msg_info = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_ab_testing_message(campaign) + Kt::KtAnalytics.instance.m_ab_testing_mgr.cache_ab_testing_msg_and_page(campaign, msg_info, page_info) + end + # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end + def store_user_id + $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? + return true + end + def capture_user_data - time(" capture user data") do - begin - user = session[:facebook_session].user - key = "KT_" + Facebooker.api_key + "_" + user.id.to_s - if cookies[key].blank? - Kt::KtAnalytics.instance.send_user_data(user) - end - cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks - rescue - # invalid session key. + begin + user = session[:facebook_session].user + key = "KT_" + Facebooker.api_key + "_" + user.id.to_s + if cookies[key].blank? + Kt::KtAnalytics.instance.send_user_data(user) end + cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks + rescue + # invalid session key. end - return true + return true end def handle_kontagent - unless App.current.theme.template.code == "snowball" - time("Handle kontagent") do - get_params = params - $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? - - # trace uninstall - if params.has_key? :fb_sig_uninstall - Kt::KtAnalytics.instance.save_app_removed(params) - return true - end + get_params = params + + # trace uninstall + if params.has_key? :fb_sig_uninstall + Kt::KtAnalytics.instance.save_app_removed(params) + return true + end - # track install - if params.has_key? :installed and params[:installed] == "1" - Kt::KtAnalytics.instance.save_app_added(params) - end + # track install + if params.has_key? :installed and params[:installed] == "1" + Kt::KtAnalytics.instance.save_app_added(params) + end - short_tag=nil - if params.has_key? :kt_type - # handle kontagent related parameters - case params[:kt_type] - when "ins" # invite sent - Kt::KtAnalytics.instance.save_invite_send(params) - when "in" # invite click - Kt::KtAnalytics.instance.save_invite_click(params) - when "nt" # notification click - Kt::KtAnalytics.instance.save_notification_click(params) - when "nte" # email notification - Kt::KtAnalytics.instance.save_notification_email_click(params) - when "fdp" - short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) - else + short_tag=nil + if params.has_key? :kt_type + # handle kontagent related parameters + case params[:kt_type] + when "ins" # invite sent + Kt::KtAnalytics.instance.save_invite_send(params) + when "in" # invite click + Kt::KtAnalytics.instance.save_invite_click(params) + when "nt" # notification click + Kt::KtAnalytics.instance.save_notification_click(params) + when "nte" # email notification + Kt::KtAnalytics.instance.save_notification_email_click(params) + when "fdp" + short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) + else - end - - # forward to the url without the kt_* params - f_url = get_stripped_kt_args_url(short_tag) - #puts "f_url \n\t #{f_url}" #xxx - redirect_to f_url - else - return true - end end + + # forward to the url without the kt_* params + f_url = get_stripped_kt_args_url(short_tag) + #puts "f_url \n\t #{f_url}" #xxx + redirect_to f_url + + else + return true end + end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb index c802583..c11f69b 100644 --- a/lib/kt/rails/helpers.rb +++ b/lib/kt/rails/helpers.rb @@ -1,60 +1,107 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 require 'kt/kt_analytics' require 'cgi' module Kt module Rails module KontagentHelpers + def kt_get_page_text(campaign) + page_id, page_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_page_info(campaign) + return page_text + end + def kt_get_msg_text(campaign) + msg_id, msg_text = Kt::KtAnalytics.instance.m_ab_testing_mgr.get_selected_msg_info(campaign) + return msg_text + end + + def kt_get_invite_post_link_vo(invite_post_link, campaign) + url = nil + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + + if session['invite_uuid'].nil? + url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid_vo(invite_post_link, + uid, + campaign) + session['invite_uuid'] = uuid + else + url = Kt::KtAnalytics.instance.get_invite_post_link_vo(invite_post_link, + uid, + session['invite_uuid'], + campaign) + session['invite_uuid'] = nil + end + return url + end + + def kt_get_invite_content_link_vo(invite_content_link, campaign) + url = nil + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + + if session['invite_uuid'].nil? + url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid_vo(invite_content_link, + uid, + campaign) + session['invite_uuid'] = uuid + else + url = Kt::KtAnalytics.instance.get_invite_content_link_vo(invite_content_link, + uid, + session['invite_uuid'], + campaign) + session['invite_uuid'] = nil + end + return url + end + def kt_get_invite_post_link(invite_post_link, template_id=nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - if session['invite_uuid'] == nil + if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, uid, template_id) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, uid, session['invite_uuid'], template_id) session['invite_uuid'] = nil end return url end def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) url = nil uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') - if session['invite_uuid'] == nil + if session['invite_uuid'].nil? url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, uid, template_id, subtype1,subtype2) session['invite_uuid'] = uuid else url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, uid, session['invite_uuid'], template_id, subtype1,subtype2) session['invite_uuid'] = nil end return url end def kt_track_page_view() uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" return track_code_str end end end end diff --git a/lib/starling_ext.rb b/lib/starling_ext.rb index 6655041..2a41d03 100644 --- a/lib/starling_ext.rb +++ b/lib/starling_ext.rb @@ -1,7 +1,7 @@ -# Kontagent facebooker version 0.1.6 +# Kontagent facebooker version 0.2.0 # An extension to the Starling class from Twitter's (www.twitter.com) starling (http://rubyforge.org/projects/starling) gem. class Starling def get(*args) super(*args) end end \ No newline at end of file
rmatei/kt
b69cab21deb0b841a3a9adbd67decdad659bf904
took handle kont out of snowball
diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb index f35d090..320345c 100644 --- a/lib/kt/rails/controller.rb +++ b/lib/kt/rails/controller.rb @@ -1,183 +1,183 @@ # Kontagent facebooker version 0.1.6 require 'kt/kt_analytics' require 'facebooker' #require 'ruby-debug' module Kt module Rails module Controller def self.included(controller) controller.extend(ClassMethods) #controller.before_filter(:capture_user_data) controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) end # DEPRECATED : we don't use iframes to track page views anymore. def handle_iframe page_uri = params[:page_uri] uid = params[:request_id] end def post_remove puts "calling post_remove..." Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) render :nothing end protected def verify_uninstall_signature puts "calling verify_uninstall_signature..." #xxx signature = '' keys = params.keys.sort keys.each do |key| next if key == 'fb_sig' next unless key.include?('fb_sig') key_name = key.gsub('fb_sig_', '') signature += key_name signature += '=' signature += params[key] end signature += Facebooker.secret_key calculated_sig = Digest::MD5.hexdigest(signature) if calculated_sig != params[:fb_sig] #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" return false else #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" post_remove # force calling post_remove return true end end def capture_user_data time(" capture user data") do begin user = session[:facebook_session].user key = "KT_" + Facebooker.api_key + "_" + user.id.to_s if cookies[key].blank? Kt::KtAnalytics.instance.send_user_data(user) end cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks rescue # invalid session key. end end return true end def handle_kontagent - time("Handle kontagent") do - get_params = params - $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? + unless App.current.theme.template.code == "snowball" + time("Handle kontagent") do + get_params = params + $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? - # trace uninstall - if params.has_key? :fb_sig_uninstall - Kt::KtAnalytics.instance.save_app_removed(params) - return true - end + # trace uninstall + if params.has_key? :fb_sig_uninstall + Kt::KtAnalytics.instance.save_app_removed(params) + return true + end - # track install - if params.has_key? :installed and params[:installed] == "1" - Kt::KtAnalytics.instance.save_app_added(params) - end + # track install + if params.has_key? :installed and params[:installed] == "1" + Kt::KtAnalytics.instance.save_app_added(params) + end - short_tag=nil - if params.has_key? :kt_type - # handle kontagent related parameters - case params[:kt_type] - when "ins" # invite sent - Kt::KtAnalytics.instance.save_invite_send(params) - when "in" # invite click - Kt::KtAnalytics.instance.save_invite_click(params) - when "nt" # notification click - Kt::KtAnalytics.instance.save_notification_click(params) - when "nte" # email notification - Kt::KtAnalytics.instance.save_notification_email_click(params) - when "fdp" - short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) - else + short_tag=nil + if params.has_key? :kt_type + # handle kontagent related parameters + case params[:kt_type] + when "ins" # invite sent + Kt::KtAnalytics.instance.save_invite_send(params) + when "in" # invite click + Kt::KtAnalytics.instance.save_invite_click(params) + when "nt" # notification click + Kt::KtAnalytics.instance.save_notification_click(params) + when "nte" # email notification + Kt::KtAnalytics.instance.save_notification_email_click(params) + when "fdp" + short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) + else - end + end - # forward to the url without the kt_* params - f_url = get_stripped_kt_args_url(short_tag) - #puts "f_url \n\t #{f_url}" #xxx - redirect_to f_url - - else - return true + # forward to the url without the kt_* params + f_url = get_stripped_kt_args_url(short_tag) + #puts "f_url \n\t #{f_url}" #xxx + redirect_to f_url + else + return true + end end end - end # handle_kontagent private def get_stripped_kt_args_url (short_tag = nil) get_params = request.parameters r_param_hash = {} get_params.each_pair do | get_key, get_val | if Kt::KtAnalytics.kt_args?(get_key.intern) if get_key == 'kt_d' r_param_hash['d'] = get_val elsif get_key == 'kt_ut' r_param_hash['ut'] = get_val end params.delete(get_key) elsif !get_key.include? "fb_sig" r_param_hash[get_key] = get_val end end if short_tag != nil r_param_hash['sut'] = short_tag end return build_url(r_param_hash) end #get_stripped_kt_args_url def build_url(param_hash) local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri matches = request.path.match(/#{local_req_uri}(.*)/) if matches == nil puts "found NO match!!!" r_url = "" else puts "found a match!!!" puts "\t #{matches[1]}" r_url = matches[1] if r_url == "/" r_url = "" end end # puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" # puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" # puts "request.request_uri \n\t #{request.request_uri}" # puts "param_hash \n\t #{param_hash.to_query}" # puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, param_hash.to_query) #puts "final_url \n\t#{r_url}" return r_url end module ClassMethods end end end end
rmatei/kt
861999b330e1018e67abaa84c77eda881246c356
importing Kontagent into its own repo
diff --git a/MIT-LICENSE b/MIT-LICENSE new file mode 100644 index 0000000..8eaf6db --- /dev/null +++ b/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2008 [name of plugin creator] + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README b/README new file mode 100644 index 0000000..24cd5cd --- /dev/null +++ b/README @@ -0,0 +1,13 @@ +Kt +== + +Introduction goes here. + + +Example +======= + +Example goes here. + + +Copyright (c) 2008 [name of plugin creator], released under the MIT license diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..da7c517 --- /dev/null +++ b/Rakefile @@ -0,0 +1,22 @@ +require 'rake' +require 'rake/testtask' +require 'rake/rdoctask' + +desc 'Default: run unit tests.' +task :default => :test + +desc 'Test the kt plugin.' +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.pattern = 'test/**/*_test.rb' + t.verbose = true +end + +desc 'Generate documentation for the kt plugin.' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'Kt' + rdoc.options << '--line-numbers' << '--inline-source' + rdoc.rdoc_files.include('README') + rdoc.rdoc_files.include('lib/**/*.rb') +end diff --git a/handle_iframe.fbml.erb.tpl b/handle_iframe.fbml.erb.tpl new file mode 100644 index 0000000..2bfae6a --- /dev/null +++ b/handle_iframe.fbml.erb.tpl @@ -0,0 +1 @@ +<img src="<%=@track_page_view_url%>" width=1 height=1 /> \ No newline at end of file diff --git a/handle_iframe.html.erb.tpl b/handle_iframe.html.erb.tpl new file mode 100644 index 0000000..2bfae6a --- /dev/null +++ b/handle_iframe.html.erb.tpl @@ -0,0 +1 @@ +<img src="<%=@track_page_view_url%>" width=1 height=1 /> \ No newline at end of file diff --git a/init.rb b/init.rb new file mode 100644 index 0000000..e494bea --- /dev/null +++ b/init.rb @@ -0,0 +1,57 @@ +# Kontagent facebooker version 0.1.6 + +puts "loading kt..." + +require 'facebook/session' + + +require 'kt/rails/helpers' + +require 'facebooker/rails/publisher' +require 'facebook/rails/publisher' +#require 'facebooker/rails/controller' +require 'facebook/rails/controller' +require 'kt/rails/controller' + +config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") + +if config['mode'] == 'async' + require 'starling' + require 'starling_ext' + + require 'kt/queue/queue' + require 'kt/queue/processor' + require 'kt/queue/task' + + # Load app applicable Kontagent::Queue::Processor subclasses from app/processors + Dir[RAILS_ROOT + '/app/processors/*.rb'].each do |file| + require file + end +end + +module ::ActionController + class Base + def self.inherited_with_kt(subclass) + inherited_without_kt(subclass) + + if subclass.to_s == "ApplicationController" + subclass.class_eval do + subclass.send(:include,Kt::Rails::Controller) + end + end + + end #def + + class << self + alias_method_chain :inherited, :kt + end + + end +end + + +ActionView::Base.send :include, Kt::Rails::KontagentHelpers + + + + diff --git a/install.rb b/install.rb new file mode 100644 index 0000000..570c7f9 --- /dev/null +++ b/install.rb @@ -0,0 +1,20 @@ +# Kontagent facebooker version 0.1.6 +# Install hook code here +require 'fileutils' +require 'rubygems' +#require 'ruby-debug' #xxx + +if ARGV.size != 2 + puts "Failure: you need to pass in the controller_name" +else + controller_name = ARGV[1] + handle_iframe_html_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.html.erb") + handle_iframe_fbml_dst = File.join(RAILS_ROOT, "app", "views", controller_name, "handle_iframe.fbml.erb") + kontagent_yml_dst = File.join(RAILS_ROOT, "config", "kontagent.yml") + + puts "copying kontagent.yml.erb to #{kontagent_yml_dst}" + FileUtils.cp( File.join(RAILS_ROOT, "vendor", "plugins", "kt", 'kontagent.yml.tpl'), + kontagent_yml_dst ) unless File.exists?( kontagent_yml_dst ) +end + + diff --git a/kontagent.yml.tpl b/kontagent.yml.tpl new file mode 100644 index 0000000..4d2b5c5 --- /dev/null +++ b/kontagent.yml.tpl @@ -0,0 +1,130 @@ +# Parameter: kt_api_key +# +# Description: App-specific Kontagent API key found in the "Account" section +# of the Kontagent website. Must be unique for each application +# that you want to track. (32 character hex number) +# +kt_api_key: 00000000000000000000000000000000 + +# Parameter: kt_secret_key +# +# Description: Kontagent secret key for the app you specified with the +# KT_API_KEY parameter. The secret key is found in the same +# location on the Kontagent website as the KT_API_KEY. (32 +# character hex number). +# +kt_secret_key: 00000000000000000000000000000000 + + + +# Parameter: canvas_page_name +# +# Description: The canvas page name that you have specified on Facebook's +# application configuration page. For example, if your +# application's full canvas page URL is apps.facebook.com/yourapp, +# this value should be set to 'yourapp'. +# +# Example: yourapp +# +canvas_page_name : + + +# Parameter: call_back_host +# +# Description: The call_back_host value is the host name component of your +# application's callback URL. For example, if your callback URL is +# www.example.com/myapp, this value should be set to +# www.example.com. This value MUST start with 'http://'. +# +# Example: http://your.callback.host +# +call_back_host: + +# Parameter: call_back_req_uri +# +# Description: The call_back_req_uri value is the path component of your +# application's callback URL. For example, if your callback URL is +# www.example.com/myapp, this value should be set to '/myapp'. Note +# that this value must start with a '/'. +# +# Example: /your_app_uri +# +call_back_req_uri: + + +# Parameter: use_test_server +# +# Description: Kontagent has a test server that data can be sent to during the +# initial instrumentation phase to verify that an application has +# been instrumented properly. The Kontagent website provides an +# interface to this test server, which shows the number of +# different types of messages that have been received in the last +# three hours and the parameters associated with the last 10 +# messages received. This can be used to resolve any instrumentation +# issues you may encounter. +# +# The test server can be accessed on the Kontagent website by +# logging in and then clicking on "Support", "Tools", "Test Server". +# +# If it is set to true, kt_host_test will be used. If it's set to +# false, kt_host, will be used. +# ************************** IMPORTANT *************************** +# The data sent to the test server IS NOT SAVED PERMANENTLY AND +# IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE +# SERVER. The test server is merely intended as a test tool and +# must be disabled to capture data that can later be viewed in the +# regular dashboard. +# ************************** IMPORTANT *************************** +use_test_server: false + +############################################################################### +# starling configuration # +############################################################################### + +# Parameter: mode +# +# Valid values: async, sync +# +# Description: Set the mode to to 'async' to use the starling queue for +# outgoing Kontagent traffic. Set it to 'sync' to disable the use +# of the starling queue. NOTE: see the documentation on +# Kontagent's websites for instructions on how to install +# starling, if necessary. +# +mode: sync + +# Parameter: queue_address +# +# Description: Set the [ip]:[port] used by your starling queue installation. +# This value will be ignored if 'mode' is set to 'sync'. +# +# Example: 127.0.0.1:22122 +# +queue_address: + + +############################################################################### +# DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # +# SPECIFICALLY TOLD BY KONTAGENT TO DO SO # +############################################################################### + +# Parameter: kt_host +# +# Description: The name of the Kontagent API server to which data is sent. Do +# NOT change this value. +# +kt_host: api.kontagent.com + +# Parameter: kt_url +# +# Description: The path on the Kontagent API server that is used to collect the +# analytics data. Do NOT change this value. +# +kt_url: /api + +# Parameter: kt_host_test +# +# Description: The name of the Kontagent test server to which data is sent when +# the test mode is enabled. Do NOT change this value. +# +kt_host_test: api.test.kontagent.net diff --git a/kontagent.yml.tpl.multi b/kontagent.yml.tpl.multi new file mode 100644 index 0000000..fcfa395 --- /dev/null +++ b/kontagent.yml.tpl.multi @@ -0,0 +1,131 @@ +<FACEBOOK_API_KEY>: + # Parameter: kt_api_key + # + # Description: App-specific Kontagent API key found in the "Account" section + # of the Kontagent website. Must be unique for each application + # that you want to track. (32 character hex number) + # + kt_api_key: 00000000000000000000000000000000 + + # Parameter: kt_secret_key + # + # Description: Kontagent secret key for the app you specified with the + # KT_API_KEY parameter. The secret key is found in the same + # location on the Kontagent website as the KT_API_KEY. (32 + # character hex number). + # + kt_secret_key: 00000000000000000000000000000000 + + + + # Parameter: canvas_page_name + # + # Description: The canvas page name that you have specified on Facebook's + # application configuration page. For example, if your + # application's full canvas page URL is apps.facebook.com/yourapp, + # this value should be set to 'yourapp'. + # + # Example: yourapp + # + canvas_page_name : + + + # Parameter: call_back_host + # + # Description: The call_back_host value is the host name component of your + # application's callback URL. For example, if your callback URL is + # www.example.com/myapp, this value should be set to + # www.example.com. This value MUST start with 'http://'. + # + # Example: http://your.callback.host + # + call_back_host: + + # Parameter: call_back_req_uri + # + # Description: The call_back_req_uri value is the path component of your + # application's callback URL. For example, if your callback URL is + # www.example.com/myapp, this value should be set to '/myapp'. Note + # that this value must start with a '/'. + # + # Example: /your_app_uri + # + call_back_req_uri: + + + # Parameter: use_test_server + # + # Description: Kontagent has a test server that data can be sent to during the + # initial instrumentation phase to verify that an application has + # been instrumented properly. The Kontagent website provides an + # interface to this test server, which shows the number of + # different types of messages that have been received in the last + # three hours and the parameters associated with the last 10 + # messages received. This can be used to resolve any instrumentation + # issues you may encounter. + # + # The test server can be accessed on the Kontagent website by + # logging in and then clicking on "Support", "Tools", "Test Server". + # + # If it is set to true, kt_host_test will be used. If it's set to + # false, kt_host, will be used. + # ************************** IMPORTANT *************************** + # The data sent to the test server IS NOT SAVED PERMANENTLY AND + # IS KEPT SEPARATE FROM THE DATA SENT TO THE REGULAR DATA CAPTURE + # SERVER. The test server is merely intended as a test tool and + # must be disabled to capture data that can later be viewed in the + # regular dashboard. + # ************************** IMPORTANT *************************** + use_test_server: false + +############################################################################### +# starling configuration # +############################################################################### + +# Parameter: mode +# +# Valid values: async, sync +# +# Description: Set the mode to to 'async' to use the starling queue for +# outgoing Kontagent traffic. Set it to 'sync' to disable the use +# of the starling queue. NOTE: see the documentation on +# Kontagent's websites for instructions on how to install +# starling, if necessary. +# +mode: sync + +# Parameter: queue_address +# +# Description: Set the [ip]:[port] used by your starling queue installation. +# This value will be ignored if 'mode' is set to 'sync'. +# +# Example: 127.0.0.1:22122 +# +queue_address: + + +############################################################################### +# DO NOT CHANGE VALUES BELOW THIS LINE UNLESS # +# SPECIFICALLY TOLD BY KONTAGENT TO DO SO # +############################################################################### + +# Parameter: kt_host +# +# Description: The name of the Kontagent API server to which data is sent. Do +# NOT change this value. +# +kt_host: api.kontagent.com + +# Parameter: kt_url +# +# Description: The path on the Kontagent API server that is used to collect the +# analytics data. Do NOT change this value. +# +kt_url: /api + +# Parameter: kt_host_test +# +# Description: The name of the Kontagent test server to which data is sent when +# the test mode is enabled. Do NOT change this value. +# +kt_host_test: api.test.kontagent.net diff --git a/lib/facebook/rails/controller.rb b/lib/facebook/rails/controller.rb new file mode 100644 index 0000000..e6a35ef --- /dev/null +++ b/lib/facebook/rails/controller.rb @@ -0,0 +1,25 @@ +# Kontagent facebooker version 0.1.6 +require 'kt/kt_analytics' + +module Facebooker + module Rails + module Controller + + def application_is_not_installed_by_facebook_user_with_kontagent + if request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri || + (request.request_uri == Kt::KtAnalytics.instance.m_call_back_req_uri + "/") + redirect_to session[:facebook_session].install_url + else + local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri + matches = request.request_uri.match(/#{local_req_uri}\/(.*)/) + redirect_to session[:facebook_session].install_url(:next =>"#{matches[1]}") + end + end #application_is_not_installed_by_facebook_user_with_kontagent + + alias_method_chain :application_is_not_installed_by_facebook_user, :kontagent + end #module Controller + + end +end + + diff --git a/lib/facebook/rails/publisher.rb b/lib/facebook/rails/publisher.rb new file mode 100644 index 0000000..150e15e --- /dev/null +++ b/lib/facebook/rails/publisher.rb @@ -0,0 +1,62 @@ +# Kontagent facebooker version 0.1.6 +module Facebooker + module Rails + class Publisher + + def template(arg) + @template = arg + end + + def subtype1(arg) + @subtype1 = arg + end + + def subtype2(arg) + @subtype2 = arg + end + + + def send_message_with_kontagent(method) + @recipients = @recipients.is_a?(Array) ? @recipients : [@recipients] + if from.nil? and @recipients.size==1 and ! announcement_notification?(from,_body) + @from = @recipients.first + end + # notifications can + # omit the from address + raise InvalidSender.new("Sender must be a Facebooker::User") unless from.is_a?(Facebooker::User) || announcement_notification?(from,_body) + case _body + when Facebooker::Feed::TemplatizedAction,Facebooker::Feed::Action + from.publish_action(_body) + when Facebooker::Feed::Story + @recipients.each {|r| r.publish_story(_body)} + when Notification + (from.nil? ? Facebooker::Session.create : from.session).send_notification(@recipients,_body.fbml, nil, @from, @template, @subtype1, @subtype2) + when Email + from.session.send_email(@recipients, + _body.title, + _body.text, + _body.fbml, + @template, + @subtype1, + @subtype2) + when Profile + # If recipient and from aren't the same person, create a new user object using the + # userid from recipient and the session from from + if @from != @recipients.first + @from = Facebooker::User.new(Facebooker::User.cast_to_facebook_id(@recipients.first),from.session) + end + from.set_profile_fbml(_body.profile, _body.mobile_profile, _body.profile_action, _body.profile_main) + when Ref + @from.session.server_cache.set_ref_handle(_body.handle,_body.fbml) + when UserAction + @from.session.publish_user_action(_body.template_id || FacebookTemplate.for(method) ,_body.data,_body.target_ids,_body.body_general) + else + raise UnspecifiedBodyType.new("You must specify a valid send_as") + end + end + + alias_method_chain :send_message, :kontagent + + end + end +end diff --git a/lib/facebook/session.rb b/lib/facebook/session.rb new file mode 100644 index 0000000..4e28dd5 --- /dev/null +++ b/lib/facebook/session.rb @@ -0,0 +1,94 @@ +# Kontagent facebooker version 0.1.6 +require 'kt/kt_analytics' + +module Facebooker + class Session + def send_notification_with_kontagent(user_ids, fbml, email_fbml = nil, source_user = nil, template_id = nil, st1 = nil, st2 = nil) + uuid,fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nt, template_id, st1, st2) + + r = send_notification_without_kontagent(user_ids, fbml, email_fbml) + + if !r.blank? + arg_hash = { + #'s' => @user.id.to_s, + 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, + 'u' => uuid + } + + if source_user.nil? + arg_hash['s'] = 0.to_s + else + arg_hash['s'] = source_user.id.to_s + end + + arg_hash['t'] = template_id.to_s unless template_id.nil? + + Kt::KtAnalytics.instance.kt_outbound_msg('nts', arg_hash) + end + end + + def send_email_with_kontagent(user_ids, subject, text, fbml = nil, template_id = nil, st1 = nil, st2 = nil) + if fbml != nil + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(fbml, :nte, + template_id, st1, st2) + else + uuid = Kt::KtAnalytics.instance.gen_long_uuid + end + + r = send_email_without_kontagent(user_ids, subject, text, fbml) + + if !r.blank? + arg_hash = { + 's' => @user.id.to_s , + 'r' => user_ids.is_a?(Array) ? user_ids * "," : user_ids, + 'u' => uuid + } + + arg_hash['t'] = template_id.to_s unless template_id.nil? + + Kt::KtAnalytics.instance.kt_outbound_msg('nte', arg_hash) + end + + end + + def publish_user_action_with_kontagent(bundle_id,data={},target_ids=nil,body_general=nil, st1 = nil, st2 = nil) + if(data != nil) + data.each_pair do |key,value | + if key == :image + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link(value[:href], :fdp, + bundle_id, st1, st2) + value[:href] = fbml + data[key] = value # do we even need this line? + elsif key == :flash + + elsif key == :mp3 + Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) + elsif key == :video + + else + uuid, fbml = Kt::KtAnalytics.instance.gen_kt_comm_link_no_href(value, :fdp, bundle_id, st1, st2) + data[key] = fbml + end + end + end + + r = publish_user_action_without_kontagent(bundle_id, data, target_ids, body_general) + + if !r.blank? + arg_hash = { + 'pt' => 4, + 's' => @user.id.to_s, + 't' => bundle_id + } + + Kt::KtAnalytics.instance.kt_outbound_msg('fdp', arg_hash) + end + + end + + alias_method_chain :send_notification, :kontagent + alias_method_chain :send_email, :kontagent + alias_method_chain :publish_user_action, :kontagent + + end +end diff --git a/lib/kt.rb b/lib/kt.rb new file mode 100644 index 0000000..671be90 --- /dev/null +++ b/lib/kt.rb @@ -0,0 +1 @@ +# Kt diff --git a/lib/kt/kt_analytics.rb b/lib/kt/kt_analytics.rb new file mode 100644 index 0000000..184ef00 --- /dev/null +++ b/lib/kt/kt_analytics.rb @@ -0,0 +1,464 @@ +# Kontagent facebooker version 0.1.6 + +require 'kt/kt_comm_layer' +require 'kt/queue/task' +require 'digest/md5' +#require 'ruby-debug' + +module Kt + class KtAnalytics + @@URL_REGEX_STR = /(href\s*=.*?)(https?:\/\/[^\s>\'"]+)/ #matches all the urls + @@URL_WITH_NO_HREF_REGEX_STR = /(https?:\/\/[^\s>\'"]+)/ #matches all the urls + @@S_undirected_types = {:pr=>:pr, :fdp=>:fdp, :ad=>:ad, :ap=>:ap} + @@S_directed_types = {:in=>:in, :nt=>:nt, :nte=>:nte} + @@S_kt_args = {:kt_uid=>1, :kt_d=>1, :kt_type=>1, :kt_ut=>1, :kt_t=>1, :kt_st1=>1, :kt_st2=>1} + @@S_install_args = {:d=>1, :ut=>1, :installed=>1, :sut=>1} + + @@S_directed_val = 'd'; + @@S_undirected_val = 'u'; + @@instance_obj = nil + + attr_reader :m_comm, :m_kt_api_key, :m_canvas_name, :m_call_back_req_uri, :m_call_back_host, :m_kt_host, :m_kt_host_port, :m_kt_host_url + + def self.instance() + if @@instance_obj == nil + @@instance_obj = new + @@instance_obj.init + end + return @@instance_obj + end + + def self.kt_args?(arg) + if @@S_kt_args.has_key? arg + return true + else + return false + end + end + + def self.install_args?(arg) + if @@S_install_args.has_key? arg + return true + else + return false + end + end + + def get_fb_param(request_params, param_name) + r = 0 + if request_params.has_key?('fb_sig_' + param_name) + r = request_params['fb_sig_'+param_name] + elsif request_params.has_key?(Facebooker.api_key+"_"+param_name) + r = request_params[Facebooker.api_key+"_"+param_name] + end + return r + end + + private + def initialize() + + end + + def init_from_conf(custom_conf = nil) + @config = YAML::load_file("#{RAILS_ROOT}/config/kontagent.yml") + @config.merge! custom_conf if custom_conf + + #figure out the port + if @config.has_key? $CURR_API_KEY + app_config_map = @config[$CURR_API_KEY] + else + app_config_map = @config + end + + if app_config_map['use_test_server'] == true + if @config['kt_host_test_port'].blank? or @config['kt_host_test_port'].nil? + @m_kt_host_port = 80 + else + @m_kt_host_port = @config['kt_host_port'] + end + else + if @config['kt_host_port'].blank? or @config['kt_host_port'].nil? + @m_kt_host_port = 80 + else + @m_kt_host_port = @config['kt_host_port'] + end + end + + # figure out the host + if app_config_map['use_test_server'] == true + @m_kt_host = @config['kt_host_test'] + else + @m_kt_host = @config['kt_host'] + end + + if @m_kt_host_port != 80 + @m_kt_host_url = "#{@m_kt_host}:#{@m_kt_host_port}" + else + @m_kt_host_url = "#{@m_kt_host}" + end + + @m_kt_url = @config['kt_url'] + + @m_kt_api_key = app_config_map['kt_api_key'].to_s + @m_kt_secret_key = app_config_map['kt_secret_key'].to_s + @m_canvas_name = app_config_map['canvas_page_name'] + + @m_call_back_req_uri = app_config_map['call_back_req_uri'] + @m_call_back_host = app_config_map['call_back_host'] + @m_mode = (@config['mode'] == 'async') ? :async : :sync + @m_timeout = @config['timeout'].blank? ? 1 : @config['timeout'].to_i + end + + public + def init(custom_conf = nil) + init_from_conf(custom_conf) + @m_comm = Kt::KtComm.instance(@m_kt_host, @m_kt_host_port) + end + + def append_kt_query_str(original_url, query_str) + if original_url =~ /\?/ + return original_url + "&" + query_str + else + if query_str == nil || query_str == "" + return original_url + else + return original_url + "?" + query_str + end + end + end + + def get_page_tracking_url(fb_user_id) + arg_hash = {} + arg_hash['s'] = fb_user_id + + @m_comm.get_call_url(@m_kt_url, "v1", + @m_kt_api_key, @m_kt_secret_key, + "pgr", + arg_hash) + end + + def get_invite_post_link_and_uuid(post_link, uid, template_id) + uuid = gen_long_uuid + url = get_invite_post_link(post_link, uid, uuid, template_id) + return url, uuid + end + + def get_invite_post_link(post_link, uid, uuid, template_id) + arg_hash = {} + arg_hash['kt_ut'] = uuid + + arg_hash['kt_uid'] = uid + arg_hash['kt_type'] = 'ins' + + if template_id != nil + arg_hash['kt_t'] = template_id + end + + r_url = append_kt_query_str(post_link, arg_hash.to_query) + + return r_url + end + + + def get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) + arg_hash = {} + arg_hash['kt_uid'] = uid + arg_hash['kt_ut'] = uuid + arg_hash['kt_type'] = 'in' + arg_hash['kt_d'] = @@S_directed_val + + if template_id != nil + arg_hash['kt_t'] = template_id + end + if subtype1 != nil + arg_hash['kt_st1'] = subtype1 + end + if subtype2 != nil + arg_hash['kt_st2'] = subtype2 + end + + r_url = append_kt_query_str(content_link, arg_hash.to_query) + return r_url + end + + + def get_invite_content_link_and_uuid(content_link, uid, template_id, subtype1, subtype2) + uuid = gen_long_uuid + url = get_invite_content_link(content_link, uid, uuid, template_id, subtype1, subtype2) + return url, uuid + end + + + def gen_kt_comm_link(input_txt, comm_type, template_id, subtype1, subtype2) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + input_txt = input_txt.gsub(@@URL_REGEX_STR){|match| + if $1.nil? + append_kt_query_str($2, query_str) + else + $1 + append_kt_query_str($2, query_str) + end + } + return uuid,input_txt + end #gen_kt_comm_link + + def gen_kt_comm_link_no_href(input_txt, comm_type, template_id, subtype1, subtype2) + uuid,query_str = gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + input_txt = input_txt.gsub(@@URL_WITH_NO_HREF_REGEX_STR){|match| + if $1.nil? + input_txt + else + append_kt_query_str($1, query_str) + end + } + return uuid, input_txt + end #gen_kt_comm_link_no_href + + def send_user_data_impl(user) + time("making API calls for Kontagent user data") do + arg_hash = {} + + if !user.birthday.blank? && user.birthday != '' + arg_hash['b'] = user.birthday + end + if !user.sex.blank? && user.sex != '' + arg_hash['g'] = user.sex + end + + # if !user.current_location.city.blank? &&user.current_location.city != '' + # arg_hash['ly'] = user.current_location.city + # end + # if !user.current_location.state.blank? && user.current_location.state != '' + # arg_hash['ls'] = user.current_location.state + # end + # if !user.current_location.country.blank? && user.current_location.country != '' + # arg_hash['lc'] = user.current_location.country + # end + # if !user.current_location.zip.blank? && user.current_location.zip != '' + # arg_hash['lp'] = user.current_location.zip + # end + # + # + # if !user.hometown_location.city.blank? &&user.hometown_location.city != '' + # arg_hash['ly'] = user.hometown_location.city + # end + # if !user.hometown_location.state.blank? && user.hometown_location.state != '' + # arg_hash['ls'] = user.hometown_location.state + # end + # if !user.hometown_location.country.blank? && user.hometown_location.country != '' + # arg_hash['lc'] = user.hometown_location.country + # end + # if !user.hometown_location.zip.blank? && user.hometown_location.zip != '' + # arg_hash['lp'] = user.hometown_location.zip + # end + + arg_hash['f'] = user.friends.size.to_s + # RAILS_DEFAULT_LOGGER.warn arg_hash.inspect # LOCAL + end + + kt_outbound_msg('cpu', arg_hash) + return true + end + + def send_user_data(user) + #sex', 'birthday', 'current_location', 'hometown_location + if @m_mode == :async + data_hash ={ + :qtype => :capture_user_data, + :user => Marshal.dump(user) + } + Kt::Queue::Task.publish :record, data_hash + else + send_user_data_impl(user) + end + + end + + def save_app_removed(uid) + arg_hash = {'s'=>uid} + kt_outbound_msg('apr', arg_hash) + end + + + def save_app_added(request_params) + has_direction = false + if request_params[:d] != nil + has_direction = true + end + + arg_hash = {} + + arg_hash['s'] = get_fb_param(request_params, 'user') + + if has_direction == true and request_params[:d] == @@S_directed_val + arg_hash['u'] = request_params[:ut] + kt_outbound_msg('apa', arg_hash) + elsif has_direction == true and request_params[:d] == @@S_undirected_val + arg_hash['su'] = request_params[:sut] + kt_outbound_msg('apa', arg_hash) + else # no viral + kt_outbound_msg('apa', arg_hash) + end + end + + def save_invite_send(request_params) + arg_hash = {} + arg_hash['s'] = request_params[:kt_uid] + arg_hash['r'] = request_params[:ids].is_a?(Array) ? request_params[:ids] * "," : request_params[:ids] + arg_hash['u'] = request_params[:kt_ut] + if request_params['kt_t'] != nil + arg_hash['t'] = request_params[:kt_t] + end + kt_outbound_msg('ins', arg_hash) + end + + def save_invite_click(request_params) + arg_hash = {} + arg_hash['i'] = get_fb_param(request_params, 'added') + arg_hash['u'] = request_params[:kt_ut] + arg_hash['tu'] = 'inr' + + if request_params[:kt_t] != nil + arg_hash['t'] = request_params[:kt_t] + end + if request_params[:kt_st1] != nil + arg_hash['st1'] = request_params[:kt_st1] + end + if request_params[:kt_st2] != nil + arg_hash['st2'] = request_params[:kt_st2] + end + kt_outbound_msg('inr', arg_hash) + end + + + def save_notification_click(request_params) + msg_type = 'ntr' + arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) + kt_outbound_msg(msg_type, arg_hash) + end + + def save_notification_email_click(request_params) + msg_type = 'nei' + arg_hash = construct_arg_hash_for_click_event_helper(msg_type, request_params) + kt_outbound_msg(msg_type, arg_hash) + end + + def save_undirected_comm_click(request_params) + msg_type = 'ucc' + arg_hash = {} + arg_hash['t'] = request_params[:kt_t] unless request_params[:kt_t] == nil + arg_hash['st1'] = request_params[:kt_st1] unless request_params[:kt_st1] == nil + arg_hash['st2'] = request_params[:kt_st2] unless request_params[:kt_st2] == nil + arg_hash['tu'] = request_params[:kt_type] + arg_hash['s'] = get_fb_param(request_params, 'user') + short_tag = gen_short_uuid + arg_hash['su'] = short_tag + arg_hash['i'] = get_fb_param(request_params, 'added') + kt_outbound_msg(msg_type, arg_hash) + return short_tag + end + + def kt_outbound_msg(type, arg_hash) + time("sending Kontagent message (#{arg_hash.inspect})") do + if @m_mode == :async + #timeout(@m_timeout) do + data_hash = { + :qtype => :kt_outbound, + :ctype => type, + :v => 'v1', + :kt_api_key => @m_kt_api_key, + :kt_secret_key => @m_kt_secret_key, + :kt_call_back_host => @m_kt_host, + :kt_call_back_port => @m_kt_host_port, + :kt_url => @m_kt_url, + :arg_hash => arg_hash, + } + Kt::Queue::Task.publish :record, data_hash + #end + else + @m_comm.api_call_method(@m_kt_url, 'v1', @m_kt_api_key, @m_kt_secret_key, type, arg_hash) + end + end + end + + # It's more secure to have 32 characters + def gen_long_uuid() + CGI::Session.generate_unique_id('kontagent') + end + + private + def construct_arg_hash_for_click_event_helper(msg_type, request_params) + arg_hash = {} + arg_hash['tu'] = msg_type + arg_hash['i'] = get_fb_param(request_params, 'added') + if request_params.has_key? 'kt_ut' + arg_hash['u'] = request_params[:kt_ut] + end + if request_params.has_key? 'kt_t' + arg_hash['t'] = request_params[:kt_t] + end + if request_params.has_key? 'kt_st1' + arg_hash['st1'] = request_params[:kt_st1] + end + if request_params.has_key? 'kt_st2' + arg_hash['st2'] = request_params[:kt_st2] + end + uid = get_fb_param(request_params, 'user') + if uid != 0 + arg_hash['r'] = uid + end + return arg_hash + end + + def gen_short_uuid() + gen_long_uuid[0...8] + end + + def directed_type?(comm_type) + @@S_directed_types.has_key?(comm_type) + end + + def undirected_type?(comm_type) + @@S_undirected_types.has_key?(comm_type) + end + + + def gen_kt_comm_query_str(comm_type, template_id, subtype1, subtype2) + param_array = {} + uuid = 0 + + if comm_type != nil + if directed_type? comm_type + dir_val = @@S_directed_val + elsif undirected_type? comm_type + dir_val = @@S_undirected_val + else + # profile? + end + end + + param_array[:kt_d] = dir_val + param_array[:kt_type] = comm_type + + if dir_val == @@S_directed_val + uuid = gen_long_uuid() + param_array[:kt_ut] = uuid + end + + if template_id != nil + param_array[:kt_t] = template_id.to_s + end + + if subtype1 != nil + param_array[:kt_st1] = subtype1 + end + + if subtype2 != nil + param_array[:kt_st2] = subtype2 + end + + return uuid, param_array.to_query + end #gen_kt_comm_query_str + + end #Kt_Analytics + +end#mdoule diff --git a/lib/kt/kt_comm_layer.rb b/lib/kt/kt_comm_layer.rb new file mode 100644 index 0000000..4fd292e --- /dev/null +++ b/lib/kt/kt_comm_layer.rb @@ -0,0 +1,143 @@ +# Kontagent facebooker version 0.1.6 +#require 'socket' +require 'net/http' +#require 'timeout' +require 'cgi' +require 'uri' +require 'digest/md5' +#require 'benchmark' +include Socket::Constants + + +module Kt + class KtComm + @@instance_obj = nil + private + def initialize(host, port) + puts "initializing KtComm" + @m_host = host + @m_port = port + end + + public + def self.instance(host, port) + if @@instance_obj == nil + @@instance_obj = new(host, port) + end + return @@instance_obj + end + + # kt_api_url : excludes the host name. + # version : example, v1, v2, etc. + # api_key : kontagent's api key is used to uniquely identify the user. + # secret_key : kontagent's secret key + # api_func : example, ins for "invite sent", inr for "invite clicked", etc + # arg_assoc_hash : an associative hash of argument list. + def api_call_method(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) + +# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) +# url_path = "http://"+@m_host+":"+@m_port.to_s+url_path +# uri = URI.parse(url_path) +# Net::HTTP.get(uri) + socket = Socket.new(AF_INET, SOCK_STREAM, 0) + sockaddr = Socket.sockaddr_in(@m_port, @m_host) + + connected = true + + #puts Benchmark.measure{ + begin + socket.connect_nonblock(sockaddr) + rescue Errno::EINPROGRESS + IO.select(nil, [socket]) + begin + socket.connect_nonblock(sockaddr) + rescue Errno::EISCONN + connected = false + puts "Errno::EISCONN!!" + end + end + #} + + if connected + url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) + + buf = "GET " + url_path + " HTTP/1.1\r\n" + buf << "Host:" + @m_host + "\r\n" + buf << "Content-type: application/x-www-form-urlencoded\r\n" + buf << "Accept: */*\r\n" + buf << "\r\n" + buf << "\r\n" + + socket.write_nonblock buf + end + socket.close + + return connected +# socket = nil + +# puts @m_host +# begin +# timeout(2) do +# #socket = TCPSocket::new(@m_host, 80) #uncomment this +# socket = TCPSocket::new(@m_host, @m_port) +# end +# rescue Timeout::Error +# puts "timeout!!!" +# return +# rescue +# puts "tcp error!!!!" +# return +# end + +# if socket != nil +# url_path = get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) +# #puts "url_path: #{url_path}" #xxx + +# buf = "GET " + url_path + " HTTP/1.1\r\n" +# buf << "Host:" + @m_host + "\r\n" +# buf << "Content-type: application/x-www-form-urlencoded\r\n" +# buf << "Accept: */*\r\n" +# buf << "\r\n" +# buf << "\r\n" +# socket.write buf +# socket.close +# end + + # old code + # socket.write("GET " + url_path + " HTTP/1.1\r\n") + # socket.write("Host:" + @m_host + "\r\n") + # socket.write("Content-type: application/x-www-form-urlencoded\r\n") + # socket.write("Accept: */*\r\n") + # socket.write("\r\n") + # socket.write("\r\n") + # socket.close + #end + end + + def get_call_url(kt_api_url, version, api_key, secret_key, api_func, arg_assoc_hash) + sig = '' + arg_assoc_hash['ts'] = Time.now.to_s + + # This is to get rid of null parameters. in the assoc array + + keys = arg_assoc_hash.keys.sort + keys.each do |key| + sig += key+"="+arg_assoc_hash[key].to_s + end + + arg_assoc_hash['an_sig'] = Digest::MD5.hexdigest(sig) + + query = arg_assoc_hash.to_query + url_path = kt_api_url+"/"+version+"/"+api_key+"/"+api_func+"/?"+query + end + + end + +end + + +# test + +#comm = Kontagent::Kt_Comm.new('67.102.65.65') +#comm = Kontagent::Kt_Comm.new('10.0.0.0') +#comm.api_call_method('/api', 'test', '123','345', 'api_func', {'a'=>'foo'}) diff --git a/lib/kt/queue/processor.rb b/lib/kt/queue/processor.rb new file mode 100644 index 0000000..429a710 --- /dev/null +++ b/lib/kt/queue/processor.rb @@ -0,0 +1,84 @@ +# Kontagent facebooker version 0.1.6 + +module Kt + module Queue + LOST_CONNECTION_ERROR_MESSAGES = [ + "Server shutdown in progress", + "Broken pipe", + "Lost connection to MySQL server during query", + "MySQL server has gone away" + ] + + # An object not found proxy exception. This is used inside our generated getter methods + # to rescue ActiveRecord::RecordNotFound + class NotFound < Exception; end + + class Processor + def options + @task.options + end + + + # Takes a class name and returns and creates an accessor method and instance + # variable for it. If the class responds to find (i.e. ActiveRecord objects), then + # it tries to call it with the value of name_id extracted from the Task. + # If not, it creates a new instaces of the class, sets an instance variable with that name + # and returns it. + def self.processes(name) + name = name.to_s + define_method(name) do + ivar = instance_variable_get("@#{name}") + return ivar unless ivar.blank? + + object = Object.const_get(name.camelize) + + value = if object.respond_to?(:find) + begin + object.find(@task.options["#{name}_id".intern]) + + # We provide automatic ActiveRecord::RecordNotFound protection because this method + # useless without a correct instance of the model. + rescue ActiveRecord::RecordNotFound => rnf + raise Kt::NotFound, rnf.message + end + else + Object.const_get(name.camelize).send('new') + end + instance_variable_set("@#{name}", value) + + value + end + end + + # Runs the process method defined in the Processor subclass (in app/processors). + # Any error that is fatal should be rescued to avoid re-entry in to the queue. As a default, we rescue + # ActiveRecord::RecordNotFound (record not found). + # Subclasses of Processor should rescue any fatal errors specific to them in their own process method. + def process!(task) + @task = task + + tries = 0 + + begin + process + rescue ActiveRecord::StatementInvalid => sti + lost_connection = false + LOST_CONNECTION_ERROR_MESSAGES.each do |error| + lost_connection = true if sti.message =~ /#{error}/ + end + if lost_connection && tries == 0 + tries += 1 + ActiveRecord::Base.connection.reconnect! + + retry + end + + task.enqueue_with_error(sti) + rescue Kt::Queue::NotFound => notfound + rescue Exception => e + task.enqueue_with_error(e) + end + end + end + end +end diff --git a/lib/kt/queue/queue.rb b/lib/kt/queue/queue.rb new file mode 100644 index 0000000..2fb380e --- /dev/null +++ b/lib/kt/queue/queue.rb @@ -0,0 +1,183 @@ +# Kontagent facebooker version 0.1.6 +require 'starling' + + +module Kt + module Queue + class Queue + attr_reader :connection + + # Max number of reconnection attempts to starling + MAX_TRIES = 1 + + class << self + def queue + @queue ||= Queue.new + end + + def enqueue(priority, message) + queue.enqueue(priority, message) + end + + def process! + queue.process! + end + + def stop! + queue.stop! + end + # Statictics methods + def count_permanently_failed + queue.connection.sizeof("#{queue.config['canvas_page_name']}_p_0") + end + + def count + queue.connection.sizeof(:all).inject(0){|c, (k, v)| c+= v} + end + + # Use this method to see what's in the queue + def peek(priority, iterate = 1) + messages = [] + + iterate.times do + message = queue.connection.get("#{queue.config['canvas_page_name']}_p_#{priority}") + enqueue(priority, message) + + messages << message + end + + messages + end + + # You can use this method to define an external Proc (usually a lambda) that + # is sent a notification when a task fails more than the max allowed times. + # The lambda is passed the Kt::Queue::Task object, and the last Exception object. + # For example: + # Kt::Queue::Queue.failure_notification_observer = lambda {|task, error| + # Mailer.deliver_exception_mail(...) + # } + attr_accessor :failure_notification_observer + end + + def initialize + self.connect! + end + + def enqueue(priority, message) + if message[:action].blank? + error = "Tried to queue a task with an empty action. The message being queued was: #{message.inspect}" + Kt::Queue::Queue.log(error, true) + end + @current_message = message + value_with_retries do + @connection.set("#{config['canvas_page_name']}_p_#{priority}", message) + end + end + + def dequeue(priority) + @current_message = nil + value_with_retries do + @connection.get("#{config['canvas_page_name']}_p_#{priority}") + end + end + + # Loads the config file + def config + @config ||= YAML.load_file("#{RAILS_ROOT}/config/kontagent.yml") + end + + # Gets the next_item in the Queue + def next_item + result = nil + + 10.times do |i| + result = dequeue(i+1) + break unless result.blank? + end + result + end + + def flush + 10.times do |i| + result = @connection.flush("#{config['canvas_page_name']}_p_#{i+1}") + end + end + + # The main loop. It goes like this: + # 1. Calls process which: + # * calls next_item (returns nil or a task from the queue) + # * process returns false if next_item is nil + # * process creates a new task and calls process! on it + # 2. The loop continues + def process! + @running = true + while @running + result = process + + unless result + puts "Waiting..." if RAILS_ENV == "development" + GC.enable + GC.start + sleep 3 + end + + sleep 1 + end + end + + def stop! + @running = false + end + + def self.log(message, force=false) + RAILS_DEFAULT_LOGGER.send(force ? :error : :debug, message) + end + + protected + def connect! + Kt::Queue::Queue.log "Connecting on #{config['queue_address']}, canvas_page_name: #{config['canvas_page_name']}" + + @connection = Starling.new(config['queue_address']) + end + + # Gets an item from the queue if there is one, creates a task, and runs process! on it + def process + task = next_item + + Kt::Queue::Queue.log "Running #{task.inspect}..." + + task.blank? ? false : Kt::Queue::Task.from_message(task).process! + end + + def value_with_retries(&block) + tries = 0 + result = nil + + begin + result = yield + rescue MemCache::MemCacheError => e + Kt::Queue::Queue.log "Try ##{tries} - Starling Error: #{e.class} -> #{e}" + + connect! + + # If we can't connect to the server at all, we just put a line in the log file. + # This can be parsed later to write back to the queue if desired + if (tries += 1) > MAX_TRIES + unless @current_message.blank? + Kt::Queue::Queue.log("+++ #{Time.now.to_i} #{@current_message.inspect}", true) + if Kt::Queue::Queue.failure_notification_observer + Kt::Queue::Queue.failure_notification_observer.call(@current_message, e) + end + end + + return nil + end + + retry + end + + return result + end + end + end +end diff --git a/lib/kt/queue/task.rb b/lib/kt/queue/task.rb new file mode 100644 index 0000000..e7d8370 --- /dev/null +++ b/lib/kt/queue/task.rb @@ -0,0 +1,76 @@ +# Kontagent facebooker version 0.1.6 +require 'kt/queue/processor' +require 'kt/kt_comm_layer' + +class RecordProcessor < Kt::Queue::Processor + def process + op = options + qtype = op[:qtype] + if qtype == :kt_outbound + m_comm = Kt::KtComm.instance(op[:kt_call_back_host], op[:kt_call_back_port]) + m_comm.api_call_method(op[:kt_url], op[:v], op[:kt_api_key], op[:kt_secret_key], op[:ctype], op[:arg_hash]) + elsif qtype == :capture_user_data + Kt::KtAnalytics.instance.send_user_data_impl(Marshal.load(op[:user])) + end + end +end + +module Kt + module Queue + class Task + MAX_ERRORS = 3 + + attr_reader :options + + def process! + processor.new.process!(self) + end + + # Puts a failed Task back in the Queue with the lowest priority. + # If a task fails MAX_ERRORS times, it is put in Queue 0 which is never processed. + def enqueue_with_error(e) + @options[:failures] = @options[:failures].to_i + 1 + @options[:errors] ||= [] + + @options[:priority] = (@options[:failures] < MAX_ERRORS) ? 10 : 0 + Kt::Queue::Queue.enqueue(@options[:priority], @options.merge!({ + :action => @action, + :errors => @options[:errors] << {:class => e.class.to_s, :message => e.message} + })) + + Kt::Queue::Queue.log("Action '#{@action}' failed #{@options[:failures]} time(s).") + + # Send failure notification if a notification observer is defined + if @options[:priority] == 0 && Kt::Queue::Queue.failure_notification_observer + Kt::Queue::Queue.failure_notification_observer.call(self, e) + end + end + + # Puts actions in the Queue. Priority defaults to 5 + def self.publish(action, options={}) + priority = options[:priority] || 5 + options.merge!({:action => action}) + Kt::Queue::Queue.enqueue(priority, options) + end + + # Creates a Task from a message + def self.from_message(message) + action = message.delete :action + Task.new(action, message) + end + + def initialize(action, options = {}) + @action = action + @options = {:priority => 5}.merge(options) + end + + protected + # Infers a Processor's name from the action + + def processor + Object.const_get(@action.to_s.camelize + 'Processor') + end + end + + end +end diff --git a/lib/kt/rails/controller.rb b/lib/kt/rails/controller.rb new file mode 100644 index 0000000..f35d090 --- /dev/null +++ b/lib/kt/rails/controller.rb @@ -0,0 +1,183 @@ +# Kontagent facebooker version 0.1.6 +require 'kt/kt_analytics' +require 'facebooker' +#require 'ruby-debug' + +module Kt + module Rails + module Controller + + def self.included(controller) + controller.extend(ClassMethods) + #controller.before_filter(:capture_user_data) + controller.before_filter(:handle_kontagent, :except=>[:post_remove, :handle_iframe]) + controller.before_filter(:verify_uninstall_signature, :only=>[:post_remove]) + end + + # DEPRECATED : we don't use iframes to track page views anymore. + def handle_iframe + page_uri = params[:page_uri] + uid = params[:request_id] + end + + def post_remove + puts "calling post_remove..." + Kt::KtAnalytics.instance.save_app_removed(params[:fb_sig_user]) + render :nothing + end + + protected + def verify_uninstall_signature + puts "calling verify_uninstall_signature..." #xxx + signature = '' + keys = params.keys.sort + keys.each do |key| + next if key == 'fb_sig' + next unless key.include?('fb_sig') + key_name = key.gsub('fb_sig_', '') + signature += key_name + signature += '=' + signature += params[key] + end + signature += Facebooker.secret_key + calculated_sig = Digest::MD5.hexdigest(signature) + + if calculated_sig != params[:fb_sig] + #logger.warn "\n\nUNINSTALL :: WARNING :: expected signatures did not match\n\n" + return false + else + #logger.warn "\n\nUNINSTALL :: SUCCESS!! Signatures matched.\n" + post_remove # force calling post_remove + return true + end + end + + def capture_user_data + time(" capture user data") do + begin + user = session[:facebook_session].user + key = "KT_" + Facebooker.api_key + "_" + user.id.to_s + if cookies[key].blank? + Kt::KtAnalytics.instance.send_user_data(user) + end + cookies[key] = {:value => 1.to_s , :expires => 2.weeks.from_now} # 2 weeks + rescue + # invalid session key. + end + end + + return true + end + + def handle_kontagent + time("Handle kontagent") do + get_params = params + $CURR_API_KEY = request.parameters[:fb_sig_api_key] if $CURR_API_KEY.nil? + + # trace uninstall + if params.has_key? :fb_sig_uninstall + Kt::KtAnalytics.instance.save_app_removed(params) + return true + end + + # track install + if params.has_key? :installed and params[:installed] == "1" + Kt::KtAnalytics.instance.save_app_added(params) + end + + + short_tag=nil + if params.has_key? :kt_type + # handle kontagent related parameters + case params[:kt_type] + when "ins" # invite sent + Kt::KtAnalytics.instance.save_invite_send(params) + when "in" # invite click + Kt::KtAnalytics.instance.save_invite_click(params) + when "nt" # notification click + Kt::KtAnalytics.instance.save_notification_click(params) + when "nte" # email notification + Kt::KtAnalytics.instance.save_notification_email_click(params) + when "fdp" + short_tag = Kt::KtAnalytics.instance.save_undirected_comm_click(params) + else + + end + + # forward to the url without the kt_* params + f_url = get_stripped_kt_args_url(short_tag) + #puts "f_url \n\t #{f_url}" #xxx + redirect_to f_url + + else + return true + end + end + + end # handle_kontagent + + + private + def get_stripped_kt_args_url (short_tag = nil) + get_params = request.parameters + r_param_hash = {} + + get_params.each_pair do | get_key, get_val | + if Kt::KtAnalytics.kt_args?(get_key.intern) + if get_key == 'kt_d' + r_param_hash['d'] = get_val + elsif get_key == 'kt_ut' + r_param_hash['ut'] = get_val + end + params.delete(get_key) + elsif !get_key.include? "fb_sig" + r_param_hash[get_key] = get_val + end + end + + if short_tag != nil + r_param_hash['sut'] = short_tag + end + + return build_url(r_param_hash) + + end #get_stripped_kt_args_url + + def build_url(param_hash) + local_req_uri = Kt::KtAnalytics.instance.m_call_back_req_uri + matches = request.path.match(/#{local_req_uri}(.*)/) + + if matches == nil + puts "found NO match!!!" + r_url = "" + else + puts "found a match!!!" + puts "\t #{matches[1]}" + r_url = matches[1] + if r_url == "/" + r_url = "" + end + end + + +# puts "local_req_uri \n\t#{Kt::KtAnalytics.instance.m_call_back_req_uri}" +# puts "canvas_name \n\t #{Kt::KtAnalytics.instance.m_canvas_name}" +# puts "request.request_uri \n\t #{request.request_uri}" +# puts "param_hash \n\t #{param_hash.to_query}" +# puts "return_url \n\t#{Kt::KtAnalytics.instance.append_kt_query_str(r_url, param_hash.to_query)}" + + r_url = Kt::KtAnalytics.instance.append_kt_query_str("/"+Kt::KtAnalytics.instance.m_canvas_name+r_url, + param_hash.to_query) + #puts "final_url \n\t#{r_url}" + + return r_url + end + + module ClassMethods + + end + + + end + end +end diff --git a/lib/kt/rails/helpers.rb b/lib/kt/rails/helpers.rb new file mode 100644 index 0000000..c802583 --- /dev/null +++ b/lib/kt/rails/helpers.rb @@ -0,0 +1,60 @@ +# Kontagent facebooker version 0.1.6 + +require 'kt/kt_analytics' +require 'cgi' + +module Kt + module Rails + module KontagentHelpers + + def kt_get_invite_post_link(invite_post_link, template_id=nil) + url = nil + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + + if session['invite_uuid'] == nil + url, uuid = Kt::KtAnalytics.instance.get_invite_post_link_and_uuid(invite_post_link, + uid, + template_id) + session['invite_uuid'] = uuid + else + url = Kt::KtAnalytics.instance.get_invite_post_link(invite_post_link, + uid, + session['invite_uuid'], + template_id) + session['invite_uuid'] = nil + end + return url + end + + def kt_get_invite_content_link(invite_content_link, template_id = nil, subtype1 = nil, subtype2 = nil) + url = nil + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + + if session['invite_uuid'] == nil + url, uuid = Kt::KtAnalytics.instance.get_invite_content_link_and_uuid(invite_content_link, + uid, + template_id, + subtype1,subtype2) + session['invite_uuid'] = uuid + else + url = Kt::KtAnalytics.instance.get_invite_content_link(invite_content_link, + uid, + session['invite_uuid'], + template_id, + subtype1,subtype2) + session['invite_uuid'] = nil + end + return url + end + + def kt_track_page_view() + uid = Kt::KtAnalytics.instance.get_fb_param(params, 'user') + url_str = Kt::KtAnalytics.instance.get_page_tracking_url(uid) + track_code_str = "<img src='http://#{Kt::KtAnalytics.instance.m_kt_host_url}#{url_str}' width='0px' height='0px' />" + return track_code_str + end + + end + + end +end diff --git a/lib/starling_ext.rb b/lib/starling_ext.rb new file mode 100644 index 0000000..6655041 --- /dev/null +++ b/lib/starling_ext.rb @@ -0,0 +1,7 @@ +# Kontagent facebooker version 0.1.6 +# An extension to the Starling class from Twitter's (www.twitter.com) starling (http://rubyforge.org/projects/starling) gem. +class Starling + def get(*args) + super(*args) + end +end \ No newline at end of file diff --git a/script/queue_processor b/script/queue_processor new file mode 100755 index 0000000..2b1c7e4 --- /dev/null +++ b/script/queue_processor @@ -0,0 +1,233 @@ +#!/usr/bin/env ruby +require 'optparse' +require 'etc' + +module Kontagent + class ProcessManager + SIGNALS = { + 'HUP' => :reload, + 'INT' => :exit_now, + 'TERM' => :exit, + 'USR1' => :info, + 'USR2' => :restart, + 'SIGTRAP' => :breakpoint + } + + VERSION = '1.0.0' + + def initialize(options={}) + @pid_file = options[:pid_file] || "#{RAILS_ROOT}/tmp/pids/queue_processor.pid" + @log_file = options[:log_file] || "#{RAILS_ROOT}/log/queue_processor.log" + @options = options + end + + def start + SIGNALS.each do |signal, handler| + install_signal_handler(signal) + end + + if RAILS_ENV != "production" + puts "Starting Queue Processor #{RAILS_ENV} mode..." + puts "Log file: #{@log_file}" + puts "PID file: #{@pid_file}" + end + + # Become a daemon + if @options[:daemon] + Daemonize.daemonize(@log_file) + write_pid + change_privilege(@options[:user], @options[:group]) + end + + # The main loop + Kt::Queue::Queue.process! + end + + def stop + send_signal('TERM', @pid_file) + end + + def restart + stop + start + end + + private + def send_signal(signal, pid_file) + pid = File.read(pid_file).to_i + logger.info "Sending #{signal} to at PID #{pid}..." + begin + Process.kill(signal, pid) + rescue Errno::ESRCH + logger.info "Process does not exist. Not running." + end + end + + def stop_processor(signal, force=false) + logger.info "Signal #{signal} received. Terminating..." + Kt::Queue::Queue.stop! + delete_pid + exit + end + + def write_pid + File.open(@pid_file, "w") {|f| f.write(Process.pid)} + end + + def delete_pid + File.unlink @pid_file + end + + # Signal handling + def install_signal_handler(signal, handler = nil) + handler ||= method("#{SIGNALS[signal]}_handler").to_proc + trap(signal, handler) + rescue ArgumentError + logger.warn "Kontagent Queue Processor: Ignoring unsupported signal #{signal}." + end + + # def with_signal_handler(signal) + # install_signal_handler(signal) + # yield + # ensure + # install_signal_handler(signal, 'DEFAULT') + # end + # + + def exit_handler(signal) + stop_processor(signal) + end + + def exit_now_handler(signal) + if @daemonize + delete_pid rescue nil + send_signal('KILL', @pid_file) + else + exit + end + end + + def info_handler(signal) + logger.info Kt::Queue::Queue.queue.connection.stats.inspect + end + + def reload_handler(signal) + logger.warn "Kontagent Queue Processor: Signal HUP is not supported!" + end + + def restart_handler(signal) + logger.warn "Kontagent Queue Processor: Signal USR2 is not supported!" + end + + def breakpoint_handler(signal) + logger.warn "Kontagent Queue Processor: Signal SIGTRAP is not supported!" + end + + # Change privileges of the process to specified user and group. + def change_privilege(user, group) + begin + uid, gid = Process.euid, Process.egid + target_uid = user ? Etc.getpwnam(user).uid : nil + target_gid = group ? Etc.getgrnam(group).gid : nil + + # --- + # TODO: Remove this, if not necessary... + # if target_uid + # logger.info "Initiating groups for #{user.inspect}:#{group.inspect}." + # Process.initgroups(user, target_gid) + # end + # +++ + + if target_uid && uid != target_uid + logger.info "Changing user to #{user.inspect}." + Process::UID.change_privilege(target_uid) + end + + if target_gid && gid != target_gid + logger.info "Changing group to #{group.inspect}." + Process::GID.change_privilege(target_gid) + end + rescue Errno::EPERM => e + STDERR.puts "Couldn't change user and group to #{user.inspect}:#{group.inspect}: #{e}." + exit 1 + end + end + + def logger + RAILS_DEFAULT_LOGGER || ActionController::Base.logger + end + end + + + # Parses the command line options and provides central access to them. + # There are no required options. The main command of +start+, +stop+, or +restart+ is _required_. + # [+environment+] Rails Environment. Defaults to +development+. + # [+pid+] Pid file location. Defaults to +RAILS_ROOT/tmp/pids/queue_processor.pid+. + # [+log+] Log file location. Defaults to +RAILS_ROOT/log/queue_processor.log+. + # [+chdir+] Change directory to this PATH before running the command. + # [+user+] Run as the specified user. Defaults to current user. + # [+group+] Run as the specified group. Defaults to current group. + # [+daemonize+] Run as a daemon process. In _production_ mode daemon mode is the default. + class Configurator + attr_reader :cwd, :environment, :options + + def initialize + options = [ + ["-e", "--environment ENV", "Rails environment to run as", :@environment, ENV['RAILS_ENV'] || "development"], + ["-p", "--pid", "Pid file location", :@pid_file, nil], + ["-l", "--log", "Log file location", :@log_file, nil], + ['-c', '--chdir PATH', "Change to dir before starting (will be expanded)", :@cwd, Dir.pwd], + ['-u', '--user USER', "Run as user USER", :@user, nil], + ['-g', '--group GROUP', "Run as group GROUP", :@group, nil], + ['-d', '--daemonize', "Run as daemon, regardless of environment", :@daemon, nil], + ] + + @options = {} + + @opts = OptionParser.new + @opts.banner = "Usage: #{File.basename($0)} <start|stop|restart> [options]" + + @opts.on("-h", "--help", "Show this message") do + show_banner + end + + options.each do |short, long, help, variable, default| + self.instance_variable_set(variable, default) + # variable comes in with @pid, @user, etc..., change to :pid, :user, etc... + options_variable = variable.to_s.gsub('@', '').intern + @options[options_variable] = default + @opts.on(short, long, help) do |arg| + self.instance_variable_set(variable, arg) + @options[options_variable] = arg + end + end + + show_banner("Please specify one of start, stop, or restart!") unless ['start', 'stop', 'restart'].include? ARGV.first + + @opts.parse! ARGV + + @cwd = File.expand_path(@cwd) + + show_banner("#{@cwd} is not a valid directory") unless File.directory? @cwd + end + + def show_banner(error=nil) + STDERR.puts error if error + puts @opts + exit(error.nil? ? 0 : 1) + end + end +end + +config = Kontagent::Configurator.new + +Dir.chdir(config.cwd) +ENV['RAILS_ENV'] = config.environment + +require File.dirname(__FILE__) + '/../config/environment' +require 'daemons/daemonize' + +puts config.options.inspect + +manager = Kontagent::ProcessManager.new config.options +manager.send ARGV.first.to_sym diff --git a/tasks/kt_tasks.rake b/tasks/kt_tasks.rake new file mode 100644 index 0000000..88b3617 --- /dev/null +++ b/tasks/kt_tasks.rake @@ -0,0 +1,4 @@ +# desc "Explaining what the task does" +# task :kt do +# # Task goes here +# end diff --git a/test/kt_test.rb b/test/kt_test.rb new file mode 100644 index 0000000..cc66f1f --- /dev/null +++ b/test/kt_test.rb @@ -0,0 +1,8 @@ +require 'test/unit' + +class KtTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_this_plugin + flunk + end +end diff --git a/uninstall.rb b/uninstall.rb new file mode 100644 index 0000000..9738333 --- /dev/null +++ b/uninstall.rb @@ -0,0 +1 @@ +# Uninstall hook code here
tedkulp/cmsms-nouveau
755a1ba69b9c5b5f8e3de03046f6ab9b4b065f3a
Namespace and ORM changes
diff --git a/components/admin/controllers/class.admin_controller.php b/components/admin/controllers/class.admin_controller.php index 64076a0..5bc3857 100644 --- a/components/admin/controllers/class.admin_controller.php +++ b/components/admin/controllers/class.admin_controller.php @@ -1,54 +1,54 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class AdminController extends \silk\action\Controller { var $theme = 'default'; function __construct() { parent::__construct(); //Add a theme determination here $this->set_layout(); } function set_layout($name = 'main') { $this->layout_name = join_path('themes', $this->theme, $name); $this->set('layout_root_url', SilkRequest::get_calculated_url_base(true) . '/layouts/themes/' . $this->theme); $this->set('layout_root_path', join_path(ROOT_DIR, 'layouts', 'themes', $this->theme)); $this->set('silk_lib_root_url', SilkRequest::get_calculated_url_base(true) . '/lib/silk'); $this->set('cmsms_lib_root_url', SilkRequest::get_calculated_url_base(true) . '/lib/cmsms'); $this->set('root_url', SilkRequest::get_calculated_url_base(true) . '/'); //Setup the menu CmsAdminTree::fill_from_file(); $this->set('root_node', CmsAdminTree::get_instance()->get_root_node()); } function before_filter() { - //$this->check_access(SilkUserSession::is_logged_in()); + //$this->check_access(\silk\auth\UserSession::is_logged_in()); SilkDatabase::disable_caching(); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/controllers/class.login_controller.php b/components/admin/controllers/class.login_controller.php index 4704fc5..7dc9aa2 100644 --- a/components/admin/controllers/class.login_controller.php +++ b/components/admin/controllers/class.login_controller.php @@ -1,34 +1,36 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +use \silk\auth\UserSession; + class LoginController extends \silk\action\Controller { function index($params) { - $user_session = new SilkUserSession($params['login']); + $user_session = new UserSession($params['login']); if ($user_session->login()) { //redirect('') var_dump('login successful'); } $this->set_by_ref('user_session', $user_session); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/helpers/class.page_helper.php b/components/admin/helpers/class.page_helper.php index 561cb8d..f4df95f 100644 --- a/components/admin/helpers/class.page_helper.php +++ b/components/admin/helpers/class.page_helper.php @@ -1,41 +1,43 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -class PageHelper extends SilkHelperBase +use \silk\display\HelperBase; + +class PageHelper extends HelperBase { function page_template_dropdown_options($params, $smarty) { $opt = array(); foreach (orm('CmsTemplate')->find_all_by_active(true) as $tpl) { $opt[$tpl->id] = $tpl->name; } return forms()->create_input_options(array('items' => $opt, 'selected_value' => $params['selected'])); } function content_type_dropdown_options($params, $smarty) { $opt = array(); $opt['CmsHtmlContent'] = 'HTML Content'; $opt['CmsOtherContent'] = 'Other Content'; return forms()->create_input_options(array('items' => $opt, 'selected_value' => $params['selected'])); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/helpers/class.page_template_helper.php b/components/admin/helpers/class.page_template_helper.php index 072211b..5cdd067 100644 --- a/components/admin/helpers/class.page_template_helper.php +++ b/components/admin/helpers/class.page_template_helper.php @@ -1,44 +1,46 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -class PageTemplateHelper extends SilkHelperBase +use \silk\display\HelperBase; + +class PageTemplateHelper extends HelperBase { function test_plugin($params) { return 'doing some stuff'; } function modifier_test_mod($string) { return $string . " - modifying some stuff"; } function block_another_test($params, $content, $smarty, $repeat) { if(!$repeat) { if (isset($content)) { return 'block -- ' . $content . ' -- block'; } } } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_attribute.php b/lib/cmsms/classes/class.cms_attribute.php index a715c2f..0a39a4d 100644 --- a/lib/cmsms/classes/class.cms_attribute.php +++ b/lib/cmsms/classes/class.cms_attribute.php @@ -1,38 +1,38 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** * Stores and attribute definition for another class to link to. This is esentially * a key/val pair w/ an optional language attribute. * * @author Ted Kulp * @since 2.0 **/ -class CmsAttribute extends SilkObjectRelationalMapping +class CmsAttribute extends \silk\orm\ActiveRecord { var $params = array('id' => -1); var $table = 'attributes'; public function __construct() { parent::__construct(); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_content_base.php b/lib/cmsms/classes/class.cms_content_base.php index a366167..132866a 100644 --- a/lib/cmsms/classes/class.cms_content_base.php +++ b/lib/cmsms/classes/class.cms_content_base.php @@ -1,53 +1,53 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ -use \silk\orm\ObjectRelationalMapping; +use \silk\orm\ActiveRecord; -class CmsContentBase extends ObjectRelationalMapping +class CmsContentBase extends ActiveRecord { var $table = 'content'; function __construct() { parent::__construct(); $this->type = get_class(); } function get_content() { return ''; } function get_edit_form($block_name = 'default') { $file_name = underscore(get_class($this)); $tpl_file = join_path(dirname(__FILE__), 'content_types', 'templates', 'edit.' . $file_name . '.tpl'); if (is_file($tpl_file)) { smarty()->assignByRef('obj', $this); smarty()->assign('block_name', $block_name); return smarty()->fetch($tpl_file); } return ''; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_page.php b/lib/cmsms/classes/class.cms_page.php index 07d52bd..615ffd9 100644 --- a/lib/cmsms/classes/class.cms_page.php +++ b/lib/cmsms/classes/class.cms_page.php @@ -1,241 +1,241 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -use \silk\orm\ObjectRelationalMapping; +use \silk\orm\ActiveRecord; /** * Base page class. Extend this to create new content types for * the system. * * @author Ted Kulp * @since 2.0 **/ -class CmsPage extends ObjectRelationalMapping +class CmsPage extends ActiveRecord { var $table = 'pages'; var $params = array('id' => -1, 'template_id' => -1, 'active' => true, 'default_content' => false, 'parent_id' => -1, 'lft' => 1, 'rgt' => 1, 'blocks' => array()); #Stuff needed to do a doppleganger for CmsNode -- Multiple inheritence would rock right now var $tree = null; var $parentnode = null; var $children = array(); function __construct() { parent::__construct(); } function setup() { $this->create_belongs_to_association('template', 'CmsTemplate', 'template_id'); $this->assign_acts_as('NestedSet'); } function display() { smarty()->register->templateObject('current_page', $this); $template_content = $this->template->process(); return $template_content; } function get_url($rewrite = true, $lang = '') { $url = SilkRequest::get_calculated_url_base() . $this->hierarchy_path(); /* $config = cms_config(); $alias = ($this->alias != ''?$this->alias:$this->id); if ($config["assume_mod_rewrite"] && $rewrite == true) { $url = $config['root_url']. '/' . ($lang != '' ? "$lang/" : '') . $this->HierarchyPath() . (isset($config['page_extension'])?$config['page_extension']:'.html'); } else { if (isset($_SERVER['PHP_SELF']) && $config['internal_pretty_urls'] == true) { $url = $config['root_url'] . '/index.php/' . ($lang != '' ? "$lang/" : '') . $this->HierarchyPath() . (isset($config['page_extension']) ? $config['page_extension '] : '.html'); } else { $url = $config['root_url'] . '/index.php?' . $config['query_var'] . '=' . $alias . ($lang != '' ? '&amp;lang=' . $lang : ''); } } */ return $url; } function get_content_block($block_name = 'default', $can_return_new = false) { if (isset($this->blocks[$block_name])) { if (isset($this->blocks[$block_name]['id'])) { $content = orm('CmsContentBase')->find_by_id($this->blocks[$block_name]['id']); if ($content != null) { return $content; } } } if ($can_return_new) return new CmsHtmlContent(); //TODO: Fix me else return null; } function get_content($block_name = 'default') { $block = $this->get_content_block($block_name); if ($block != null) { return $block->get_content(); } return '<!-- No content found for ' . $block_name . ' -->'; } /** * Function content types to use to say whether or not they should show * up in lists where parents of content are set. This will default to true, * but should be used in cases like Separator where you don't want it to * have any children. * * @since 0.11 */ function wants_children() { return true; } function can_preview() { return false; } function template_name() { $tmp = $this->template; if ($tmp) return $tmp->name; return ''; } function add_child($node) { $node->set_parent($this); $node->tree = $this->tree; $this->children[] = $node; } function get_tree() { return $this->tree; } function has_children() { return $this->rgt > $this->lft + 1; } function depth() { $depth = 0; $currLevel = &$this; while ($currLevel->parentnode) { $depth++; $currLevel = &$currLevel->parentnode; } return $depth; } function get_level() { return $this->depth(); } function getLevel() { return $this->depth(); } function get_parent() { return $this->parentnode; } function set_parent($node) { $this->parentnode = $node; } function get_children_count() { return count($this->children); } function getChildrenCount() { return $this->get_children_count(); } function &get_children() { if ($this->has_children()) { //We know there are children, but no nodes have been //created yet. We should probably do that. if (!$this->children_loaded()) { //$this->tree->load_child_nodes(-1, $this->lft, $this->rgt); $this->tree->load_child_nodes($this->id); } } return $this->children; } function &get_flat_list() { $return = array(); if ($this->has_children()) { for ($i=0; $i<count($this->children); $i++) { $return[] = &$this->children[$i]; $return = array_merge($return, $this->children[$i]->get_flat_list()); } } return $return; } function &getFlatList() { $tmp =& $this->get_flat_list(); return $tmp; } } ?> diff --git a/lib/cmsms/classes/class.cms_smarty.php b/lib/cmsms/classes/class.cms_smarty.php index 4ceda83..d3d7135 100644 --- a/lib/cmsms/classes/class.cms_smarty.php +++ b/lib/cmsms/classes/class.cms_smarty.php @@ -1,70 +1,70 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #BUT withOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** * Represents a template in the database. * * @author Ted Kulp * @since 2.0 **/ -class CmsSmarty extends SilkSmarty +class CmsSmarty extends \silk\display\Smarty { function __construct() { parent::__construct(); $this->register->resource("template", array($this, "template_get_template", "template_get_timestamp", "db_get_secure", "db_get_trusted")); } function template_get_template($tpl_name, &$tpl_source, $smarty_obj) { $template = CmsTemplate::find_by_id($tpl_name); if ($template) { $tpl_source = $template->content; return true; } return false; } function template_get_timestamp($tpl_name, &$tpl_timestamp, $smarty_obj) { $template = CmsTemplate::find_by_id($tpl_name); if ($template) { $tpl_timestamp = $template->modified_date->timestamp(); return true; } return false; } function db_get_secure($tpl_name, &$smarty_obj) { // assume all templates are secure return true; } function db_get_trusted($tpl_name, &$smarty_obj) { // not used for templates } } ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_stylesheet.php b/lib/cmsms/classes/class.cms_stylesheet.php index bf47357..314744b 100644 --- a/lib/cmsms/classes/class.cms_stylesheet.php +++ b/lib/cmsms/classes/class.cms_stylesheet.php @@ -1,114 +1,114 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -use \silk\orm\ObjectRelationalMapping; +use \silk\orm\ActiveRecord; /** * Represents a stylesheet in the database. * * @author Ted Kulp * @since 0.11 **/ -class CmsStylesheet extends ObjectRelationalMapping +class CmsStylesheet extends ActiveRecord { var $params = array('id' => -1, 'name' => '', 'value' => '', 'media_type' => 'all', 'active' => 1); var $table = 'stylesheets'; var $media_types = array( array('name' => "all"), array('name' => "aural"), array('name' => "braille"), array('name' => "embossed"), array('name' => "handheld"), array('name' => "print"), array('name' => "projection"), array('name' => "screen"), array('name' => "tty"), array('name' => "tv") ); public function validate() { $this->validate_not_blank('name'); $this->validate_not_blank('value'); if ($this->name != '') { $result = $this->find_all_by_name($this->name); if (count($result) > 0) { if ($result[0]->id != $this->id) { $this->add_validation_error('Stylesheet Exists'); } } } } public function get_media_types_as_array() { return explode(', ', $this->media_type); } public function setup() { $this->create_has_many_association('template_associations', 'template_stylesheet_association', 'stylesheet_id'); $this->create_has_and_belongs_to_many_association('templates', 'template', 'stylesheet_template_assoc', 'template_id', 'stylesheet_id'); $this->create_has_and_belongs_to_many_association('active_templates', 'template', 'stylesheet_template_assoc', 'template_id', 'stylesheet_id', array('conditions' => 'templates.active = 1')); } public function assign_template_by_id($template_id) { $template = orm('CmsTemplate')->find_by_id($template_id); if ($template) { $template->assign_stylesheet_by_id($this->id); } } public function remove_assigned_template_by_id($template_id) { $template = orm('CmsTemplate')->find_by_id($template_id); if ($template) { $template->remove_assigned_stylesheet_by_id($this->id); } } //Callback handlers function before_save() { //CmsEvents::send_event( 'Core', ($this->id == -1 ? 'AddStylesheetPre' : 'EditStylesheetPre'), array('stylesheet' => &$this)); } function after_save() { //CmsEvents::send_event( 'Core', ($this->create_date == $this->modified_date ? 'AddStylesheetPost' : 'EditStylesheetPost'), array('stylesheet' => &$this)); } function before_delete() { //CmsEvents::send_event('Core', 'DeleteStylesheetPre', array('stylesheet' => &$this)); } function after_delete() { //CmsEvents::send_event('Core', 'DeleteStylesheetPost', array('stylesheet' => &$this)); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_template.php b/lib/cmsms/classes/class.cms_template.php index 423f602..09675f1 100644 --- a/lib/cmsms/classes/class.cms_template.php +++ b/lib/cmsms/classes/class.cms_template.php @@ -1,191 +1,191 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #BUT withOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -use \silk\orm\ObjectRelationalMapping; +use \silk\orm\ActiveRecord; /** * Represents a template in the database. * * @author Ted Kulp * @since 2.0 **/ -class CmsTemplate extends ObjectRelationalMapping +class CmsTemplate extends ActiveRecord { var $params = array('id' => -1, 'name' => '', 'content' => '', 'stylesheet' => '', 'encoding' => '', 'active' => true, 'default' => false); var $field_maps = array('template_name' => 'name', 'default_template' => 'default', 'template_content' => 'content'); var $table = 'templates'; var $blocks = array(); public function setup() { $this->create_has_many_association('stylesheet_associations', 'cms_template_stylesheet_association', 'template_id', array('order' => 'order_num ASC')); $this->create_has_and_belongs_to_many_association('stylesheets', 'cms_stylesheet', 'stylesheet_template_assoc', 'stylesheet_id', 'template_id', array('order' => 'order_num ASC')); $this->create_has_and_belongs_to_many_association('active_stylesheets', 'cms_stylesheet', 'stylesheet_template_assoc', 'stylesheet_id', 'template_id', array('order' => 'order_num ASC', 'conditions' => 'stylesheets.active = 1')); } function usage_count() { return orm('CmsTemplateAssociation')->find_count_by_template_id($this->id); } function validate() { $this->validate_not_blank('name'); $this->validate_not_blank('content'); if ($this->name != '') { $result = orm('cms_template')->find_all_by_name($this->name); if (count($result) > 0) { if ($result[0]->id != $this->id) { $this->add_validation_error('Template Exists'); } } } } public function get_stylesheet_media_types($show_inactive = false) { $result = array(); foreach ($this->active_stylesheets as $stylesheet) { foreach ($stylesheet->get_media_types_as_array() as $media_type) { if (!in_array($media_type, $result)) $result[] = $media_type; } } return $result; } public function assign_stylesheet_by_id($stylesheet_id) { $exists = false; $cur_stylesheets = $this->stylesheets; foreach ($cur_stylesheets as $one_stylesheet) { if ($one_stylesheet->stylesheet_id == $stylesheet_id) { $exists = true; break; } } if (!$exists) { $new_assoc = new CmsTemplateStylesheetAssociation; $new_assoc->template_id = $this->id; $new_assoc->stylesheet_id = $stylesheet_id; $new_assoc->save(); } } public function remove_assigned_stylesheet_by_id($stylesheet_id) { $cur_stylesheets = $this->stylesheet_associations; foreach ($cur_stylesheets as $one_stylesheet) { if ($one_stylesheet->stylesheet_id == $stylesheet_id) { $one_stylesheet->delete(); break; } } } public function get_page_blocks() { $smarty = smarty(); $this->blocks = array(); $old_function = $smarty->_plugins['function']['content']; $smarty->register->templateFunction('content', array($this, 'parse_block_callback')); $smarty->fetch("string:" . $this->content); $smarty->unregister->templateFunction('content'); $smarty->_plugins['function']['content'] = $old_function; return $this->blocks; } public function parse_block_callback($params, $smarty) { $name = 'default'; if (isset($params['block'])) { $name = $params['block']; unset($params['block']); } if (!isset($params['type'])) { $params['type'] = 'CmsHtmlContentType'; } $this->blocks[$name] = $params; } function process() { $smarty = smarty(); return $smarty->fetch('template:' . $this->id); } //Callback handlers function before_save() { //Make sure we have a default template set or we'll probably break stuff down the road if (orm('CmsTemplate')->find_count_by_default_template(1) == 0) { $this->default_template = 1; } //CmsEvents::send_event( 'Core', ($this->id == -1 ? 'AddTemplatePre' : 'EditTemplatePre'), array('template' => &$this)); } function after_save() { /* CmsEvents::send_event( 'Core', ($this->create_date == $this->modified_date ? 'AddTemplatePost' : 'EditTemplatePost'), array('template' => &$this)); CmsCache::clear(); CmsContentOperations::clear_cache(); */ } function before_delete() { //CmsEvents::send_event('Core', 'DeleteTemplatePre', array('template' => &$this)); } function after_delete() { /* CmsEvents::send_event('Core', 'DeleteTemplatePost', array('template' => &$this)); CmsCache::clear(); CmsContentOperations::clear_cache(); */ } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_template_stylesheet_association.php b/lib/cmsms/classes/class.cms_template_stylesheet_association.php index 23bf443..ed5a2e9 100644 --- a/lib/cmsms/classes/class.cms_template_stylesheet_association.php +++ b/lib/cmsms/classes/class.cms_template_stylesheet_association.php @@ -1,38 +1,38 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ -use \silk\orm\ObjectRelationalMapping; +use \silk\orm\ActiveRecord; -class CmsTemplateStylesheetAssociation extends ObjectRelationalMapping +class CmsTemplateStylesheetAssociation extends ActiveRecord { var $table = 'stylesheet_template_assoc'; var $list_filter_fields = array('template_id'); //So order only counts when it's the same template_id public function setup() { $this->create_belongs_to_association('template', 'template', 'template_id'); $this->create_belongs_to_association('stylesheet', 'stylesheet', 'stylesheet_id'); $this->assign_acts_as('list'); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file
tedkulp/cmsms-nouveau
79ced86e31a4fa3e9a0aa71995e73c3e982c76d7
Changes for namespaces
diff --git a/lib/cmsms/classes/class.cms_content_base.php b/lib/cmsms/classes/class.cms_content_base.php index 194ea14..a366167 100644 --- a/lib/cmsms/classes/class.cms_content_base.php +++ b/lib/cmsms/classes/class.cms_content_base.php @@ -1,51 +1,53 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ -class CmsContentBase extends SilkObjectRelationalMapping +use \silk\orm\ObjectRelationalMapping; + +class CmsContentBase extends ObjectRelationalMapping { var $table = 'content'; function __construct() { parent::__construct(); $this->type = get_class(); } function get_content() { return ''; } function get_edit_form($block_name = 'default') { $file_name = underscore(get_class($this)); $tpl_file = join_path(dirname(__FILE__), 'content_types', 'templates', 'edit.' . $file_name . '.tpl'); if (is_file($tpl_file)) { smarty()->assignByRef('obj', $this); smarty()->assign('block_name', $block_name); return smarty()->fetch($tpl_file); } return ''; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_page.php b/lib/cmsms/classes/class.cms_page.php index a1a0412..07d52bd 100644 --- a/lib/cmsms/classes/class.cms_page.php +++ b/lib/cmsms/classes/class.cms_page.php @@ -1,239 +1,241 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +use \silk\orm\ObjectRelationalMapping; + /** * Base page class. Extend this to create new content types for * the system. * * @author Ted Kulp * @since 2.0 **/ -class CmsPage extends SilkObjectRelationalMapping +class CmsPage extends ObjectRelationalMapping { var $table = 'pages'; var $params = array('id' => -1, 'template_id' => -1, 'active' => true, 'default_content' => false, 'parent_id' => -1, 'lft' => 1, 'rgt' => 1, 'blocks' => array()); #Stuff needed to do a doppleganger for CmsNode -- Multiple inheritence would rock right now var $tree = null; var $parentnode = null; var $children = array(); function __construct() { parent::__construct(); } function setup() { $this->create_belongs_to_association('template', 'CmsTemplate', 'template_id'); $this->assign_acts_as('NestedSet'); } function display() { smarty()->register->templateObject('current_page', $this); $template_content = $this->template->process(); return $template_content; } function get_url($rewrite = true, $lang = '') { $url = SilkRequest::get_calculated_url_base() . $this->hierarchy_path(); /* $config = cms_config(); $alias = ($this->alias != ''?$this->alias:$this->id); if ($config["assume_mod_rewrite"] && $rewrite == true) { $url = $config['root_url']. '/' . ($lang != '' ? "$lang/" : '') . $this->HierarchyPath() . (isset($config['page_extension'])?$config['page_extension']:'.html'); } else { if (isset($_SERVER['PHP_SELF']) && $config['internal_pretty_urls'] == true) { $url = $config['root_url'] . '/index.php/' . ($lang != '' ? "$lang/" : '') . $this->HierarchyPath() . (isset($config['page_extension']) ? $config['page_extension '] : '.html'); } else { $url = $config['root_url'] . '/index.php?' . $config['query_var'] . '=' . $alias . ($lang != '' ? '&amp;lang=' . $lang : ''); } } */ return $url; } function get_content_block($block_name = 'default', $can_return_new = false) { if (isset($this->blocks[$block_name])) { if (isset($this->blocks[$block_name]['id'])) { $content = orm('CmsContentBase')->find_by_id($this->blocks[$block_name]['id']); if ($content != null) { return $content; } } } if ($can_return_new) return new CmsHtmlContent(); //TODO: Fix me else return null; } function get_content($block_name = 'default') { $block = $this->get_content_block($block_name); if ($block != null) { return $block->get_content(); } return '<!-- No content found for ' . $block_name . ' -->'; } /** * Function content types to use to say whether or not they should show * up in lists where parents of content are set. This will default to true, * but should be used in cases like Separator where you don't want it to * have any children. * * @since 0.11 */ function wants_children() { return true; } function can_preview() { return false; } function template_name() { $tmp = $this->template; if ($tmp) return $tmp->name; return ''; } function add_child($node) { $node->set_parent($this); $node->tree = $this->tree; $this->children[] = $node; } function get_tree() { return $this->tree; } function has_children() { return $this->rgt > $this->lft + 1; } function depth() { $depth = 0; $currLevel = &$this; while ($currLevel->parentnode) { $depth++; $currLevel = &$currLevel->parentnode; } return $depth; } function get_level() { return $this->depth(); } function getLevel() { return $this->depth(); } function get_parent() { return $this->parentnode; } function set_parent($node) { $this->parentnode = $node; } function get_children_count() { return count($this->children); } function getChildrenCount() { return $this->get_children_count(); } function &get_children() { if ($this->has_children()) { //We know there are children, but no nodes have been //created yet. We should probably do that. if (!$this->children_loaded()) { //$this->tree->load_child_nodes(-1, $this->lft, $this->rgt); $this->tree->load_child_nodes($this->id); } } return $this->children; } function &get_flat_list() { $return = array(); if ($this->has_children()) { for ($i=0; $i<count($this->children); $i++) { $return[] = &$this->children[$i]; $return = array_merge($return, $this->children[$i]->get_flat_list()); } } return $return; } function &getFlatList() { $tmp =& $this->get_flat_list(); return $tmp; } } ?> diff --git a/lib/cmsms/classes/class.cms_stylesheet.php b/lib/cmsms/classes/class.cms_stylesheet.php index 24a1d2b..bf47357 100644 --- a/lib/cmsms/classes/class.cms_stylesheet.php +++ b/lib/cmsms/classes/class.cms_stylesheet.php @@ -1,112 +1,114 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +use \silk\orm\ObjectRelationalMapping; + /** * Represents a stylesheet in the database. * * @author Ted Kulp * @since 0.11 **/ -class CmsStylesheet extends SilkObjectRelationalMapping +class CmsStylesheet extends ObjectRelationalMapping { var $params = array('id' => -1, 'name' => '', 'value' => '', 'media_type' => 'all', 'active' => 1); var $table = 'stylesheets'; var $media_types = array( array('name' => "all"), array('name' => "aural"), array('name' => "braille"), array('name' => "embossed"), array('name' => "handheld"), array('name' => "print"), array('name' => "projection"), array('name' => "screen"), array('name' => "tty"), array('name' => "tv") ); public function validate() { $this->validate_not_blank('name'); $this->validate_not_blank('value'); if ($this->name != '') { $result = $this->find_all_by_name($this->name); if (count($result) > 0) { if ($result[0]->id != $this->id) { $this->add_validation_error('Stylesheet Exists'); } } } } public function get_media_types_as_array() { return explode(', ', $this->media_type); } public function setup() { $this->create_has_many_association('template_associations', 'template_stylesheet_association', 'stylesheet_id'); $this->create_has_and_belongs_to_many_association('templates', 'template', 'stylesheet_template_assoc', 'template_id', 'stylesheet_id'); $this->create_has_and_belongs_to_many_association('active_templates', 'template', 'stylesheet_template_assoc', 'template_id', 'stylesheet_id', array('conditions' => 'templates.active = 1')); } public function assign_template_by_id($template_id) { $template = orm('CmsTemplate')->find_by_id($template_id); if ($template) { $template->assign_stylesheet_by_id($this->id); } } public function remove_assigned_template_by_id($template_id) { $template = orm('CmsTemplate')->find_by_id($template_id); if ($template) { $template->remove_assigned_stylesheet_by_id($this->id); } } //Callback handlers function before_save() { //CmsEvents::send_event( 'Core', ($this->id == -1 ? 'AddStylesheetPre' : 'EditStylesheetPre'), array('stylesheet' => &$this)); } function after_save() { //CmsEvents::send_event( 'Core', ($this->create_date == $this->modified_date ? 'AddStylesheetPost' : 'EditStylesheetPost'), array('stylesheet' => &$this)); } function before_delete() { //CmsEvents::send_event('Core', 'DeleteStylesheetPre', array('stylesheet' => &$this)); } function after_delete() { //CmsEvents::send_event('Core', 'DeleteStylesheetPost', array('stylesheet' => &$this)); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_template.php b/lib/cmsms/classes/class.cms_template.php index 96494f1..423f602 100644 --- a/lib/cmsms/classes/class.cms_template.php +++ b/lib/cmsms/classes/class.cms_template.php @@ -1,189 +1,191 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #BUT withOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +use \silk\orm\ObjectRelationalMapping; + /** * Represents a template in the database. * * @author Ted Kulp * @since 2.0 **/ -class CmsTemplate extends SilkObjectRelationalMapping +class CmsTemplate extends ObjectRelationalMapping { var $params = array('id' => -1, 'name' => '', 'content' => '', 'stylesheet' => '', 'encoding' => '', 'active' => true, 'default' => false); var $field_maps = array('template_name' => 'name', 'default_template' => 'default', 'template_content' => 'content'); var $table = 'templates'; var $blocks = array(); public function setup() { $this->create_has_many_association('stylesheet_associations', 'cms_template_stylesheet_association', 'template_id', array('order' => 'order_num ASC')); $this->create_has_and_belongs_to_many_association('stylesheets', 'cms_stylesheet', 'stylesheet_template_assoc', 'stylesheet_id', 'template_id', array('order' => 'order_num ASC')); $this->create_has_and_belongs_to_many_association('active_stylesheets', 'cms_stylesheet', 'stylesheet_template_assoc', 'stylesheet_id', 'template_id', array('order' => 'order_num ASC', 'conditions' => 'stylesheets.active = 1')); } function usage_count() { return orm('CmsTemplateAssociation')->find_count_by_template_id($this->id); } function validate() { $this->validate_not_blank('name'); $this->validate_not_blank('content'); if ($this->name != '') { $result = orm('cms_template')->find_all_by_name($this->name); if (count($result) > 0) { if ($result[0]->id != $this->id) { $this->add_validation_error('Template Exists'); } } } } public function get_stylesheet_media_types($show_inactive = false) { $result = array(); foreach ($this->active_stylesheets as $stylesheet) { foreach ($stylesheet->get_media_types_as_array() as $media_type) { if (!in_array($media_type, $result)) $result[] = $media_type; } } return $result; } public function assign_stylesheet_by_id($stylesheet_id) { $exists = false; $cur_stylesheets = $this->stylesheets; foreach ($cur_stylesheets as $one_stylesheet) { if ($one_stylesheet->stylesheet_id == $stylesheet_id) { $exists = true; break; } } if (!$exists) { $new_assoc = new CmsTemplateStylesheetAssociation; $new_assoc->template_id = $this->id; $new_assoc->stylesheet_id = $stylesheet_id; $new_assoc->save(); } } public function remove_assigned_stylesheet_by_id($stylesheet_id) { $cur_stylesheets = $this->stylesheet_associations; foreach ($cur_stylesheets as $one_stylesheet) { if ($one_stylesheet->stylesheet_id == $stylesheet_id) { $one_stylesheet->delete(); break; } } } public function get_page_blocks() { $smarty = smarty(); $this->blocks = array(); $old_function = $smarty->_plugins['function']['content']; $smarty->register->templateFunction('content', array($this, 'parse_block_callback')); $smarty->fetch("string:" . $this->content); $smarty->unregister->templateFunction('content'); $smarty->_plugins['function']['content'] = $old_function; return $this->blocks; } public function parse_block_callback($params, $smarty) { $name = 'default'; if (isset($params['block'])) { $name = $params['block']; unset($params['block']); } if (!isset($params['type'])) { $params['type'] = 'CmsHtmlContentType'; } $this->blocks[$name] = $params; } function process() { $smarty = smarty(); return $smarty->fetch('template:' . $this->id); } //Callback handlers function before_save() { //Make sure we have a default template set or we'll probably break stuff down the road if (orm('CmsTemplate')->find_count_by_default_template(1) == 0) { $this->default_template = 1; } //CmsEvents::send_event( 'Core', ($this->id == -1 ? 'AddTemplatePre' : 'EditTemplatePre'), array('template' => &$this)); } function after_save() { /* CmsEvents::send_event( 'Core', ($this->create_date == $this->modified_date ? 'AddTemplatePost' : 'EditTemplatePost'), array('template' => &$this)); CmsCache::clear(); CmsContentOperations::clear_cache(); */ } function before_delete() { //CmsEvents::send_event('Core', 'DeleteTemplatePre', array('template' => &$this)); } function after_delete() { /* CmsEvents::send_event('Core', 'DeleteTemplatePost', array('template' => &$this)); CmsCache::clear(); CmsContentOperations::clear_cache(); */ } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_template_stylesheet_association.php b/lib/cmsms/classes/class.cms_template_stylesheet_association.php index 74949e1..23bf443 100644 --- a/lib/cmsms/classes/class.cms_template_stylesheet_association.php +++ b/lib/cmsms/classes/class.cms_template_stylesheet_association.php @@ -1,36 +1,38 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ -class CmsTemplateStylesheetAssociation extends SilkObjectRelationalMapping +use \silk\orm\ObjectRelationalMapping; + +class CmsTemplateStylesheetAssociation extends ObjectRelationalMapping { var $table = 'stylesheet_template_assoc'; var $list_filter_fields = array('template_id'); //So order only counts when it's the same template_id public function setup() { $this->create_belongs_to_association('template', 'template', 'template_id'); $this->create_belongs_to_association('stylesheet', 'stylesheet', 'stylesheet_id'); $this->assign_acts_as('list'); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file
tedkulp/cmsms-nouveau
8fbfcd0d2fe9b423720d853d3c082bc4c1a886a4
Namespace related changes
diff --git a/layouts/themes/default/main.tpl b/layouts/themes/default/main.tpl index e01b6f9..e77a471 100644 --- a/layouts/themes/default/main.tpl +++ b/layouts/themes/default/main.tpl @@ -1,115 +1,115 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="Generator" content="CMS Made Simple - Copyright (C) 2004-2009 Ted Kulp. All rights reserved." /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> <title>{$sitename} - {$title}</title> <link rel="stylesheet" href="{$layout_root_url}/css/kevin_tabs.css" type="text/css" /> <link rel="stylesheet" href="{$layout_root_url}/css/style.css" type="text/css" /> <!--[if IE]> <script type="text/javascript" src="{$layout_root_url}/includes/ie7-standard-p.js"></script> <![endif]--> <!-- <script type="text/javascript" src="{$layout_root_url}/includes/standard.js"></script> --> <!-- jQuery and tabs --> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.color.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.silk.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.tabs.js"></script> <!-- Tree stuff --> <link rel="stylesheet" type="text/css" href="{$cmsms_lib_root_url}/js/jstree/source/tree_component.css" /> <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/css.js"></script> <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/source/tree_component.js"></script> <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/jquery.metadata.js"></script> <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/jquery.cookie.js"></script> <script type="text/javascript"> //<![CDATA[ // form handling stuff $(document).ready(function() { setup_form(); }); function setup_form() { // disable all buttons $('button').addClass("disabled").attr("disabled", true); // but enable cancel $('button[@name="cancel"]').removeClass("disabled").attr("disabled", false); // assign event for every input $('form :input').one("change", function() { // on change call enable form enableForm(this.form); // mark in title if(document.title[0] != "*") { document.title = "*"+document.title; } }); // fill the default help text var help = $('#default_helptext').html(); $('#HelpContent').html(help); // assign an event for every form row $("div[id*='formrow']").bind("click", function() { var help = $(this).children("input[id*='help_']").val(); $('#HelpContent').html(help); }); } function enableForm(form) { var input = $('button', form); input.attr('disabled', false).removeClass('disabled'); } //}></script> {$headtext} <base href="{$root_url}" /> </head> <body> <div id="clean-container"> {include file="$layout_root_path/topmenu.tpl"} <div id="MainContent"> {capture assign="errmsg"}{php}echo SilkFlash::get_instance()->get('std');{/php}{/capture} <div class="pagemcontainer"{if empty($errmsg)} style="display: none;"{/if}> <p class="pagemessage" id="pagemessage"> {$errmsg} </p> </div> <div class="pagecontainer" id="pagecontent"> {$content} </div> <div class="clearb"></div> <div id="HelpContent"></div> </div><!-- end MainContent --> <div id="footer"> <a rel="external" href="http://www.cmsmadesimple.org"><b>CMS Made Simple</b></a> {$cms_version} "{$cms_versionname}"<br /><b>CMS Made Simple</b> is free software released under the General Public Licence. </div> </div><!--end clean-container--> </body> </html> -{php}echo \SilkProfiler::get_instance()->report();{/php} \ No newline at end of file +{php}echo \silk\performance\Profiler::get_instance()->report();{/php} \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_loader.php b/lib/cmsms/classes/class.cms_module_loader.php index e6a6def..f03e5ed 100644 --- a/lib/cmsms/classes/class.cms_module_loader.php +++ b/lib/cmsms/classes/class.cms_module_loader.php @@ -1,286 +1,288 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ +use \silk\performance\Cache; + class CmsModuleLoader extends \silk\core\Object { public static $module_list = null; function __construct() { parent::__construct(); } public static function load_module_data() { $files = CmsModuleLoader::find_module_info_files(); //Actually slower if it's cached -- have to retest with lots of modules - $installed_data = SilkCache::get_instance()->call('CmsModuleLoader::get_installed_module_details'); + $installed_data = Cache::get_instance()->call('CmsModuleLoader::get_installed_module_details'); $module_list = array(); foreach ($files as $one_file) { $module_data = self::xmlify_module_info_file($one_file); $module_data = self::inject_installed_data_for_module($module_data, $installed_data); $module_list[$module_data['name']] = $module_data; } self::check_core_version($module_list); self::check_dependencies($module_list); self::$module_list = $module_list; } public static function check_core_version(&$module_list) { foreach ($module_list as &$one_module) { if (isset($one_module['minimum_core_version'])) { if (version_compare($one_module['minimum_core_version'], '2.0', '>')) //Use a real version number here { $one_module['meets_minimum_core'] = false; $one_module['active'] = false; } } } } public static function check_dependencies(&$module_list) { foreach ($module_list as $one_module) { self::check_dependencies_for_module($one_module['name'], $module_list); } } public static function check_dependencies_for_module($module_name, &$module_list) { //Make sure we haven't done this one yet -- no point in repeating if (!isset($module_list[$module_name]['meets_dependencies'])) { $module_list[$module_name]['meets_dependencies'] = true; if (isset($module_list[$module_name]['dependencies']) && is_array($module_list[$module_name]['dependencies'])) { //Hack for handling 1 module dependency if (isset($module_list[$module_name]['dependencies']['module'])) { $tmp = $module_list[$module_name]['dependencies']['module']; unset($module_list[$module_name]['dependencies']['module']); $module_list[$module_name]['dependencies'][0]['module'] = $tmp; } for ($i = 0; $i < count($module_list[$module_name]['dependencies']); $i++) { //If a module dependency (only kind for now) if (isset($module_list[$module_name]['dependencies'][$i]['module'])) { $one_dep = $module_list[$module_name]['dependencies'][$i]['module']; //Does this dependency exist at all? if (isset($module_list[$one_dep['name']])) { //Make sure we process any dependencies first self::check_dependencies_for_module($one_dep['name'], $module_list); //Now that it's processed, check for active and installed_version stuff if ($module_list[$one_dep['name']]['active'] == false) { //var_dump('parent is not active: ' . $one_dep['name'] . ' from ' . $module_name); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } else if (isset($one_dep['minimum_version']) && version_compare($one_dep['minimum_version'], $module_list[$one_dep['name']]['installed_version'], '>')) { //var_dump('does not meet minimum version: ' . $one_dep['name'] . ' from ' . $module_name); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } } else { //var_dump('does not exist: ' . $one_dep['name']); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } } } } } } public static function get_proper_module_case($name) { if (self::$module_list != null) { foreach (self::$module_list as $k=>$v) { if (strtolower($k) == strtolower($name)) { return $k; } } } return name; } public static function get_module_class($name) { if (self::$module_list != null) { //Make sure we can call modules without checking case $name = self::get_proper_module_case($name); if (isset(self::$module_list[$name]) && self::$module_list[$name]['active'] == true) { if (isset(self::$module_list[$name]['object'])) { return self::$module_list[$name]['object']; } else { require_once(join_path(ROOT_DIR, 'modules', $name, $name . '.module.php')); if (class_exists($name) && is_subclass_of($name, 'CmsModuleBase')) { if (isset(self::$module_list[$name]['dependencies'])) { foreach (self::$module_list[$name]['dependencies'] as $dep) { self::get_module_class($dep['module']['name']); } } //var_dump('Instantiating: ' . $name); self::$module_list[$name]['object'] = new $name(); self::$module_list[$name]['object']->setup(); return self::$module_list[$name]['object']; } } } } return null; } public static function is_installed($name) { if (isset(self::$module_list[$name]) && isset(self::$module_list[$name]['installed'])) return self::$module_list[$name]['installed']; return false; } public static function is_active($name) { if (isset(self::$module_list[$name]) && isset(self::$module_list[$name]['active'])) return self::$module_list[$name]['active']; return false; } public static function get_installed_module_details() { $db_prefix = db_prefix(); return db()->GetAll("select * from {$db_prefix}modules"); } public static function inject_installed_data_for_module($module_data, $installed_data) { $module_data['installed'] = false; $module_data['active'] = false; $module_data['installed_version'] = $module_data['version']; $module_data['needs_upgrade'] = false; $module_data['meets_minimum_core'] = true; foreach($installed_data as $one_row) { if ($one_row['module_name'] == $module_data['name']) { $module_data['installed'] = true; $module_data['active'] = ($one_row['active'] == '1' ? true : false); $module_data['installed_version'] = $one_row['version']; $module_data['needs_upgrade'] = version_compare($module_data['installed_version'], $one_row['version'], '<'); } } return $module_data; } public static function xmlify_module_info_file($file) { $xml = simplexml_load_file($file); return self::convert_xml_to_array($xml); } public static function convert_xml_to_array($xml) { if (!($xml->children())) { return (string) $xml; } foreach ($xml->children() as $child) { $name = $child->getName(); if (count($xml->$name) == 1) { $element[$name] = self::convert_xml_to_array($child); } else { $element[][$name] = self::convert_xml_to_array($child); } } return $element; } public static function find_module_info_files() { $filelist = array(); $dir = join_path(ROOT_DIR, 'modules'); if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..') { $mod_dir = join_path($dir, $file); if (is_dir($mod_dir)) { $mod_info_file = join_path($dir, $file, $file . '.info.xml'); if (is_file($mod_info_file) && is_readable($mod_info_file)) { $filelist[] = $mod_info_file; } } } } closedir($dh); } } return $filelist; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_page_tree.php b/lib/cmsms/classes/class.cms_page_tree.php index fa34de0..3fddbd7 100644 --- a/lib/cmsms/classes/class.cms_page_tree.php +++ b/lib/cmsms/classes/class.cms_page_tree.php @@ -1,181 +1,183 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +use \silk\performance\Cache; + /** * Classes for storing the frontend page hierarchy. Includes methods to load * the structure from the database and properly return related Content objects. * * @author Ted Kulp * @since 2.0 **/ class CmsPageTree extends SilkTree { static public $content = array(); static private $instance = NULL; function __construct() { parent::__construct(); $this->root = new SilkNode(); $this->root->tree = $this; $this->load_child_nodes(); //Fill the base of the tree } static public function get_instance() { if (self::$instance == NULL) { self::$instance = new CmsPageTree(); } return self::$instance; } function get_root() { return $this->root; } function getRootNode() { return $this->root; } public function load_child_nodes($parent_id = 1, $lft = -1, $rgt = -1) { $pages = array(); if ($lft == -1 && $rgt == -1) { $pages = orm('CmsPage')->find_all_by_parent_id($parent_id, array('order' => 'lft ASC')); } else { $pages = orm('CmsPage')->find_all(array('conditions' => array('lft > ? AND rgt < ?', $lft, $rgt), 'order' => 'lft ASC')); } //var_dump(count($pages)); //debug_print_backtrace(); foreach ($pages as $page) { $parent_node = $this->get_node_by_id($page->parent_id); if ($parent_node != null) { $parent_node->add_child($page); self::$content[(string)$page->id] = $page; //Put a reference up so we can quickly check to see if it's loaded already $parent_node->children_loaded = true; } } } public function load_parent_nodes($id) { //TODO: Optimize this more -- right now we're just making sure it works //First we find the page. If it exists, we then grab the great-great-grandparent //and load all of the nodes in between. $page = orm('CmsPage')->find_by_id($id); if ($page) { $ancestor = null; $top_nodes = $this->tree->get_root_node()->get_children(); foreach ($top_nodes as $one_node) { //Don't bother doing this if we're only level 2 if ($one_node->lft < $page->lft && $one_node->rgt > $page->rgt && $one_node->id != $page->id) { $ancestor = $one_node; break; } } if ($ancestor != null) { $this->load_child_nodes(1, $ancestor->lft, $ancestor->rgt); } } } public function get_node_by_id($id) { if ($id) { if ($id == 1) { return $this->get_root_node(); } else if (array_key_exists((string)$id, self::$content)) { return self::$content[(string)$id]; } else { $this->load_parent_nodes($id); return self::$content[(string)$id]; } } } function getNodeByID($id) { return $this->get_node_by_id($id); } function sureGetNodeByID($id) { return $this->get_node_by_id($id); } public function get_node_by_alias($alias) { $result = null; - $id = SilkCache::get_instance()->call('CmsContentOperations::get_page_id_from_alias', $alias); + $id = Cache::get_instance()->call('CmsContentOperations::get_page_id_from_alias', $alias); if ($id) { $result = $this->get_node_by_id($id); } return $result; } function getNodeByAlias($alias) { return $this->get_node_by_alias($alias); } function sureGetNodeByAlias($alias) { return $this->get_node_by_alias($alias); } function get_node_by_hierarchy($position) { $result = null; - $id = SilkCache::get_instance()->call('CmsContentOperations::get_page_id_from_hierarchy', $position); + $id = Cache::get_instance()->call('CmsContentOperations::get_page_id_from_hierarchy', $position); if ($id) { $result = $this->get_node_by_id($id); } return $result; } function getNodeByHierarchy($position) { return $this->get_node_by_hierarchy($position); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_route.php b/lib/cmsms/classes/class.cms_route.php index a3a2499..503d369 100644 --- a/lib/cmsms/classes/class.cms_route.php +++ b/lib/cmsms/classes/class.cms_route.php @@ -1,92 +1,91 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ +use \silk\performance\Cache; + /** * Class to handle url routes for modules to handle pretty urls. * * @author Ted Kulp * @since 2.0 **/ class CmsRoute extends \silk\core\Object { var $module; var $regex; var $defaults; function __construct() { parent::__construct(); } /* public static function run($params, $page) { - $page_obj = SilkCache::get_instance()->call('CmsRoute::match_route', $page); + $page_obj = Cache::get_instance()->call('CmsRoute::match_route', $page); if ($page_obj) { - echo SilkCache::get_instance()->call(array($page_obj, 'display')); + echo Cache::get_instance()->call(array($page_obj, 'display')); } //TODO: Remove me - echo \SilkProfiler::get_instance()->report(); + echo \silk\performance\Profiler::get_instance()->report(); } */ public static function run($params, $page) { CmsModuleLoader::load_module_data(); //TODO: This is a full page cahce. It needs options. - //echo SilkCache::get_instance()->call('CmsRoute::_run', $params, $page); + //echo Cache::get_instance()->call('CmsRoute::_run', $params, $page); echo CmsRoute::_run($params, $page); - - //TODO: Remove me - echo \SilkProfiler::get_instance()->report(); } public static function _run($params, $page) { $page_obj = CmsRoute::match_route($page); if ($page_obj) { return $page_obj->display(); } //TODO: This is where we do some 404 logic. var_dump('404'); return ''; } public static function match_route($page) { $page_obj = null; if ($page == '' || $page == '/') $page_obj = CmsPage::find_by_default_page(true); else $page_obj = CmsPage::find_by_hierarchy_path($page); return $page_obj; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/modules/MenuManager/action.default.php b/modules/MenuManager/action.default.php index 77c22d2..9a601af 100644 --- a/modules/MenuManager/action.default.php +++ b/modules/MenuManager/action.default.php @@ -1,93 +1,93 @@ <?php -SilkProfiler::get_instance()->mark('Start of Menu Manager Display'); +\silk\performance\Profiler::get_instance()->mark('Start of Menu Manager Display'); $root_node = null; if (isset($params['start_page']) || isset($params['start_element'])) { $tree = CmsPageTree::get_instance(); $root_node = null; if (isset($params['start_page'])) { $root_node = $tree->get_node_by_alias($params['start_page']); } else { $root_node = $tree->get_node_by_hierarchy($params['start_element']); } if ($root_node != null) { if (isset($params['show_root_siblings']) && $params['show_root_siblings']) { $parent_node = $root_node->get_parent(); if ($parent_node != null) { $this->module->display_menu($parent_node->get_children(), $params); } } else if (isset($params['show_only_children']) && $params['show_only_children']) { $this->module->display_menu($root_node->get_children(), $params); } else { //Hack alert! //Make an array of one and pass that $ary = array($root_node); $this->module->display_menu($ary, $params); } } } else if (isset($params['start_level']) && $params['start_level'] > 1) { $tree = CmsPageTree::get_instance(); $curnode = $tree->get_node_by_id(cmsms()->variables['content_id']); if ($curnode != null) { $ids = explode('.', $curnode->id_hierarchy()); if (count($ids) >= $params['start_level'] - 2) { $parent_node = $tree->get_node_by_id($ids[$params['start_level'] - 2]); if ($parent_node != null && $parent_node->has_children()) { $this->module->display_menu($parent_node->get_children(), $params); } } } } else if (isset($params['items'])) { $result = array(); $tree = CmsPageTree::get_instance(); $items = explode(',', $params['items']); if ($tree != null && count($items) > 0) { foreach ($items as $oneitem) { $curnode = $tree->get_node_by_alias(trim($oneitem)); if ($curnode) { $result[] = $curnode; } } } if (count($result) > 0) { $params['number_of_levels'] = 1; $this->module->display_menu($result, $params); } } else { $this->module->display_menu(CmsPageTree::get_instance()->get_root_node()->get_children(), $params); } -SilkProfiler::get_instance()->mark('End of Menu Manager Display'); +\silk\performance\Profiler::get_instance()->mark('End of Menu Manager Display'); ?> \ No newline at end of file
tedkulp/cmsms-nouveau
ab8485435580088b8393b6b246ae8efd808a72ce
Some updates for the smarty and namespace changes
diff --git a/components/admin/controllers/class.admin_controller.php b/components/admin/controllers/class.admin_controller.php index d8780bd..64076a0 100644 --- a/components/admin/controllers/class.admin_controller.php +++ b/components/admin/controllers/class.admin_controller.php @@ -1,54 +1,54 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -class AdminController extends SilkControllerBase +class AdminController extends \silk\action\Controller { var $theme = 'default'; function __construct() { parent::__construct(); //Add a theme determination here $this->set_layout(); } function set_layout($name = 'main') { $this->layout_name = join_path('themes', $this->theme, $name); $this->set('layout_root_url', SilkRequest::get_calculated_url_base(true) . '/layouts/themes/' . $this->theme); $this->set('layout_root_path', join_path(ROOT_DIR, 'layouts', 'themes', $this->theme)); $this->set('silk_lib_root_url', SilkRequest::get_calculated_url_base(true) . '/lib/silk'); $this->set('cmsms_lib_root_url', SilkRequest::get_calculated_url_base(true) . '/lib/cmsms'); $this->set('root_url', SilkRequest::get_calculated_url_base(true) . '/'); //Setup the menu CmsAdminTree::fill_from_file(); $this->set('root_node', CmsAdminTree::get_instance()->get_root_node()); } function before_filter() { //$this->check_access(SilkUserSession::is_logged_in()); SilkDatabase::disable_caching(); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/controllers/class.login_controller.php b/components/admin/controllers/class.login_controller.php index 688b0d9..4704fc5 100644 --- a/components/admin/controllers/class.login_controller.php +++ b/components/admin/controllers/class.login_controller.php @@ -1,34 +1,34 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -class LoginController extends SilkControllerBase +class LoginController extends \silk\action\Controller { function index($params) { $user_session = new SilkUserSession($params['login']); if ($user_session->login()) { //redirect('') var_dump('login successful'); } $this->set_by_ref('user_session', $user_session); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/config/routes.php b/config/routes.php index d9dd4b6..db7401e 100644 --- a/config/routes.php +++ b/config/routes.php @@ -1,14 +1,16 @@ <?php +use \silk\action\Route; + //Automatically add some component routes -- see docs for details -//SilkRoute::build_default_component_routes(); +//Route::build_default_component_routes(); -SilkRoute::register_route("/admin/:controller/:action/:id", array("component" => 'admin')); -SilkRoute::register_route("/admin/:controller/:action", array("id" => '', "component" => 'admin')); -SilkRoute::register_route("/admin/:controller", array("id" => '', 'action' => 'index', "component" => 'admin')); -SilkRoute::register_route("/admin", array("id" => '', 'action' => 'index', "component" => 'admin', 'controller' => 'admin')); +Route::register_route("/admin/:controller/:action/:id", array("component" => 'admin')); +Route::register_route("/admin/:controller/:action", array("id" => '', "component" => 'admin')); +Route::register_route("/admin/:controller", array("id" => '', 'action' => 'index', "component" => 'admin')); +Route::register_route("/admin", array("id" => '', 'action' => 'index', "component" => 'admin', 'controller' => 'admin')); //Catch-all goes here -SilkRoute::register_route_callback("*", array("CmsRoute", "run"), array()); +Route::register_route_callback("*", array("CmsRoute", "run"), array()); ?> \ No newline at end of file diff --git a/index.php b/index.php index d686206..abd8278 100644 --- a/index.php +++ b/index.php @@ -1,31 +1,31 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- // The MIT License // // Copyright (c) 2008-2010 Ted Kulp // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. define('ROOT_DIR', dirname(__FILE__)); include_once('lib/silk/silk.api.php'); -SilkBootstrap::get_instance()->run(); +\silk\core\Bootstrap::get_instance()->run(); # vim:ts=4 sw=4 noet -?> \ No newline at end of file +?> diff --git a/layouts/themes/default/main.tpl b/layouts/themes/default/main.tpl index 2efe8ce..e01b6f9 100644 --- a/layouts/themes/default/main.tpl +++ b/layouts/themes/default/main.tpl @@ -1,115 +1,115 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="Generator" content="CMS Made Simple - Copyright (C) 2004-2009 Ted Kulp. All rights reserved." /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> <title>{$sitename} - {$title}</title> <link rel="stylesheet" href="{$layout_root_url}/css/kevin_tabs.css" type="text/css" /> <link rel="stylesheet" href="{$layout_root_url}/css/style.css" type="text/css" /> <!--[if IE]> <script type="text/javascript" src="{$layout_root_url}/includes/ie7-standard-p.js"></script> <![endif]--> <!-- <script type="text/javascript" src="{$layout_root_url}/includes/standard.js"></script> --> <!-- jQuery and tabs --> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.color.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.silk.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.tabs.js"></script> <!-- Tree stuff --> <link rel="stylesheet" type="text/css" href="{$cmsms_lib_root_url}/js/jstree/source/tree_component.css" /> <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/css.js"></script> <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/source/tree_component.js"></script> <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/jquery.metadata.js"></script> <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/jquery.cookie.js"></script> <script type="text/javascript"> //<![CDATA[ // form handling stuff $(document).ready(function() { setup_form(); }); function setup_form() { // disable all buttons $('button').addClass("disabled").attr("disabled", true); // but enable cancel $('button[@name="cancel"]').removeClass("disabled").attr("disabled", false); // assign event for every input $('form :input').one("change", function() { // on change call enable form enableForm(this.form); // mark in title if(document.title[0] != "*") { document.title = "*"+document.title; } }); // fill the default help text var help = $('#default_helptext').html(); $('#HelpContent').html(help); // assign an event for every form row $("div[id*='formrow']").bind("click", function() { var help = $(this).children("input[id*='help_']").val(); $('#HelpContent').html(help); }); } function enableForm(form) { var input = $('button', form); input.attr('disabled', false).removeClass('disabled'); } //}></script> {$headtext} <base href="{$root_url}" /> </head> <body> <div id="clean-container"> {include file="$layout_root_path/topmenu.tpl"} <div id="MainContent"> {capture assign="errmsg"}{php}echo SilkFlash::get_instance()->get('std');{/php}{/capture} <div class="pagemcontainer"{if empty($errmsg)} style="display: none;"{/if}> <p class="pagemessage" id="pagemessage"> {$errmsg} </p> </div> <div class="pagecontainer" id="pagecontent"> {$content} </div> <div class="clearb"></div> <div id="HelpContent"></div> </div><!-- end MainContent --> <div id="footer"> <a rel="external" href="http://www.cmsmadesimple.org"><b>CMS Made Simple</b></a> {$cms_version} "{$cms_versionname}"<br /><b>CMS Made Simple</b> is free software released under the General Public Licence. </div> </div><!--end clean-container--> </body> </html> -{php}echo SilkProfiler::get_instance()->report();{/php} \ No newline at end of file +{php}echo \SilkProfiler::get_instance()->report();{/php} \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_base.php b/lib/cmsms/classes/class.cms_module_base.php index c6de248..bce7dfe 100644 --- a/lib/cmsms/classes/class.cms_module_base.php +++ b/lib/cmsms/classes/class.cms_module_base.php @@ -1,110 +1,106 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ -class CmsModuleBase extends SilkObject +class CmsModuleBase extends \silk\core\Object { function __construct() { parent::__construct(); } public function get_name() { return get_class($this); } public function get_module_path() { if (is_subclass_of($this, 'CmsModuleBase')) { return join_path(ROOT_DIR, 'modules' , $this->get_name()); } else { return dirname(__FILE__); } } public static function cms_module_plugin($params, &$smarty) { $module_name = coalesce_key($params, 'module', ''); $action = coalesce_key($params, 'action', 'default'); if ($module_name != '') { $module = CmsModuleLoader::get_module_class($module_name); if ($module) { //@ob_start(); $id = '1'; $request = $module->create_request_instance($id, $returnid); $result = $request->do_action_base($action, $params); if ($result !== FALSE) { echo $result; } //$modresult = @ob_get_contents(); //@ob_end_clean(); //return $modresult; } } } function create_request_instance($id, $return_id = '') { return new CmsModuleRequest($this, $id, $return_id); } /** * Register a plugin to smarty with the * name of the module. This method should be called * from the module constructor, or from the setup() * method. */ public function register_module_plugin($plugin_name = '', $method_name = 'function_plugin') { if ($plugin_name == '') $plugin_name = $this->get_name(); - smarty()->register_function($plugin_name, array($this, $method_name)); + smarty()->register->templateFunction($plugin_name, array($this, $method_name)); } /** * Given a template in a variable, this method processes it through smarty * note, there is no caching involved. */ public function process_template_from_data($data) { $smarty = smarty(); - $smarty->_compile_source('temporary template', $data, $_compiled ); - @ob_start(); - $smarty->_eval('?>' . $_compiled); - $_contents = @ob_get_contents(); - @ob_end_clean(); + $_contents = $smarty->fetch("string:" . $data); return $_contents; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_loader.php b/lib/cmsms/classes/class.cms_module_loader.php index 63c39d1..e6a6def 100644 --- a/lib/cmsms/classes/class.cms_module_loader.php +++ b/lib/cmsms/classes/class.cms_module_loader.php @@ -1,286 +1,286 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ -class CmsModuleLoader extends SilkObject +class CmsModuleLoader extends \silk\core\Object { public static $module_list = null; function __construct() { parent::__construct(); } public static function load_module_data() { $files = CmsModuleLoader::find_module_info_files(); //Actually slower if it's cached -- have to retest with lots of modules $installed_data = SilkCache::get_instance()->call('CmsModuleLoader::get_installed_module_details'); $module_list = array(); foreach ($files as $one_file) { $module_data = self::xmlify_module_info_file($one_file); $module_data = self::inject_installed_data_for_module($module_data, $installed_data); $module_list[$module_data['name']] = $module_data; } self::check_core_version($module_list); self::check_dependencies($module_list); self::$module_list = $module_list; } public static function check_core_version(&$module_list) { foreach ($module_list as &$one_module) { if (isset($one_module['minimum_core_version'])) { if (version_compare($one_module['minimum_core_version'], '2.0', '>')) //Use a real version number here { $one_module['meets_minimum_core'] = false; $one_module['active'] = false; } } } } public static function check_dependencies(&$module_list) { foreach ($module_list as $one_module) { self::check_dependencies_for_module($one_module['name'], $module_list); } } public static function check_dependencies_for_module($module_name, &$module_list) { //Make sure we haven't done this one yet -- no point in repeating if (!isset($module_list[$module_name]['meets_dependencies'])) { $module_list[$module_name]['meets_dependencies'] = true; if (isset($module_list[$module_name]['dependencies']) && is_array($module_list[$module_name]['dependencies'])) { //Hack for handling 1 module dependency if (isset($module_list[$module_name]['dependencies']['module'])) { $tmp = $module_list[$module_name]['dependencies']['module']; unset($module_list[$module_name]['dependencies']['module']); $module_list[$module_name]['dependencies'][0]['module'] = $tmp; } for ($i = 0; $i < count($module_list[$module_name]['dependencies']); $i++) { //If a module dependency (only kind for now) if (isset($module_list[$module_name]['dependencies'][$i]['module'])) { $one_dep = $module_list[$module_name]['dependencies'][$i]['module']; //Does this dependency exist at all? if (isset($module_list[$one_dep['name']])) { //Make sure we process any dependencies first self::check_dependencies_for_module($one_dep['name'], $module_list); //Now that it's processed, check for active and installed_version stuff if ($module_list[$one_dep['name']]['active'] == false) { //var_dump('parent is not active: ' . $one_dep['name'] . ' from ' . $module_name); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } else if (isset($one_dep['minimum_version']) && version_compare($one_dep['minimum_version'], $module_list[$one_dep['name']]['installed_version'], '>')) { //var_dump('does not meet minimum version: ' . $one_dep['name'] . ' from ' . $module_name); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } } else { //var_dump('does not exist: ' . $one_dep['name']); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } } } } } } public static function get_proper_module_case($name) { if (self::$module_list != null) { foreach (self::$module_list as $k=>$v) { if (strtolower($k) == strtolower($name)) { return $k; } } } return name; } public static function get_module_class($name) { if (self::$module_list != null) { //Make sure we can call modules without checking case $name = self::get_proper_module_case($name); if (isset(self::$module_list[$name]) && self::$module_list[$name]['active'] == true) { if (isset(self::$module_list[$name]['object'])) { return self::$module_list[$name]['object']; } else { require_once(join_path(ROOT_DIR, 'modules', $name, $name . '.module.php')); if (class_exists($name) && is_subclass_of($name, 'CmsModuleBase')) { if (isset(self::$module_list[$name]['dependencies'])) { foreach (self::$module_list[$name]['dependencies'] as $dep) { self::get_module_class($dep['module']['name']); } } //var_dump('Instantiating: ' . $name); self::$module_list[$name]['object'] = new $name(); self::$module_list[$name]['object']->setup(); return self::$module_list[$name]['object']; } } } } return null; } public static function is_installed($name) { if (isset(self::$module_list[$name]) && isset(self::$module_list[$name]['installed'])) return self::$module_list[$name]['installed']; return false; } public static function is_active($name) { if (isset(self::$module_list[$name]) && isset(self::$module_list[$name]['active'])) return self::$module_list[$name]['active']; return false; } public static function get_installed_module_details() { $db_prefix = db_prefix(); return db()->GetAll("select * from {$db_prefix}modules"); } public static function inject_installed_data_for_module($module_data, $installed_data) { $module_data['installed'] = false; $module_data['active'] = false; $module_data['installed_version'] = $module_data['version']; $module_data['needs_upgrade'] = false; $module_data['meets_minimum_core'] = true; foreach($installed_data as $one_row) { if ($one_row['module_name'] == $module_data['name']) { $module_data['installed'] = true; $module_data['active'] = ($one_row['active'] == '1' ? true : false); $module_data['installed_version'] = $one_row['version']; $module_data['needs_upgrade'] = version_compare($module_data['installed_version'], $one_row['version'], '<'); } } return $module_data; } public static function xmlify_module_info_file($file) { $xml = simplexml_load_file($file); return self::convert_xml_to_array($xml); } public static function convert_xml_to_array($xml) { if (!($xml->children())) { return (string) $xml; } foreach ($xml->children() as $child) { $name = $child->getName(); if (count($xml->$name) == 1) { $element[$name] = self::convert_xml_to_array($child); } else { $element[][$name] = self::convert_xml_to_array($child); } } return $element; } public static function find_module_info_files() { $filelist = array(); $dir = join_path(ROOT_DIR, 'modules'); if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..') { $mod_dir = join_path($dir, $file); if (is_dir($mod_dir)) { $mod_info_file = join_path($dir, $file, $file . '.info.xml'); if (is_file($mod_info_file) && is_readable($mod_info_file)) { $filelist[] = $mod_info_file; } } } } closedir($dh); } } return $filelist; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_request.php b/lib/cmsms/classes/class.cms_module_request.php index 8f36f73..944ecc2 100644 --- a/lib/cmsms/classes/class.cms_module_request.php +++ b/lib/cmsms/classes/class.cms_module_request.php @@ -1,546 +1,546 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ /** * Class to represent one module "request". Basically a wrapper * object to hold a call to a module's action. It will hold * specifc module "session" variables, and also hold methods only * used during a session, including form generation. * * @package cmsms * @author Ted Kulp * @version $Revision$ * @modifiedby $LastChangedBy$ * @lastmodified $Date$ * @license GPL */ -class CmsModuleRequest extends SilkObject +class CmsModuleRequest extends \silk\core\Object { var $module = null; var $id = ''; var $return_id = ''; function __construct($module, $id, $return_id = '') { parent::__construct(); $this->module = $module; $this->id = $id; $this->return_id = $return_id; } /** * Getter overload method. Called when a field * does not exist in the object's variable list. * * @param string The field to look up * @return mixed The value for that field, if it exists * @author Ted Kulp **/ function __get($n) { if ($this->module != null) { if (property_exists($this->module, $n)) { return $this->module->$n; } } } /** * Setter overload method. Called when a field * does not exist in the object's variable list. * * @param string The field to set * @param mixed The value to set for said field * @return void * @author Ted Kulp **/ function __set($n, $val) { if ($this->module != null) { if (property_exists($this->module, $n)) { $this->module->$n = $val; } } } /** * Caller overload method. Called when a method does not exist. * * @param string The name of the method called * @param array The parameters sent along with that method call * @return mixed The result of the method call * @author Ted Kulp **/ function __call($function, $arguments) { if ($arguments == null) $arguments = array(); if ($this->module != null) { if (method_exists($this->module, $function)) { return call_user_func_array(array($this->module, $function), $arguments); } } } /** * Used for navigation between "pages" of a module. Forms and links should * pass an action with them so that the module will know what to do next. * By default, DoAction will be passed 'default' and 'defaultadmin', * depending on where the module was called from. If being used as a module * or content type, 'default' will be passed. If the module was selected * from the list on the admin menu, then 'defaultadmin' will be passed. * * @param string Name of the action to perform * @param string The ID of the module * @param string The parameters targeted for this module */ public function do_action($action_name, $params) { //In case the module overrides it if (method_exists($this->module, 'do_action')) { return $this->module->do_action($this, $action_name, $params); } $return_id = $this->return_id; //avoid confusion $returnid = $return_id; if ($action_name != '') { $filename = join_path($this->module->get_module_path(), 'action.' . $action_name . '.php'); if (@is_file($filename)) { { $db = db(); //$config = cms_config(); $smarty = smarty(); $id = $this->id; $smarty->assignByRef('request', $this); $smarty->assign('module_action',$action_name); include($filename); } } } } public function do_action_base($name, $incoming_params) { return $this->do_action($name, $incoming_params); } static public function strip_extra_params(&$params, $default_params, $other_params_key = '') { $extra_params = array_diff_key($params, $default_params); $params = $default_params; if ($other_params_key != '' && isset($params[$other_params_key]) && is_array($params[$other_params_key])) { $extra_params = array_merge($extra_params, $params[$other_params_key]); unset($params[$other_params_key]); } return $extra_params; } static public function create_start_tag($name, $params, $self_close = false, $extra_html = '') { $text = "<{$name}"; foreach ($params as $key=>$value) { $text .= " {$key}=\"{$value}\""; } if ($extra_html != '') { $text .= " {$extra}"; } $text .= ($self_close ? ' />' : '>'); return $text; } static public function create_end_tag($name) { return "</{$name}>"; } /** * Returns the start of a module form\n * Parameters: * - 'action' - The action that this form should do when the form is submitted. Defaults to 'default'. * - 'method' - Method to put in the form tag. Defaults to 'post'. * - 'enctype' - Optional enctype for the form. Only real option is 'multipart/form-data'. Defaults to null. * - 'inline' - Boolean to tell whether or not we want the form's result to be "inline". Defaults to false. * - 'id_suffix' - Text to append to the end of the id and name of the form. Defaults to ''. * - 'extra' - Text to append to the <form>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'use_current_page_as_action' - A flag to determine if the action should just * redirect back to this exact page. Defaults to false. * - 'params' - An array of key/value pairs to add as extra hidden parameters. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as hidden * variables to the form and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp **/ public function create_form_start($params = array(), $check_keys = false) { $default_params = array( 'action' => coalesce_key($params, 'action', 'default', FILTER_SANITIZE_URL), 'method' => coalesce_key($params, 'method', 'post', FILTER_SANITIZE_STRING), 'enctype' => coalesce_key($params, 'enctype', '', FILTER_SANITIZE_STRING), 'inline' => coalesce_key($params, 'inline', false, FILTER_VALIDATE_BOOLEAN), 'id_suffix' => coalesce_key($params, 'id_suffix', '', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'use_current_page_as_action' => coalesce_key($params, 'use_current_page_as_action', false, FILTER_VALIDATE_BOOLEAN), 'params' => coalesce_key($params, 'params', array()), 'id' => coalesce_key($params, 'id', $this->id), 'return_id' => coalesce_key($params, 'return_id', $this->return_id) ); $default_params['html_id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['id'].$default_params['action'].$default_params['id_suffix']), FILTER_SANITIZE_STRING ); $default_params['html_name'] = coalesce_key($params, 'html_name', $default_params['html_id'], FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Strip out any straggling parameters to their own array //Merge in anything if it was passed in the params key to the method $extra_params = $this->strip_extra_params($params, $default_params, 'params'); $form_count = cmsms()->get('formcount'); if ($form_count == null) $form_count = 1; $mact = $this->module->get_name().','.$params['id'].','.$params['action'].','.($inline == true?1:0); $goto = ''; $use_current_page_as_action = $params['use_current_page_as_action']; unset($params['use_current_page_as_action']); if ($use_current_page_as_action) $goto = CmsRequest::get_requested_uri(); else $goto = ($params['return_id'] == '' ? 'moduleinterface.php' : 'index.php'); $form_params = array( 'id' => $params['html_id'], 'name' => $params['html_name'], 'method' => $params['method'], 'action' => $goto ); if ($enctype != '') { $form_params['enctype'] = $params['enctype']; } $extra = ''; if ($params['extra']) { $extra = $params['extra']; unset($params['extra']); } $text .= $this->create_start_tag('form', $form_params, false, $extra); $text .= $this->create_start_tag('div', array('class' => 'hidden')); if (!$use_current_page_as_action) $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => 'mact', 'value' => $mact), true); if ($params['return_id'] != '') { $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['id'].'returnid', 'value' => $params['return_id']), true); if ($inline) { $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => cms_config()->get('query_var'), 'value' => $params['return_id']), true); } } foreach ($extra_params as $key=>$value) { if ($key != 'module' && $key != 'action' && $key != 'id') $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['id'].$key, 'value' => $value), true); } $text .= $this->create_end_tag('div'); //end "hidden" cmsms()->set('formcount', $form_count + 1); return $text; } /** * Returns the end of a module form\n * Parameters: * - none * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as hidden * variables to the form and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp **/ public function create_form_end($params = array(), $check_keys = false) { return $this->create_end_tag('form'); } /** * Returns the xhtml equivalent of an input textbox. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant. * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'value' - The value of the field. Defaults to ''. * - 'size' - The length of the input field when displayed. Defaults to 10. * - 'maxlength' - The max length of the value allowed. Defaults to 255. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'label' - If set to a string, a label will be created with the proper "for" value for the input. * - 'label_extra' - Text to append to the <label>-statement, ex. for javascript-validation code. Defaults to ''. * - 'in_between_text' - Text to put between the label and input fields. Defaults to ''. * - 'password' - Boolean to tell whether or not we want it to be a password input. Defaults to false. * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_text($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), 'size' => coalesce_key($params, 'size', 25, FILTER_SANITIZE_NUMBER_INT), 'maxlength' => coalesce_key($params, 'maxlength', 255, FILTER_SANITIZE_NUMBER_INT), 'extra' => coalesce_key($params, 'extra', ''), 'label' => coalesce_key($params, 'label', '', FILTER_SANITIZE_STRING), 'label_extra' => coalesce_key($params, 'label_extra', ''), 'in_between_text' => coalesce_key($params, 'in_between_text', ''), 'password' => coalesce_key($params, 'password', false, FILTER_VALIDATE_BOOLEAN), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); $params['type'] = ($params['password'] == true ? 'password' : 'text'); $text = ''; if ($params['label'] != '') { $text .= $this->create_start_tag('form', array('for' => $params['id']), true, $params['label_extra']); $text .= $params['in_between_text']; } unset($params['label']); unset($params['label_extra']); $text .= $this->create_start_tag('input', $params, true, $extra); return $text; } /** * Returns the xhtml equivalent of an hidden input. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'value' - The value of the field. Defaults to ''. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_hidden($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); $params['type'] = 'hidden'; //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); return $this->create_start_tag('input', $params, true, $extra); } /** * Returns the xhtml equivalent of an checkbox input. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant. Also adds the feature * of making sure that even unchecked checkboxes return a value back to the form.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'checked' - Boolean of whether or not the checkbox is checked. Defaults to false. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_checkbox($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'checked' => coalesce_key($params, 'checked', false, FILTER_VALIDATE_BOOLEAN), 'extra' => coalesce_key($params, 'extra', ''), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); $params['type'] = 'checkbox'; $params['value'] = '1'; if ($params['checked']) $params['checked'] = 'checked'; else unset($params['checked']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); return $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['name'], 'value' => '0'), true) . $this->create_start_tag('input', $params, true, $extra); } /** * Returns the xhtml equivalent of an submit button. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'value' - The value (text) of the button. Defaults to ''. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'image' - The name of an image to display instead of the text. Defaults to ''. * - 'confirm_text' - If set, a message to display to confirm the click. Defaults to ''. * - 'params' - An array of key/value pairs to add as attributes to the input tag. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * - 'reset' - Boolean of whether or not this is a reset buton. Defaults to false. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_submit($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'image' => coalesce_key($params, 'image', '', FILTER_SANITIZE_STRING), 'confirm_text' => coalesce_key($params, 'confirm_text', '', FILTER_SANITIZE_STRING), 'reset' => coalesce_key($params, 'reset', false, FILTER_VALIDATE_BOOLEAN), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), diff --git a/lib/cmsms/classes/class.cms_page.php b/lib/cmsms/classes/class.cms_page.php index 44d1e82..a1a0412 100644 --- a/lib/cmsms/classes/class.cms_page.php +++ b/lib/cmsms/classes/class.cms_page.php @@ -1,239 +1,239 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** * Base page class. Extend this to create new content types for * the system. * * @author Ted Kulp * @since 2.0 **/ class CmsPage extends SilkObjectRelationalMapping { var $table = 'pages'; var $params = array('id' => -1, 'template_id' => -1, 'active' => true, 'default_content' => false, 'parent_id' => -1, 'lft' => 1, 'rgt' => 1, 'blocks' => array()); #Stuff needed to do a doppleganger for CmsNode -- Multiple inheritence would rock right now var $tree = null; var $parentnode = null; var $children = array(); function __construct() { parent::__construct(); } function setup() { $this->create_belongs_to_association('template', 'CmsTemplate', 'template_id'); $this->assign_acts_as('NestedSet'); } function display() { - smarty()->register_object('current_page', $this); + smarty()->register->templateObject('current_page', $this); $template_content = $this->template->process(); return $template_content; } function get_url($rewrite = true, $lang = '') { $url = SilkRequest::get_calculated_url_base() . $this->hierarchy_path(); /* $config = cms_config(); $alias = ($this->alias != ''?$this->alias:$this->id); if ($config["assume_mod_rewrite"] && $rewrite == true) { $url = $config['root_url']. '/' . ($lang != '' ? "$lang/" : '') . $this->HierarchyPath() . (isset($config['page_extension'])?$config['page_extension']:'.html'); } else { if (isset($_SERVER['PHP_SELF']) && $config['internal_pretty_urls'] == true) { $url = $config['root_url'] . '/index.php/' . ($lang != '' ? "$lang/" : '') . $this->HierarchyPath() . (isset($config['page_extension']) ? $config['page_extension '] : '.html'); } else { $url = $config['root_url'] . '/index.php?' . $config['query_var'] . '=' . $alias . ($lang != '' ? '&amp;lang=' . $lang : ''); } } */ return $url; } function get_content_block($block_name = 'default', $can_return_new = false) { if (isset($this->blocks[$block_name])) { if (isset($this->blocks[$block_name]['id'])) { $content = orm('CmsContentBase')->find_by_id($this->blocks[$block_name]['id']); if ($content != null) { return $content; } } } if ($can_return_new) return new CmsHtmlContent(); //TODO: Fix me else return null; } function get_content($block_name = 'default') { $block = $this->get_content_block($block_name); if ($block != null) { return $block->get_content(); } return '<!-- No content found for ' . $block_name . ' -->'; } /** * Function content types to use to say whether or not they should show * up in lists where parents of content are set. This will default to true, * but should be used in cases like Separator where you don't want it to * have any children. * * @since 0.11 */ function wants_children() { return true; } function can_preview() { return false; } function template_name() { $tmp = $this->template; if ($tmp) return $tmp->name; return ''; } function add_child($node) { $node->set_parent($this); $node->tree = $this->tree; $this->children[] = $node; } function get_tree() { return $this->tree; } function has_children() { return $this->rgt > $this->lft + 1; } function depth() { $depth = 0; $currLevel = &$this; while ($currLevel->parentnode) { $depth++; $currLevel = &$currLevel->parentnode; } return $depth; } function get_level() { return $this->depth(); } function getLevel() { return $this->depth(); } function get_parent() { return $this->parentnode; } function set_parent($node) { $this->parentnode = $node; } function get_children_count() { return count($this->children); } function getChildrenCount() { return $this->get_children_count(); } function &get_children() { if ($this->has_children()) { //We know there are children, but no nodes have been //created yet. We should probably do that. if (!$this->children_loaded()) { //$this->tree->load_child_nodes(-1, $this->lft, $this->rgt); $this->tree->load_child_nodes($this->id); } } return $this->children; } function &get_flat_list() { $return = array(); if ($this->has_children()) { for ($i=0; $i<count($this->children); $i++) { $return[] = &$this->children[$i]; $return = array_merge($return, $this->children[$i]->get_flat_list()); } } return $return; } function &getFlatList() { $tmp =& $this->get_flat_list(); return $tmp; } } ?> diff --git a/lib/cmsms/classes/class.cms_route.php b/lib/cmsms/classes/class.cms_route.php index 7a54141..a3a2499 100644 --- a/lib/cmsms/classes/class.cms_route.php +++ b/lib/cmsms/classes/class.cms_route.php @@ -1,92 +1,92 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ /** * Class to handle url routes for modules to handle pretty urls. * * @author Ted Kulp * @since 2.0 **/ -class CmsRoute extends SilkObject +class CmsRoute extends \silk\core\Object { var $module; var $regex; var $defaults; function __construct() { parent::__construct(); } /* public static function run($params, $page) { $page_obj = SilkCache::get_instance()->call('CmsRoute::match_route', $page); if ($page_obj) { echo SilkCache::get_instance()->call(array($page_obj, 'display')); } //TODO: Remove me - echo SilkProfiler::get_instance()->report(); + echo \SilkProfiler::get_instance()->report(); } */ public static function run($params, $page) { CmsModuleLoader::load_module_data(); //TODO: This is a full page cahce. It needs options. //echo SilkCache::get_instance()->call('CmsRoute::_run', $params, $page); echo CmsRoute::_run($params, $page); //TODO: Remove me - echo SilkProfiler::get_instance()->report(); + echo \SilkProfiler::get_instance()->report(); } public static function _run($params, $page) { $page_obj = CmsRoute::match_route($page); if ($page_obj) { return $page_obj->display(); } //TODO: This is where we do some 404 logic. var_dump('404'); return ''; } public static function match_route($page) { $page_obj = null; if ($page == '' || $page == '/') $page_obj = CmsPage::find_by_default_page(true); else $page_obj = CmsPage::find_by_hierarchy_path($page); return $page_obj; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_smarty.php b/lib/cmsms/classes/class.cms_smarty.php index c9d0101..4ceda83 100644 --- a/lib/cmsms/classes/class.cms_smarty.php +++ b/lib/cmsms/classes/class.cms_smarty.php @@ -1,70 +1,70 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #BUT withOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** * Represents a template in the database. * * @author Ted Kulp * @since 2.0 **/ class CmsSmarty extends SilkSmarty { function __construct() { parent::__construct(); - $this->register->resource("template", array(&$this, "template_get_template", + $this->register->resource("template", array($this, "template_get_template", "template_get_timestamp", "db_get_secure", "db_get_trusted")); } - function template_get_template($tpl_name, &$tpl_source, &$smarty_obj) + function template_get_template($tpl_name, &$tpl_source, $smarty_obj) { - $template = orm('CmsTemplate')->find_by_id($tpl_name); + $template = CmsTemplate::find_by_id($tpl_name); if ($template) { $tpl_source = $template->content; return true; } return false; } - function template_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj) + function template_get_timestamp($tpl_name, &$tpl_timestamp, $smarty_obj) { - $template = orm('CmsTemplate')->find_by_id($tpl_name); + $template = CmsTemplate::find_by_id($tpl_name); if ($template) { $tpl_timestamp = $template->modified_date->timestamp(); return true; } return false; } function db_get_secure($tpl_name, &$smarty_obj) { // assume all templates are secure return true; } function db_get_trusted($tpl_name, &$smarty_obj) { // not used for templates } } ?> \ No newline at end of file diff --git a/lib/cmsms/plugins/function.content.php b/lib/cmsms/plugins/function.content.php index 7bc011a..e2b82b0 100644 --- a/lib/cmsms/plugins/function.content.php +++ b/lib/cmsms/plugins/function.content.php @@ -1,32 +1,32 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function smarty_function_content($params, &$smarty) { $block_name = coalesce_key($params, 'block', coalesce_key($params, 'name', 'default')); - $page = smarty()->get_registered_object('current_page'); + $page = smarty()->getRegisteredObject('current_page'); if ($page) { return $page->get_content($block_name); } return '<!-- No content for block: ' . $block_name . ' on this page. -->'; } # vim:ts=4 sw=4 noet ?> diff --git a/modules/MenuManager/MenuManager.module.php b/modules/MenuManager/MenuManager.module.php index ab2c941..5d580e6 100644 --- a/modules/MenuManager/MenuManager.module.php +++ b/modules/MenuManager/MenuManager.module.php @@ -1,178 +1,178 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2009 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class MenuManager extends CmsModuleBase { function __construct() { parent::__construct(); } function setup() { $this->register_module_plugin('menu_children', 'menu_children_plugin_callback'); } - public function menu_children_plugin_callback($params, &$smarty) + public function menu_children_plugin_callback($params, $smarty) { $orig_params = $smarty->getTemplateVars('orig_params'); $params = array_merge($orig_params, $params); if (!isset($params['node'])) { return; } if ($params['node']->has_children()) { $this->current_depth++; //Handle number_of_levels param if (!isset($params['number_of_levels']) || $params['number_of_levels'] > $this->current_depth) { //Handle collapse param if (!isset($params['collapse']) || $params['collapse'] != true || starts_with(cmsms()->variables['position'] . '.', $params['node']->hierarchy . '.')) { $this->display_menu($params['node']->get_children(), $params, false); } } $this->current_depth--; } } public function display_menu(&$nodes, $params, $first_call = true) { $usefile = true; //$lang = CmsMultiLanguage::get_client_language(); $lang = 'en_US'; $mdid = md5('12345'); //md5(cmsms()->variables['content_id'].implode('|', $params).$lang); $tpl_name = coalesce_key($params, 'template', ''); if (!ends_with($tpl_name, '.tpl')) { $usefile = false; } if (is_array($nodes)) { $count = 0; foreach ($nodes as &$node) { $this->add_fields_to_node($node); $node->show = $this->should_show_node($node, $params); //Numeric Stuff $node->first = ($count == 0); $node->last = ($count + 1 == count($nodes)); $node->index = $count; $count++; } $smarty = smarty(); $smarty->assign('count', count($nodes)); $smarty->assignByRef('nodelist', $nodes); if ($first_call) { $smarty->assign('orig_params', $params); $this->current_depth = 1; } //echo $this->process_template_from_database($id, $return_id, 'menu_template', $tpl_name); echo $this->process_template_from_data($this->get_default_template()); } } public function add_fields_to_node(&$node) { $node->url = $node->get_url(true, $lang); $node->menutext = $node->get_property_value('menu_text', $lang); $node->haschildren = $node->has_children(); $node->target = ''; if ($node->has_property('target')) $node->target = $node->get_property_value('target'); $node->depth = $this->current_depth; } public function should_show_node(&$node, $params) { $include = true; $exclude = false; if (isset($params['includeprefix'])) { $include = false; $prefixes = explode(',', $params['includeprefix']); foreach ($prefixes as $oneprefix) { if (starts_with(strtolower($node->alias), strtolower($oneprefix))) { $include = true; break; } } } if (isset($params['excludeprefix'])) { $prefixes = explode(',', $params['excludeprefix']); foreach ($prefixes as $oneprefix) { if (starts_with(strtolower($node->alias), strtolower($oneprefix))) { $exclude = true; break; } } } $should_show = $node->active && $node->show_in_menu && ($include && !$exclude); //Override is show_all is true if (isset($params['show_all']) && $params['show_all']) $should_show = true; return $should_show; } function get_default_template() { - return '[[if $count > 0]] + return '{if $count > 0} <ul> - [[foreach from=$nodelist item=node]] - [[if $node->show]] + {foreach from=$nodelist item=node} + {if $node->show} <li> - <a href="[[$node->get_url()]]">[[$node->menu_text]]</a> - [[menu_children node=$node]] + <a href="{$node->get_url()}">{$node->menu_text}</a> + {menu_children node=$node} </li> - [[/if]] - [[/foreach]] + {/if} + {/foreach} </ul> -[[/if]] +{/if} '; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file
tedkulp/cmsms-nouveau
8c27fbe189824265f17622ffd3694e697d14e8d4
Changes for smarty 3
diff --git a/components/admin/controllers/class.page_controller.php b/components/admin/controllers/class.page_controller.php index a501269..33d662c 100644 --- a/components/admin/controllers/class.page_controller.php +++ b/components/admin/controllers/class.page_controller.php @@ -1,139 +1,140 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class PageController extends AdminController { function index($params) { $this->set('tree', CmsPageTree::get_instance()); } function main_content($params) { $page_id = substr($params['node_id'], 5); $page = CmsPage::find_by_id($page_id); $this->set('page', $page); $ajax = new SilkAjax(); $ajax->replace_html('#main_section', $this->render_partial('main_section.tpl')); $ajax->script('reset_main_content();'); return $ajax->get_result(); } function update_content($params) { $ajax = new SilkAjax(); $page = CmsPage::load($params['page_id']); $name = substr($params['name'], 11, -1); $content = $page->get_content_block($name, true); if ($content == null || get_class($content) != $params['value']) $content = new $params['value']; $target_id = str_replace('select_', '', $params['parent_id']); $ajax->replace_html('#' . $target_id, $content->get_edit_form()); $ajax->script('setup_content();'); return $ajax->get_result(); } function update_page($params) { $page = CmsPage::load($params['page']); $ajax = new SilkAjax(); if ($page) { $page->update_parameters($params['page']); } $this->set('page', $page); $ajax->replace_html('#main_section', $this->render_partial('main_section.tpl')); $ajax->script('reset_main_content();'); return $ajax->get_result(); } function check_unique_alias($params) { $ajax = new SilkAjax(); $count = CmsPage::find_count(array('conditions' => array('unique_alias = ? AND id != ?', $params['alias'], $params['page_id']))); if ($params['alias'] == '') { $ajax->replace_html('#unique_alias_ok', 'Empty'); $ajax->script('$("#unique_alias_ok").attr("style", "color: red;")'); } else if ($count > 0 || $params['alias'] == '') { $ajax->replace_html('#unique_alias_ok', 'Used'); $ajax->script('$("#unique_alias_ok").attr("style", "color: red;")'); } else { $ajax->replace_html('#unique_alias_ok', 'Ok'); $ajax->script('$("#unique_alias_ok").attr("style", "color: green;")'); } $ajax->script('reset_main_content();'); return $ajax->get_result(); } function check_alias($params) { $ajax = new SilkAjax(); $count = CmsPage::find_count(array('conditions' => array('alias = ? AND id != ?', $params['alias'], $params['page_id']))); if ($params['alias'] == '') { $ajax->replace_html('#alias_ok', 'Empty'); $ajax->script('$("#alias_ok").attr("style", "color: red;")'); } else if ($count > 0 || $params['alias'] == '') { $ajax->replace_html('#alias_ok', 'Used'); $ajax->script('$("#alias_ok").attr("style", "color: red;")'); } else { $ajax->replace_html('#alias_ok', 'Ok'); $ajax->script('$("#alias_ok").attr("style", "color: green;")'); } $ajax->script('reset_main_content();'); return $ajax->get_result(); } function save($params) { $ajax = new SilkAjax(); if (isset($params['save']) || isset($params['apply'])) { $page = CmsPage::load($params['page']); + var_dump($params['page']); if ($page) { $page->update_parameters($params['page']); if ($page->save()) { $ajax->show('.pagemcontainer'); $ajax->replace_html('#pagemessage', 'Page Saved'); $ajax->script('$(".pagemcontainer").fadeOut(2000)'); return $ajax->get_result(); } } $ajax->show('.pagemcontainer'); $ajax->replace_html('#pagemessage', 'Error Saving Page'); $ajax->script('$(".pagemcontainer").fadeOut(2000)'); } return $ajax->get_result(); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/helpers/class.page_helper.php b/components/admin/helpers/class.page_helper.php index a97eb4b..561cb8d 100644 --- a/components/admin/helpers/class.page_helper.php +++ b/components/admin/helpers/class.page_helper.php @@ -1,41 +1,41 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class PageHelper extends SilkHelperBase { - function page_template_dropdown_options($params, &$smarty) + function page_template_dropdown_options($params, $smarty) { $opt = array(); foreach (orm('CmsTemplate')->find_all_by_active(true) as $tpl) { $opt[$tpl->id] = $tpl->name; } return forms()->create_input_options(array('items' => $opt, 'selected_value' => $params['selected'])); } - function content_type_dropdown_options($params, &$smarty) + function content_type_dropdown_options($params, $smarty) { $opt = array(); $opt['CmsHtmlContent'] = 'HTML Content'; $opt['CmsOtherContent'] = 'Other Content'; return forms()->create_input_options(array('items' => $opt, 'selected_value' => $params['selected'])); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/helpers/class.page_template_helper.php b/components/admin/helpers/class.page_template_helper.php index e4dc484..072211b 100644 --- a/components/admin/helpers/class.page_template_helper.php +++ b/components/admin/helpers/class.page_template_helper.php @@ -1,44 +1,44 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class PageTemplateHelper extends SilkHelperBase { function test_plugin($params) { return 'doing some stuff'; } function modifier_test_mod($string) { return $string . " - modifying some stuff"; } - function block_another_test($params, $content, &$smarty, &$repeat) + function block_another_test($params, $content, $smarty, $repeat) { if(!$repeat) { if (isset($content)) { return 'block -- ' . $content . ' -- block'; } } } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/plugins/function.cms_validation_errors.php b/components/admin/plugins/function.cms_validation_errors.php index 0eadcb3..49c36a3 100644 --- a/components/admin/plugins/function.cms_validation_errors.php +++ b/components/admin/plugins/function.cms_validation_errors.php @@ -1,45 +1,45 @@ <?php #CMS - CMS Made Simple #(c)2004-2006 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -function smarty_function_cms_validation_errors($params, &$smarty) +function smarty_function_cms_validation_errors($params, $smarty) { $default_params = array( 'for' => coalesce_key($params, 'for', null), 'params' => coalesce_key($params, 'params', array()) ); $params = array_merge($default_params, forms()->strip_extra_params($params, $default_params, 'params')); unset($params['params']); if ($params['for'] != null && is_object($params['for'])) { if (isset($params['for']->validation_errors) && is_array($params['for']->validation_errors) && count($params['for']->validation_errors) > 0) { echo '<div class="pagemcontainer">'; echo '<p class="pagemessage">'; foreach ($params['for']->validation_errors as $err) { - echo '<img class="systemicon" title="Sucesso" alt="Sucesso" src="' . $smarty->get_template_vars('layout_root_url') . '/images/icons/system/stop.gif" />'.$err.'<br />'; + echo '<img class="systemicon" title="Sucesso" alt="Sucesso" src="' . $smarty->getTemplateVars('layout_root_url') . '/images/icons/system/stop.gif" />'.$err.'<br />'; } echo '</p>'; echo '</div>'; } } } ?> diff --git a/components/admin/plugins/function.img.php b/components/admin/plugins/function.img.php index 9c7d35d..d427df5 100644 --- a/components/admin/plugins/function.img.php +++ b/components/admin/plugins/function.img.php @@ -1,45 +1,45 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- // The MIT License // -// Copyright (c) 2008 Ted Kulp +// Copyright (c) 2008-2010 Ted Kulp // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -function smarty_function_img($params, &$smarty) +function smarty_function_img($params, $smarty) { if ($params['src']) { - $txt = '<img src="' . $smarty->get_template_vars('layout_root_url') . '/' . $params['src'] . '"'; + $txt = '<img src="' . $smarty->getTemplateVars('layout_root_url') . '/' . $params['src'] . '"'; if ($params['alt']) { $txt .= ' alt="' . $params['alt'] . '"'; unset($params['alt']); } if ($params['title']) { $txt .= ' title="' . $params['title'] . '"'; unset($params['title']); } $txt .= ' />'; return $txt; } } # vim:ts=4 sw=4 noet ?> diff --git a/components/admin/plugins/function.img_link.php b/components/admin/plugins/function.img_link.php index 8acd878..3b324af 100644 --- a/components/admin/plugins/function.img_link.php +++ b/components/admin/plugins/function.img_link.php @@ -1,47 +1,47 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- // The MIT License // -// Copyright (c) 2008 Ted Kulp +// Copyright (c) 2008-2010 Ted Kulp // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -function smarty_function_img_link($params, &$smarty) +function smarty_function_img_link($params, $smarty) { if ($params['src']) { - $txt = '<img src="' . $smarty->get_template_vars('layout_root_url') . '/' . $params['src'] . '"'; + $txt = '<img src="' . $smarty->getTemplateVars('layout_root_url') . '/' . $params['src'] . '"'; if ($params['alt']) { $txt .= ' alt="' . $params['alt'] . '"'; unset($params['alt']); } if ($params['title']) { $txt .= ' title="' . $params['title'] . '"'; unset($params['title']); } $txt .= ' />'; $params['text'] = $txt; unset($params['src']); } return forms()->create_link($params); } # vim:ts=4 sw=4 noet ?> diff --git a/components/admin/views/content/index.tpl b/components/admin/views/content/index.tpl index 61c443b..bda664a 100644 --- a/components/admin/views/content/index.tpl +++ b/components/admin/views/content/index.tpl @@ -1,35 +1,35 @@ <div class="pageoverflow"> <div class="pageheader">Content <span class="helptext"> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Stylesheets" rel="external"> - <img src="[[$layout_root_url]]/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> + <img src="{$layout_root_url}/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> </a> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Stylesheets" rel="external">Help</a> (new window) </span> </div> </div> <table cellspacing="0" class="pagetable"> <thead> <tr> <th class="pagew50">Template</th> <th class="pagepos">Active</th> <th class="pageicon">&nbsp;</th> <th class="pageicon">&nbsp;</th> </tr> </thead> <tbody id="tablebody"> - [[render_partial template='indextablebody.tpl']] + {render_partial template='indextablebody.tpl'} </tbody> </table> <div class="pageoptions"> <p class="pageoptions"> <span style="float: left;"> - <a href="[[link only_href='true' controller='stylesheet' action='add']]"><img src="[[$layout_root_url]]/images/icons/system/newobject.gif" class="systemicon" alt="Add Stylesheet" title="Add Stylesheet" /></a> - [[link html_class="pageoptions" text="Add Stylesheet" controller="stylesheet" action="add"]] + <a href="{link only_href='true' controller='stylesheet' action='add'}"><img src="{$layout_root_url}/images/icons/system/newobject.gif" class="systemicon" alt="Add Stylesheet" title="Add Stylesheet" /></a> + {link html_class="pageoptions" text="Add Stylesheet" controller="stylesheet" action="add"} </span> </p> </div> <br /> diff --git a/components/admin/views/login/index.tpl b/components/admin/views/login/index.tpl index 90704c4..5586aa7 100644 --- a/components/admin/views/login/index.tpl +++ b/components/admin/views/login/index.tpl @@ -1,19 +1,19 @@ -[[validation_errors for=$user_session]] +{validation_errors for=$user_session} -[[form]] +{form} -<div id="regular" [[if $params.login.openid ne '' or $smarty.request.openid_mode ne '']]style="display: none;"[[/if]]> -[[label for="login[username]"]]Username:[[/label]][[textbox name="login[username]" value=$params.login.username]]<br /> -[[label for="login[password]"]]Password:[[/label]][[password name="login[password]" value=$params.login.password]]<br /> +<div id="regular" {if $params.login.openid ne '' or $smarty.request.openid_mode ne ''}style="display: none;"{/if}> +{label for="login[username]"}Username:{/label}{textbox name="login[username]" value=$params.login.username}<br /> +{label for="login[password]"}Password:{/label}{password name="login[password]" value=$params.login.password}<br /> <a href="#" onclick="$('#regular').hide();$('#openid').show();return false;">Use OpenID</a> </div> -<div id="openid" [[if $params.login.openid eq '' and $smarty.request.openid_mode eq '']]style="display: none;"[[/if]]> -[[label for="login[openid]"]]Open ID:[[/label]][[textbox name="login[openid]" value=$params.login.openid]]<br /> +<div id="openid" {if $params.login.openid eq '' and $smarty.request.openid_mode eq ''}style="display: none;"{/if}> +{label for="login[openid]"}Open ID:{/label}{textbox name="login[openid]" value=$params.login.openid}<br /> <a href="#" onclick="$('#regular').show();$('#openid').hide();return false;">Use Username/Password</a> </div> -[[submit value="Submit"]] +{submit value="Submit"} -[[/form]] \ No newline at end of file +{/form} \ No newline at end of file diff --git a/components/admin/views/page/branch.tpl b/components/admin/views/page/branch.tpl index f468e61..f548bef 100644 --- a/components/admin/views/page/branch.tpl +++ b/components/admin/views/page/branch.tpl @@ -1,11 +1,10 @@ -[[foreach from=$subpages item='page']] +{foreach from=$subpages item='page'} <ul> - <li id="node_[[$page->id]]"> - <a href="#">[[$page->alias]]</a> - [[if $page->has_children()]] - [[assign var='subpages' value=$page->get_children()]] - [[render_partial template='branch.tpl']] - [[/if]] + <li id="node_{$page->id}"> + <a href="#">{$page->alias}</a> + {if $page->has_children()} + {render_partial template='branch.tpl' subpages=$page->get_children()} + {/if} </li> </ul> -[[/foreach]] \ No newline at end of file +{/foreach} \ No newline at end of file diff --git a/components/admin/views/page/content.tpl b/components/admin/views/page/content.tpl index 6c37858..1c197b0 100644 --- a/components/admin/views/page/content.tpl +++ b/components/admin/views/page/content.tpl @@ -1,12 +1,12 @@ -[[if $page->template]] - [[foreach from=$page->template->get_page_blocks() key='name' item='block' name='foo']] - [[assign var=block_obj value=$page->get_content_block($name, true)]] - [[if $block_obj]] - <h3>[[$name]]</h3> - <label>Content Type:</label> [[select class='content_type_picker' html_id="block_select_`$smarty.foreach.foo.index`" name="block_type[$name]"]][[content_type_dropdown_options selected=$block_obj.type]][[/select]]<br /> - <div id="block_[[$smarty.foreach.foo.index]]"> - [[$block_obj->get_edit_form($name)]] +{if $page->template} + {foreach from=$page->template->get_page_blocks() key='name' item='block' name='foo'} + {assign var=block_obj value=$page->get_content_block($name, true)} + {if $block_obj} + <h3>{$name}</h3> + <label>Content Type:</label> {select class='content_type_picker' html_id="block_select_`$smarty.foreach.foo.index`" name="block_type[$name]"}{content_type_dropdown_options selected=$block_obj.type}{/select}<br /> + <div id="block_{$smarty.foreach.foo.index}"> + {$block_obj->get_edit_form($name)} </div> - [[/if]] - [[/foreach]] -[[/if]] + {/if} + {/foreach} +{/if} diff --git a/components/admin/views/page/index.tpl b/components/admin/views/page/index.tpl index 683ca6b..56b98f1 100644 --- a/components/admin/views/page/index.tpl +++ b/components/admin/views/page/index.tpl @@ -1,95 +1,94 @@ -[[assign var='page' value=$tree->get_root_node()]] +{assign var='page' value=$tree->get_root_node()} <h2>Content</h2> <div style="width: 1000px; margin-top: 15px;"> <div id="content_tree" style="width: 240px; float: left; border-right: 1px solid black"> <ul> <li id="node_1" class="open"> <a href="#">ROOT</a> - [[if $page->has_children()]] - [[assign var='subpages' value=$page->get_children()]] - [[render_partial template='branch.tpl']] - [[/if]] + {if $page->has_children()} + {render_partial template='branch.tpl' subpages=$page->get_children()} + {/if} </li> </ul> </div> <div id="main_section" style="float: right; min-width: 750px; text-align: left;"> </div> </div> <br style="clear: both;" /> <script type="text/javascript"> //<![CDATA[ $('#content_tree').tree( { 'rules' : { 'draggable' : 'all' }, 'callback' : { 'onselect' : function(node, tree_obj) { if (node.id != 'node_1') { - silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'main_content'))[[/php]]', [{name:'node_id', value:node.id}]); + silk_ajax_call('{php}echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'main_content'));{/php}', [{ name:'node_id', value:node.id }]); } else { clear_main_content(); } }, 'ondeselect' : function(node, tree_obj) { clear_main_content(); } } } ); function clear_main_content() { $('#main_section').html(''); } function reset_main_content() { $('#module_page_tabs > ul').tabs(); setup_form(); $('#unique_alias').delayedObserver(function() { - silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_unique_alias'))[[/php]]', [{name:'alias', value:$('#unique_alias').val()}, {name:'page_id', value:$('#page_id').html()}]); + silk_ajax_call('{php}echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_unique_alias'));{/php}', [{ name:'alias', value:$('#unique_alias').val() }, { name:'page_id', value:$('#page_id').html() }]); }, 0.5); $('#alias').delayedObserver(function() { - silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_alias'))[[/php]]', [{name:'alias', value:$('#alias').val()}, {name:'page_id', value:$('#page_id').html()}]); + silk_ajax_call('{php}echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_alias'));{/php}', [{ name:'alias', value:$('#alias').val() }, { name:'page_id', value:$('#page_id').html() }]); }, 0.5); $('#page_template_id').delayedObserver(function() { - silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'update_page'))[[/php]]', $('#form_save').serializeArray()); - }, 0.5, { event: 'change'}); + silk_ajax_call('{php}echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'update_page'));{/php}', $('#form_save').serializeArray()); + }, 0.5, { event: 'change' }); setup_content(); } function setup_content() { $('.content_type_picker').each(function() { $(this).delayedObserver(function() { - silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'update_content'))[[/php]]', [{name:'parent_id', value:$(this).attr('id')}, {name:'name', value:$(this).attr('name')}, {name:'value', value:$(this).val()}, {name:'page_id', value:$('#page_id').html()}]); - }, 0.5, { event: 'change'}); + silk_ajax_call('{php}echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'update_content'));{/php}', [{ name:'parent_id', value:$(this).attr('id') }, { name:'name', value:$(this).attr('name') }, { name:'value', value:$(this).val() }, { name:'page_id', value:$('#page_id').html() }]); + }, 0.5, { event: 'change' }); }); } $(document).ready(function() { reset_main_content(); }); -//]]></script> +//}></script> diff --git a/components/admin/views/page/info.tpl b/components/admin/views/page/info.tpl index e55263c..9265061 100644 --- a/components/admin/views/page/info.tpl +++ b/components/admin/views/page/info.tpl @@ -1,8 +1,8 @@ -<label>Id:</label> <span id="page_id">[[$page.id]]</span><br /> -<label>Page Name:</label> [[textbox name='page[page_name]' value=$page.page_name]]<br /> -<label>Menu Text:</label> [[textbox name='page[menu_text]' value=$page.menu_text]]<br /> -<label>Page Template:</label> [[select name='page[template_id]']][[page_template_dropdown_options selected=$page.template_id]][[/select]]<br /> +<label>Id:</label> <span id="page_id">{$page.id}</span><br /> +<label>Page Name:</label> {textbox name='page[page_name]' value=$page.page_name}<br /> +<label>Menu Text:</label> {textbox name='page[menu_text]' value=$page.menu_text}<br /> +<label>Page Template:</label> {select name='page[template_id]'}{page_template_dropdown_options selected=$page.template_id}{/select}<br /> <label>Active:</label> <span><a href="#">True</a></span><br /> <label>Show In Menu:</label> <span><a href="#">True</a></span><br /> -<label>Path to Page:</label> /[[textbox html_id='alias' name='page[alias]' autocomplete="off" value=$page.alias]]&nbsp;&nbsp;<span id="alias_ok" style="color: green;">Ok</span><br /> -<label>Unique Alias:</label> [[textbox html_id='unique_alias' name='page[unique_alias]' autocomplete="off" value=$page.unique_alias]]&nbsp;&nbsp;<span id="unique_alias_ok" style="color: green;">Ok</span><br /> +<label>Path to Page:</label> /{textbox html_id='alias' name='page[alias]' autocomplete="off" value=$page.alias}&nbsp;&nbsp;<span id="alias_ok" style="color: green;">Ok</span><br /> +<label>Unique Alias:</label> {textbox html_id='unique_alias' name='page[unique_alias]' autocomplete="off" value=$page.unique_alias}&nbsp;&nbsp;<span id="unique_alias_ok" style="color: green;">Ok</span><br /> diff --git a/components/admin/views/page/main_section.tpl b/components/admin/views/page/main_section.tpl index 3308a35..e2530ae 100644 --- a/components/admin/views/page/main_section.tpl +++ b/components/admin/views/page/main_section.tpl @@ -1,30 +1,30 @@ -[[form action="save" controller="page"]] +{form action="save" controller="page"} <div id="module_page_tabs"> <ul> <li><a href="#info"><span>Information</span></a></li> <li><a href="#edit"><span>Content</span></a></li> <li><a href="#attributes"><span>Attributes</span></a></li> <li><a href="#metadata"><span>Metadata</span></a></li> <li><a href="#preview"><span>Preview</span></a></li> </ul> <div id="info"> - [[render_partial template="info.tpl"]] + {render_partial template="info.tpl"} </div> <div id="edit"> - [[render_partial template="content.tpl"]] + {render_partial template="content.tpl"} </div> <div id="attributes"> </div> <div id="metadata"> </div> <div id="preview"> </div> </div> <br /> - [[hidden name='page[id]' value=$page.id]] + {hidden name='page[id]' value=$page.id} - [[submit name="save" value="Save" remote="true" action="save" controller="page"]] [[submit name="cancel" value="Cancel" onclick="clear_main_content(); return false;"]] [[submit name="apply" value="Apply" remote="true" action="save" controller="page"]] + {submit name="save" value="Save" remote="true" action="save" controller="page"} {submit name="cancel" value="Cancel" onclick="clear_main_content(); return false;"} {submit name="apply" value="Apply" remote="true" action="save" controller="page"} -[[/form]] \ No newline at end of file +{/form} \ No newline at end of file diff --git a/components/admin/views/page_template/add.tpl b/components/admin/views/page_template/add.tpl index e560fe6..dfee3af 100644 --- a/components/admin/views/page_template/add.tpl +++ b/components/admin/views/page_template/add.tpl @@ -1 +1 @@ -[[render_partial template='editform.tpl']] +{render_partial template='editform.tpl'} diff --git a/components/admin/views/page_template/edit.tpl b/components/admin/views/page_template/edit.tpl index e560fe6..dfee3af 100644 --- a/components/admin/views/page_template/edit.tpl +++ b/components/admin/views/page_template/edit.tpl @@ -1 +1 @@ -[[render_partial template='editform.tpl']] +{render_partial template='editform.tpl'} diff --git a/components/admin/views/page_template/editform.tpl b/components/admin/views/page_template/editform.tpl index 5a6cbe5..2bb101b 100644 --- a/components/admin/views/page_template/editform.tpl +++ b/components/admin/views/page_template/editform.tpl @@ -1,10 +1,10 @@ -[[cms_validation_errors for=$template]] +{cms_validation_errors for=$template} -[[form]] +{form} -[[label for='template[name]']]Name[[/label]]: [[textbox name='template[name]' value=$template.name]]<br /> -[[label for='template[name]']]Content[[/label]]: [[textarea name='template[content]' value=$template.content cols='80' rows='10']]<br /> -[[label for='template[active]']]Active[[/label]]: [[checkbox name='template[active]' checked=$template.active]]<br /> -[[hidden name='template[id]' value=$template.id]][[submit name='submit' value="Submit"]][[submit name='cancel' value="Cancel"]][[submit name='apply' value="Apply" remote="true"]] +{label for='template[name]'}Name{/label}: {textbox name='template[name]' value=$template.name}<br /> +{label for='template[name]'}Content{/label}: {textarea name='template[content]' value=$template.content cols='80' rows='10'}<br /> +{label for='template[active]'}Active{/label}: {checkbox name='template[active]' checked=$template.active}<br /> +{hidden name='template[id]' value=$template.id}{submit name='submit' value="Submit"}{submit name='cancel' value="Cancel"}{submit name='apply' value="Apply" remote="true"} -[[/form]] \ No newline at end of file +{/form} \ No newline at end of file diff --git a/components/admin/views/page_template/index.tpl b/components/admin/views/page_template/index.tpl index 8bd09b6..7271f23 100644 --- a/components/admin/views/page_template/index.tpl +++ b/components/admin/views/page_template/index.tpl @@ -1,36 +1,36 @@ <div class="pageoverflow"> <div class="pageheader">Page Templates <span class="helptext"> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Templates" rel="external"> - <img src="[[$layout_root_url]]/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> + <img src="{$layout_root_url}/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> </a> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Templates" rel="external">Help</a> (new window) </span> </div> </div> <table cellspacing="0" class="pagetable"> <thead> <tr> <th class="pagew50">Template</th> <th class="pagepos">Default</th> <th class="pagepos">Active</th> <th class="pageicon">&nbsp;</th> <th class="pageicon">&nbsp;</th> </tr> </thead> <tbody id="tablebody"> - [[render_partial template='indextablebody.tpl']] + {render_partial template='indextablebody.tpl'} </tbody> </table> <div class="pageoptions"> <p class="pageoptions"> <span style="float: left;"> - <a href="[[link only_href='true' controller='page_template' action='add']]"><img src="[[$layout_root_url]]/images/icons/system/newobject.gif" class="systemicon" alt="Add New Template" title="Add New Template" /></a> - [[link html_class="pageoptions" text="Add Template" controller="page_template" action="add"]] + <a href="{link only_href='true' controller='page_template' action='add'}"><img src="{$layout_root_url}/images/icons/system/newobject.gif" class="systemicon" alt="Add New Template" title="Add New Template" /></a> + {link html_class="pageoptions" text="Add Template" controller="page_template" action="add"} </span> </p> </div> <br /> diff --git a/components/admin/views/page_template/indextablebody.tpl b/components/admin/views/page_template/indextablebody.tpl index c367fcf..6bd6af1 100644 --- a/components/admin/views/page_template/indextablebody.tpl +++ b/components/admin/views/page_template/indextablebody.tpl @@ -1,9 +1,9 @@ -[[foreach from=$templates item='template']] -<tr class="[[cycle values='row1,row2']]"> - <td>[[link text=$template.name controller='page_template' action='edit' id=$template.id]]</td> - <td class="pagepos">[[if $template.default]][[img src="images/icons/system/true.gif" alt="True" title="True"]][[else]][[img src="images/icons/system/false.gif" title="False" alt="False"]][[/if]]</td> - <td class="pagepos">[[if $template.active]][[img src="images/icons/system/true.gif" alt="True" title="True"]][[else]][[img src="images/icons/system/false.gif" alt="False" title="False"]][[/if]]</td> - <td class="icons_wide">[[img_link src="images/icons/system/edit.gif" alt="Edit" title="Edit" controller='page_template' action='edit' id=$template.id]]</td> - <td class="icons_wide">[[img_link src="images/icons/system/delete.gif" alt="Delete" title="Delete" controller='page_template' action='delete' id=$template.id confirm_text='Are you sure you want to delete?']]</td> +{foreach from=$templates item='template'} +<tr class="{cycle values='row1,row2'}"> + <td>{link text=$template.name controller='page_template' action='edit' id=$template.id}</td> + <td class="pagepos">{if $template.default}{img src="images/icons/system/true.gif" alt="True" title="True"}{else}{img src="images/icons/system/false.gif" title="False" alt="False"}{/if}</td> + <td class="pagepos">{if $template.active}{img src="images/icons/system/true.gif" alt="True" title="True"}{else}{img src="images/icons/system/false.gif" alt="False" title="False"}{/if}</td> + <td class="icons_wide">{img_link src="images/icons/system/edit.gif" alt="Edit" title="Edit" controller='page_template' action='edit' id=$template.id}</td> + <td class="icons_wide">{img_link src="images/icons/system/delete.gif" alt="Delete" title="Delete" controller='page_template' action='delete' id=$template.id confirm_text='Are you sure you want to delete?'}</td> </tr> -[[/foreach]] \ No newline at end of file +{/foreach} \ No newline at end of file diff --git a/components/admin/views/stylesheet/add.tpl b/components/admin/views/stylesheet/add.tpl index 23dfe61..ea66c56 100644 --- a/components/admin/views/stylesheet/add.tpl +++ b/components/admin/views/stylesheet/add.tpl @@ -1,10 +1,10 @@ -[[validation_errors for=$stylesheet]] +{validation_errors for=$stylesheet} -[[form]] +{form} -[[label for='stylesheet[name]']]Name[[/label]]: [[textbox name='stylesheet[name]' value=$stylesheet.name]]<br /> -[[label for='stylesheet[value]']]Content[[/label]]: [[textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10']]<br /> -[[label for='stylesheet[active]']]Active[[/label]]: [[checkbox name='stylesheet[active]' checked=$stylesheet.active]]<br /> -[[submit name='submit' value="Submit"]][[submit name='cancel' value="Cancel"]] +{label for='stylesheet[name]'}Name{/label}: {textbox name='stylesheet[name]' value=$stylesheet.name}<br /> +{label for='stylesheet[value]'}Content{/label}: {textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10'}<br /> +{label for='stylesheet[active]'}Active{/label}: {checkbox name='stylesheet[active]' checked=$stylesheet.active}<br /> +{submit name='submit' value="Submit"}{submit name='cancel' value="Cancel"} -[[/form]] \ No newline at end of file +{/form} \ No newline at end of file diff --git a/components/admin/views/stylesheet/edit.tpl b/components/admin/views/stylesheet/edit.tpl index fd0b009..cab4704 100644 --- a/components/admin/views/stylesheet/edit.tpl +++ b/components/admin/views/stylesheet/edit.tpl @@ -1,10 +1,10 @@ -[[validation_errors for=$stylesheet]] +{validation_errors for=$stylesheet} -[[form]] +{form} -[[label for='stylesheet[name]']]Name[[/label]]: [[textbox name='stylesheet[name]' value=$stylesheet.name]]<br /> -[[label for='stylesheet[value]']]Content[[/label]]: [[textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10']]<br /> -[[label for='stylesheet[active]']]Active[[/label]]: [[checkbox name='stylesheet[active]' checked=$stylesheet.active]]<br /> -[[hidden name='stylesheet[id]' value=$stylesheet.id]][[submit name='submit' value="Submit"]][[submit name='cancel' value="Cancel"]] +{label for='stylesheet[name]'}Name{/label}: {textbox name='stylesheet[name]' value=$stylesheet.name}<br /> +{label for='stylesheet[value]'}Content{/label}: {textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10'}<br /> +{label for='stylesheet[active]'}Active{/label}: {checkbox name='stylesheet[active]' checked=$stylesheet.active}<br /> +{hidden name='stylesheet[id]' value=$stylesheet.id}{submit name='submit' value="Submit"}{submit name='cancel' value="Cancel"} -[[/form]] \ No newline at end of file +{/form} \ No newline at end of file diff --git a/components/admin/views/stylesheet/index.tpl b/components/admin/views/stylesheet/index.tpl index 5fc9c76..3419989 100644 --- a/components/admin/views/stylesheet/index.tpl +++ b/components/admin/views/stylesheet/index.tpl @@ -1,35 +1,35 @@ <div class="pageoverflow"> <div class="pageheader">Stylesheets <span class="helptext"> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Stylesheets" rel="external"> - <img src="[[$layout_root_url]]/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> + <img src="{$layout_root_url}/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> </a> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Stylesheets" rel="external">Help</a> (new window) </span> </div> </div> <table cellspacing="0" class="pagetable"> <thead> <tr> <th class="pagew50">Template</th> <th class="pagepos">Active</th> <th class="pageicon">&nbsp;</th> <th class="pageicon">&nbsp;</th> </tr> </thead> <tbody id="tablebody"> - [[render_partial template='indextablebody.tpl']] + {render_partial template='indextablebody.tpl'} </tbody> </table> <div class="pageoptions"> <p class="pageoptions"> <span style="float: left;"> - <a href="[[link only_href='true' controller='stylesheet' action='add']]"><img src="[[$layout_root_url]]/images/icons/system/newobject.gif" class="systemicon" alt="Add Stylesheet" title="Add Stylesheet" /></a> - [[link html_class="pageoptions" text="Add Stylesheet" controller="stylesheet" action="add"]] + <a href="{link only_href='true' controller='stylesheet' action='add'}"><img src="{$layout_root_url}/images/icons/system/newobject.gif" class="systemicon" alt="Add Stylesheet" title="Add Stylesheet" /></a> + {link html_class="pageoptions" text="Add Stylesheet" controller="stylesheet" action="add"} </span> </p> </div> <br /> diff --git a/components/admin/views/stylesheet/indextablebody.tpl b/components/admin/views/stylesheet/indextablebody.tpl index ec22f52..248a252 100644 --- a/components/admin/views/stylesheet/indextablebody.tpl +++ b/components/admin/views/stylesheet/indextablebody.tpl @@ -1,8 +1,8 @@ -[[foreach from=$stylesheets item='stylesheet']] -<tr class="[[cycle values='row1,row2']]"> - <td>[[link text=$stylesheet.name controller='stylesheet' action='edit' id=$stylesheet.id]]</td> - <td class="pagepos">[[if $stylesheet.active]][[img src="images/icons/system/true.gif" alt="True" title="True"]][[else]][[img src="images/icons/system/false.gif" alt="False" title="False"]][[/if]]</td> - <td class="icons_wide">[[img_link src="images/icons/system/edit.gif" alt="Edit" title="Edit" controller='stylesheet' action='edit' id=$stylesheet.id]]</td> - <td class="icons_wide">[[img_link src="images/icons/system/delete.gif" alt="Delete" title="Delete" controller='stylesheet' action='delete' id=$stylesheet.id confirm_text='Are you sure you want to delete?']]</td> +{foreach from=$stylesheets item='stylesheet'} +<tr class="{cycle values='row1,row2'}"> + <td>{link text=$stylesheet.name controller='stylesheet' action='edit' id=$stylesheet.id}</td> + <td class="pagepos">{if $stylesheet.active}{img src="images/icons/system/true.gif" alt="True" title="True"}{else}{img src="images/icons/system/false.gif" alt="False" title="False"}{/if}</td> + <td class="icons_wide">{img_link src="images/icons/system/edit.gif" alt="Edit" title="Edit" controller='stylesheet' action='edit' id=$stylesheet.id}</td> + <td class="icons_wide">{img_link src="images/icons/system/delete.gif" alt="Delete" title="Delete" controller='stylesheet' action='delete' id=$stylesheet.id confirm_text='Are you sure you want to delete?'}</td> </tr> -[[/foreach]] +{/foreach} diff --git a/index.php b/index.php index 0c48049..d686206 100644 --- a/index.php +++ b/index.php @@ -1,31 +1,31 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- // The MIT License // -// Copyright (c) 2008 Ted Kulp +// Copyright (c) 2008-2010 Ted Kulp // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. define('ROOT_DIR', dirname(__FILE__)); include_once('lib/silk/silk.api.php'); SilkBootstrap::get_instance()->run(); # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/layouts/themes/default/login.tpl b/layouts/themes/default/login.tpl index 22bef7a..cfa8196 100644 --- a/layouts/themes/default/login.tpl +++ b/layouts/themes/default/login.tpl @@ -1,63 +1,63 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>CMS Login</title> <link rel="stylesheet" type="text/css" media="screen, projection" href="themes/default/css/style.css" /> -<base href="[[$base_url]]" /> +<base href="{$base_url}" /> </head> <body> <div class="login-all clear"> <div class="info"> - <h1>[[tr]]Information[[/tr]]</h1> + <h1>{tr}Information{/tr}</h1> <div class="centerLogin"> - <p id="img">[[tr]]From this point should take into consideration the following parameters:[[/tr]]:</p> -[[tr]]<ol> + <p id="img">{tr}From this point should take into consideration the following parameters:{/tr}:</p> +{tr}<ol> <li>Cookies enabled in your browser</li> <li>Javascript enabled in your browser </li> <li>Windows popup active to the following address:</li> -</ol>[[/tr]] -<span>( [[$smarty.server.SERVER_NAME]] +</ol>{/tr} +<span>( {$smarty.server.SERVER_NAME} )</span> </div> </div> <div class="login"> -<div class="top">[[tr]]logintitle[[/tr]]</div> +<div class="top">{tr}logintitle{/tr}</div> <div id="centerLogin" class="formcontainer"> - [[$debug_buffer]] - [[if !empty($error)]] - <div class="erroLogin">[[$error]]</div > - [[/if]] + {$debug_buffer} + {if !empty($error)} + <div class="erroLogin">{$error}</div > + {/if} <div class="lbfieldstext"> - <p class="lbuser">[[tr]]username[[/tr]]:</p> - <p class="lbpass">[[tr]]password[[/tr]]:</p> - <p class="lbopenid">[[tr]]openid[[/tr]]:</p> + <p class="lbuser">{tr}username{/tr}:</p> + <p class="lbpass">{tr}password{/tr}:</p> + <p class="lbopenid">{tr}openid{/tr}:</p> </div> <div class="login-fields"> <form method="post" action="login.php"> <p> - <input id="lbusername" name="username" class="defaultfocus" type="text" size="15" value="[[$username]]" /><br /> - [[if !empty($error)]] + <input id="lbusername" name="username" class="defaultfocus" type="text" size="15" value="{$username}" /><br /> + {if !empty($error)} <input id="lbpassword" class="defaultfocus" name="password" type="password" size="15" /><br /> - [[else]] + {else} <input id="lbpassword" name="password" type="password" size="15" /><br /> - [[/if]] - <input name="openid" id="openid" type="text" size="15" value="[[$openid]]" /><br /><br /> - [[html_submit name="loginsubmit" name="loginsubmit" value=$submit_text]] - [[html_submit name="logincancel" name="logincancel" value=$cancel_text]] + {/if} + <input name="openid" id="openid" type="text" size="15" value="{$openid}" /><br /><br /> + {html_submit name="loginsubmit" name="loginsubmit" value=$submit_text} + {html_submit name="logincancel" name="logincancel" value=$cancel_text} </p> </form> </div> </div> </div> </div> <div class="login-footer"></div> <div id="copy"> &copy; <a rel="external" href="http://www.cmsmadesimple.org" >CMS Made Simple</a> <br /> Is free software released under the General Public Licence.</div> </body> </html> diff --git a/layouts/themes/default/main.tpl b/layouts/themes/default/main.tpl index a20e872..2efe8ce 100644 --- a/layouts/themes/default/main.tpl +++ b/layouts/themes/default/main.tpl @@ -1,115 +1,115 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="Generator" content="CMS Made Simple - Copyright (C) 2004-2009 Ted Kulp. All rights reserved." /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> - <title>[[$sitename]] - [[$title]]</title> + <title>{$sitename} - {$title}</title> - <link rel="stylesheet" href="[[$layout_root_url]]/css/kevin_tabs.css" type="text/css" /> - <link rel="stylesheet" href="[[$layout_root_url]]/css/style.css" type="text/css" /> + <link rel="stylesheet" href="{$layout_root_url}/css/kevin_tabs.css" type="text/css" /> + <link rel="stylesheet" href="{$layout_root_url}/css/style.css" type="text/css" /> <!--[if IE]> - <script type="text/javascript" src="[[$layout_root_url]]/includes/ie7-standard-p.js"></script> + <script type="text/javascript" src="{$layout_root_url}/includes/ie7-standard-p.js"></script> <![endif]--> - <!-- <script type="text/javascript" src="[[$layout_root_url]]/includes/standard.js"></script> --> + <!-- <script type="text/javascript" src="{$layout_root_url}/includes/standard.js"></script> --> <!-- jQuery and tabs --> - <script type="text/javascript" src="[[$silk_lib_root_url]]/jquery/jquery.js"></script> - <script type="text/javascript" src="[[$silk_lib_root_url]]/jquery/jquery.color.js"></script> - <script type="text/javascript" src="[[$silk_lib_root_url]]/jquery/jquery.silk.js"></script> - <script type="text/javascript" src="[[$silk_lib_root_url]]/jquery/ui/ui.tabs.js"></script> + <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.js"></script> + <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.color.js"></script> + <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.silk.js"></script> + <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.tabs.js"></script> <!-- Tree stuff --> - <link rel="stylesheet" type="text/css" href="[[$cmsms_lib_root_url]]/js/jstree/source/tree_component.css" /> - <script type="text/javascript" src="[[$cmsms_lib_root_url]]/js/jstree/lib/css.js"></script> - <script type="text/javascript" src="[[$cmsms_lib_root_url]]/js/jstree/source/tree_component.js"></script> - <script type="text/javascript" src="[[$cmsms_lib_root_url]]/js/jstree/lib/jquery.metadata.js"></script> - <script type="text/javascript" src="[[$cmsms_lib_root_url]]/js/jstree/lib/jquery.cookie.js"></script> + <link rel="stylesheet" type="text/css" href="{$cmsms_lib_root_url}/js/jstree/source/tree_component.css" /> + <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/css.js"></script> + <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/source/tree_component.js"></script> + <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/jquery.metadata.js"></script> + <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/jquery.cookie.js"></script> <script type="text/javascript"> //<![CDATA[ // form handling stuff $(document).ready(function() { setup_form(); }); function setup_form() { // disable all buttons $('button').addClass("disabled").attr("disabled", true); // but enable cancel $('button[@name="cancel"]').removeClass("disabled").attr("disabled", false); // assign event for every input $('form :input').one("change", function() { // on change call enable form enableForm(this.form); // mark in title if(document.title[0] != "*") { document.title = "*"+document.title; } }); // fill the default help text var help = $('#default_helptext').html(); $('#HelpContent').html(help); // assign an event for every form row $("div[id*='formrow']").bind("click", function() { var help = $(this).children("input[id*='help_']").val(); $('#HelpContent').html(help); }); } function enableForm(form) { var input = $('button', form); input.attr('disabled', false).removeClass('disabled'); } - //]]></script> + //}></script> - [[$headtext]] + {$headtext} - <base href="[[$root_url]]" /> + <base href="{$root_url}" /> </head> <body> <div id="clean-container"> - [[include file="$layout_root_path/topmenu.tpl"]] + {include file="$layout_root_path/topmenu.tpl"} <div id="MainContent"> - [[capture assign="errmsg"]][[php]]echo SilkFlash::get_instance()->get('std')[[/php]][[/capture]] - <div class="pagemcontainer"[[if empty($errmsg)]] style="display: none;"[[/if]]> + {capture assign="errmsg"}{php}echo SilkFlash::get_instance()->get('std');{/php}{/capture} + <div class="pagemcontainer"{if empty($errmsg)} style="display: none;"{/if}> <p class="pagemessage" id="pagemessage"> - [[$errmsg]] + {$errmsg} </p> </div> <div class="pagecontainer" id="pagecontent"> - [[$content]] + {$content} </div> <div class="clearb"></div> <div id="HelpContent"></div> </div><!-- end MainContent --> <div id="footer"> - <a rel="external" href="http://www.cmsmadesimple.org"><b>CMS Made Simple</b></a> [[$cms_version]] "[[$cms_versionname]]"<br /><b>CMS Made Simple</b> is free software released under the General Public Licence. + <a rel="external" href="http://www.cmsmadesimple.org"><b>CMS Made Simple</b></a> {$cms_version} "{$cms_versionname}"<br /><b>CMS Made Simple</b> is free software released under the General Public Licence. </div> </div><!--end clean-container--> </body> </html> -[[php]]echo SilkProfiler::get_instance()->report();[[/php]] \ No newline at end of file +{php}echo SilkProfiler::get_instance()->report();{/php} \ No newline at end of file diff --git a/layouts/themes/default/topmenu.tpl b/layouts/themes/default/topmenu.tpl index b27c334..f0ee427 100644 --- a/layouts/themes/default/topmenu.tpl +++ b/layouts/themes/default/topmenu.tpl @@ -1,58 +1,58 @@ -<div id="logocontainer"><img src="layouts/themes/default/images/logoCMS.png" alt="[[$adminpaneltitle]]" title="[[$adminpaneltitle]]" /><div class="logotext">[[$adminpaneltitle]] +<div id="logocontainer"><img src="layouts/themes/default/images/logoCMS.png" alt="{$adminpaneltitle}" title="{$adminpaneltitle}" /><div class="logotext">{$adminpaneltitle} -<br />Welcome User: [[$its_me]] +<br />Welcome User: {$its_me} </div></div> -[[if $root_node->has_children()]] +{if $root_node->has_children()} <div class="topmenucontainer"> <ul id="nav"> - [[foreach from=$root_node->get_children() item=node name=node]] - <li><a href="[[$node->url|escape:'html']]" class="[[if $node->selected]] selected[[/if]]"[[if $node->target ne '']] rel="external"[[/if]]>[[$node->title]]</a> + {foreach from=$root_node->get_children() item=node name=node} + <li><a href="{$node->url|escape:'html'}" class="{if $node->selected} selected{/if}"{if $node->target ne ''} rel="external"{/if}>{$node->title}</a> - [[if $node->has_children()]] + {if $node->has_children()} <ul> - [[foreach from=$node->get_children() item=subnode name=subnode]] - [[if $subnode->show_in_menu]] - <li><a href="[[$subnode->url|escape:'html']]" class="[[if $subnode->selected]] selected[[/if]][[if $subnode->first_module]] firstmodule[[elseif $subnode->module]] module[[/if]]"[[if $subnode->target ne '']] rel="external"[[/if]]>[[$subnode->title]]</a></li> - [[/if]] - [[/foreach]] + {foreach from=$node->get_children() item=subnode name=subnode} + {if $subnode->show_in_menu} + <li><a href="{$subnode->url|escape:'html'}" class="{if $subnode->selected} selected{/if}{if $subnode->first_module} firstmodule{elseif $subnode->module} module{/if}"{if $subnode->target ne ''} rel="external"{/if}>{$subnode->title}</a></li> + {/if} + {/foreach} </ul> - [[/if]] + {/if} </li> - [[/foreach]] + {/foreach} </ul> <!-- ICONS--> <div id="nav-icons_all"> <ul id="nav-icons"> <li class="viewsite-icon"><a rel="external" title="View Site" href="../">View Site</a></li> <li class="logout-icon"><a title="Logout" href="logout.php">Logout</a></li> </ul> </div><!--end nav-icons_all--> <div class="clearb"></div> </div> <div class="breadcrumbs"> - [[if count($breadcrumbs) gt 0]] - [[foreach from=$breadcrumbs item=breadcrumb name=breadcrumb]] - [[if $breadcrumb.url ne '']] - <a class="breadcrumbs" href="[[$breadcrumb.url|escape:'html']]">[[$breadcrumb.title]]</a> - [[else]] - [[$breadcrumb.title]] - [[/if]] - [[if !$smarty.foreach.breadcrumb.last]] + {if count($breadcrumbs) gt 0} + {foreach from=$breadcrumbs item=breadcrumb name=breadcrumb} + {if $breadcrumb.url ne ''} + <a class="breadcrumbs" href="{$breadcrumb.url|escape:'html'}">{$breadcrumb.title}</a> + {else} + {$breadcrumb.title} + {/if} + {if !$smarty.foreach.breadcrumb.last} &#187; - [[/if]] - [[/foreach]] - [[/if]] + {/if} + {/foreach} + {/if} </div> -[[/if]] +{/if} diff --git a/lib/cmsms/classes/class.cms_content_base.php b/lib/cmsms/classes/class.cms_content_base.php index 1696aad..194ea14 100644 --- a/lib/cmsms/classes/class.cms_content_base.php +++ b/lib/cmsms/classes/class.cms_content_base.php @@ -1,51 +1,51 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class CmsContentBase extends SilkObjectRelationalMapping { var $table = 'content'; function __construct() { parent::__construct(); $this->type = get_class(); } function get_content() { return ''; } function get_edit_form($block_name = 'default') { $file_name = underscore(get_class($this)); $tpl_file = join_path(dirname(__FILE__), 'content_types', 'templates', 'edit.' . $file_name . '.tpl'); if (is_file($tpl_file)) { - smarty()->assign_by_ref('obj', $this); + smarty()->assignByRef('obj', $this); smarty()->assign('block_name', $block_name); return smarty()->fetch($tpl_file); } return ''; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_request.php b/lib/cmsms/classes/class.cms_module_request.php index 15e15fe..8f36f73 100644 --- a/lib/cmsms/classes/class.cms_module_request.php +++ b/lib/cmsms/classes/class.cms_module_request.php @@ -1,657 +1,657 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ /** * Class to represent one module "request". Basically a wrapper * object to hold a call to a module's action. It will hold * specifc module "session" variables, and also hold methods only * used during a session, including form generation. * * @package cmsms * @author Ted Kulp * @version $Revision$ * @modifiedby $LastChangedBy$ * @lastmodified $Date$ * @license GPL */ class CmsModuleRequest extends SilkObject { var $module = null; var $id = ''; var $return_id = ''; function __construct($module, $id, $return_id = '') { parent::__construct(); $this->module = $module; $this->id = $id; $this->return_id = $return_id; } /** * Getter overload method. Called when a field * does not exist in the object's variable list. * * @param string The field to look up * @return mixed The value for that field, if it exists * @author Ted Kulp **/ function __get($n) { if ($this->module != null) { if (property_exists($this->module, $n)) { return $this->module->$n; } } } /** * Setter overload method. Called when a field * does not exist in the object's variable list. * * @param string The field to set * @param mixed The value to set for said field * @return void * @author Ted Kulp **/ function __set($n, $val) { if ($this->module != null) { if (property_exists($this->module, $n)) { $this->module->$n = $val; } } } /** * Caller overload method. Called when a method does not exist. * * @param string The name of the method called * @param array The parameters sent along with that method call * @return mixed The result of the method call * @author Ted Kulp **/ function __call($function, $arguments) { if ($arguments == null) $arguments = array(); if ($this->module != null) { if (method_exists($this->module, $function)) { return call_user_func_array(array($this->module, $function), $arguments); } } } /** * Used for navigation between "pages" of a module. Forms and links should * pass an action with them so that the module will know what to do next. * By default, DoAction will be passed 'default' and 'defaultadmin', * depending on where the module was called from. If being used as a module * or content type, 'default' will be passed. If the module was selected * from the list on the admin menu, then 'defaultadmin' will be passed. * * @param string Name of the action to perform * @param string The ID of the module * @param string The parameters targeted for this module */ public function do_action($action_name, $params) { //In case the module overrides it if (method_exists($this->module, 'do_action')) { return $this->module->do_action($this, $action_name, $params); } $return_id = $this->return_id; //avoid confusion $returnid = $return_id; if ($action_name != '') { $filename = join_path($this->module->get_module_path(), 'action.' . $action_name . '.php'); if (@is_file($filename)) { { $db = db(); //$config = cms_config(); $smarty = smarty(); $id = $this->id; - $smarty->assign_by_ref('request', $this); + $smarty->assignByRef('request', $this); $smarty->assign('module_action',$action_name); include($filename); } } } } public function do_action_base($name, $incoming_params) { return $this->do_action($name, $incoming_params); } static public function strip_extra_params(&$params, $default_params, $other_params_key = '') { $extra_params = array_diff_key($params, $default_params); $params = $default_params; if ($other_params_key != '' && isset($params[$other_params_key]) && is_array($params[$other_params_key])) { $extra_params = array_merge($extra_params, $params[$other_params_key]); unset($params[$other_params_key]); } return $extra_params; } static public function create_start_tag($name, $params, $self_close = false, $extra_html = '') { $text = "<{$name}"; foreach ($params as $key=>$value) { $text .= " {$key}=\"{$value}\""; } if ($extra_html != '') { $text .= " {$extra}"; } $text .= ($self_close ? ' />' : '>'); return $text; } static public function create_end_tag($name) { return "</{$name}>"; } /** * Returns the start of a module form\n * Parameters: * - 'action' - The action that this form should do when the form is submitted. Defaults to 'default'. * - 'method' - Method to put in the form tag. Defaults to 'post'. * - 'enctype' - Optional enctype for the form. Only real option is 'multipart/form-data'. Defaults to null. * - 'inline' - Boolean to tell whether or not we want the form's result to be "inline". Defaults to false. * - 'id_suffix' - Text to append to the end of the id and name of the form. Defaults to ''. * - 'extra' - Text to append to the <form>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'use_current_page_as_action' - A flag to determine if the action should just * redirect back to this exact page. Defaults to false. * - 'params' - An array of key/value pairs to add as extra hidden parameters. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as hidden * variables to the form and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp **/ public function create_form_start($params = array(), $check_keys = false) { $default_params = array( 'action' => coalesce_key($params, 'action', 'default', FILTER_SANITIZE_URL), 'method' => coalesce_key($params, 'method', 'post', FILTER_SANITIZE_STRING), 'enctype' => coalesce_key($params, 'enctype', '', FILTER_SANITIZE_STRING), 'inline' => coalesce_key($params, 'inline', false, FILTER_VALIDATE_BOOLEAN), 'id_suffix' => coalesce_key($params, 'id_suffix', '', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'use_current_page_as_action' => coalesce_key($params, 'use_current_page_as_action', false, FILTER_VALIDATE_BOOLEAN), 'params' => coalesce_key($params, 'params', array()), 'id' => coalesce_key($params, 'id', $this->id), 'return_id' => coalesce_key($params, 'return_id', $this->return_id) ); $default_params['html_id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['id'].$default_params['action'].$default_params['id_suffix']), FILTER_SANITIZE_STRING ); $default_params['html_name'] = coalesce_key($params, 'html_name', $default_params['html_id'], FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Strip out any straggling parameters to their own array //Merge in anything if it was passed in the params key to the method $extra_params = $this->strip_extra_params($params, $default_params, 'params'); $form_count = cmsms()->get('formcount'); if ($form_count == null) $form_count = 1; $mact = $this->module->get_name().','.$params['id'].','.$params['action'].','.($inline == true?1:0); $goto = ''; $use_current_page_as_action = $params['use_current_page_as_action']; unset($params['use_current_page_as_action']); if ($use_current_page_as_action) $goto = CmsRequest::get_requested_uri(); else $goto = ($params['return_id'] == '' ? 'moduleinterface.php' : 'index.php'); $form_params = array( 'id' => $params['html_id'], 'name' => $params['html_name'], 'method' => $params['method'], 'action' => $goto ); if ($enctype != '') { $form_params['enctype'] = $params['enctype']; } $extra = ''; if ($params['extra']) { $extra = $params['extra']; unset($params['extra']); } $text .= $this->create_start_tag('form', $form_params, false, $extra); $text .= $this->create_start_tag('div', array('class' => 'hidden')); if (!$use_current_page_as_action) $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => 'mact', 'value' => $mact), true); if ($params['return_id'] != '') { $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['id'].'returnid', 'value' => $params['return_id']), true); if ($inline) { $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => cms_config()->get('query_var'), 'value' => $params['return_id']), true); } } foreach ($extra_params as $key=>$value) { if ($key != 'module' && $key != 'action' && $key != 'id') $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['id'].$key, 'value' => $value), true); } $text .= $this->create_end_tag('div'); //end "hidden" cmsms()->set('formcount', $form_count + 1); return $text; } /** * Returns the end of a module form\n * Parameters: * - none * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as hidden * variables to the form and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp **/ public function create_form_end($params = array(), $check_keys = false) { return $this->create_end_tag('form'); } /** * Returns the xhtml equivalent of an input textbox. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant. * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'value' - The value of the field. Defaults to ''. * - 'size' - The length of the input field when displayed. Defaults to 10. * - 'maxlength' - The max length of the value allowed. Defaults to 255. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'label' - If set to a string, a label will be created with the proper "for" value for the input. * - 'label_extra' - Text to append to the <label>-statement, ex. for javascript-validation code. Defaults to ''. * - 'in_between_text' - Text to put between the label and input fields. Defaults to ''. * - 'password' - Boolean to tell whether or not we want it to be a password input. Defaults to false. * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_text($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), 'size' => coalesce_key($params, 'size', 25, FILTER_SANITIZE_NUMBER_INT), 'maxlength' => coalesce_key($params, 'maxlength', 255, FILTER_SANITIZE_NUMBER_INT), 'extra' => coalesce_key($params, 'extra', ''), 'label' => coalesce_key($params, 'label', '', FILTER_SANITIZE_STRING), 'label_extra' => coalesce_key($params, 'label_extra', ''), 'in_between_text' => coalesce_key($params, 'in_between_text', ''), 'password' => coalesce_key($params, 'password', false, FILTER_VALIDATE_BOOLEAN), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); $params['type'] = ($params['password'] == true ? 'password' : 'text'); $text = ''; if ($params['label'] != '') { $text .= $this->create_start_tag('form', array('for' => $params['id']), true, $params['label_extra']); $text .= $params['in_between_text']; } unset($params['label']); unset($params['label_extra']); $text .= $this->create_start_tag('input', $params, true, $extra); return $text; } /** * Returns the xhtml equivalent of an hidden input. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'value' - The value of the field. Defaults to ''. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_hidden($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); $params['type'] = 'hidden'; //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); return $this->create_start_tag('input', $params, true, $extra); } /** * Returns the xhtml equivalent of an checkbox input. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant. Also adds the feature * of making sure that even unchecked checkboxes return a value back to the form.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'checked' - Boolean of whether or not the checkbox is checked. Defaults to false. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_checkbox($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'checked' => coalesce_key($params, 'checked', false, FILTER_VALIDATE_BOOLEAN), 'extra' => coalesce_key($params, 'extra', ''), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); $params['type'] = 'checkbox'; $params['value'] = '1'; if ($params['checked']) $params['checked'] = 'checked'; else unset($params['checked']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); return $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['name'], 'value' => '0'), true) . $this->create_start_tag('input', $params, true, $extra); } /** * Returns the xhtml equivalent of an submit button. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'value' - The value (text) of the button. Defaults to ''. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'image' - The name of an image to display instead of the text. Defaults to ''. * - 'confirm_text' - If set, a message to display to confirm the click. Defaults to ''. * - 'params' - An array of key/value pairs to add as attributes to the input tag. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * - 'reset' - Boolean of whether or not this is a reset buton. Defaults to false. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_submit($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'image' => coalesce_key($params, 'image', '', FILTER_SANITIZE_STRING), 'confirm_text' => coalesce_key($params, 'confirm_text', '', FILTER_SANITIZE_STRING), 'reset' => coalesce_key($params, 'reset', false, FILTER_VALIDATE_BOOLEAN), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); if ($reset) { $params['type'] = 'reset'; } else if ($params['image'] != '') { $params['type'] = 'image'; $params['src'] = CmsConfig::get('root_url') . '/' . $params['image']; } else { $params['type'] = 'submit'; } unset($params['image']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; if ($params['confirm_text'] != '') { $extra .= ' onclick="return confirm(\''.$params['confirm_text'].'\');"'; } } unset($params['extra']); unset($params['confirm_text']); return $this->create_start_tag('input', $params, true, $extra); } /** * Returns the xhtml equivalent of the opening of a select input. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'multiple' - Boolean of whether or not this is should show multiple items. Defaults to false. * - 'size' - Number of items to show if multiple is set to true. Defaults to 3. * - 'params' - An array of key/value pairs to add as attributes to the input tag. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_select($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'multiple' => coalesce_key($params, 'multiple', false, FILTER_VALIDATE_BOOLEAN), 'size' => coalesce_key($params, 'size', 3, FILTER_SANITIZE_NUMBER_INT), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); if ($params['multiple']) { $params['multiple'] = 'multiple'; } else { unset($params['multiple']); unset($params['size']); } $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); return $this->create_start_tag('select', $params, false, $extra); } /** * Returns the xhtml equivalent of options tags. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant.\n * Parameters: * - 'items' - An associative array of key/values to represent the value and text of the items in the list. This can also be * passed a string in the form of 'key,value,key,value'. Defaults to array(). * - 'selected_value' - A string that will set the matching item (by value) as selected. Defaults = ''. * - 'selected_index' - An integer that will set the matching item (by index) as selected. Defaults to -1 (no selection). * - 'selected_values' - An array of strings that will set the matching item as selected. This is for multiple select items. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. diff --git a/lib/cmsms/classes/class.cms_smarty.php b/lib/cmsms/classes/class.cms_smarty.php index 8ab12c4..c9d0101 100644 --- a/lib/cmsms/classes/class.cms_smarty.php +++ b/lib/cmsms/classes/class.cms_smarty.php @@ -1,70 +1,70 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #BUT withOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** * Represents a template in the database. * * @author Ted Kulp * @since 2.0 **/ class CmsSmarty extends SilkSmarty { function __construct() { parent::__construct(); - $this->register_resource("template", array(&$this, "template_get_template", + $this->register->resource("template", array(&$this, "template_get_template", "template_get_timestamp", "db_get_secure", "db_get_trusted")); } function template_get_template($tpl_name, &$tpl_source, &$smarty_obj) { $template = orm('CmsTemplate')->find_by_id($tpl_name); if ($template) { $tpl_source = $template->content; return true; } return false; } function template_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj) { $template = orm('CmsTemplate')->find_by_id($tpl_name); if ($template) { $tpl_timestamp = $template->modified_date->timestamp(); return true; } return false; } function db_get_secure($tpl_name, &$smarty_obj) { // assume all templates are secure return true; } function db_get_trusted($tpl_name, &$smarty_obj) { // not used for templates } } ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_template.php b/lib/cmsms/classes/class.cms_template.php index e460aed..96494f1 100644 --- a/lib/cmsms/classes/class.cms_template.php +++ b/lib/cmsms/classes/class.cms_template.php @@ -1,193 +1,189 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #BUT withOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** * Represents a template in the database. * * @author Ted Kulp * @since 2.0 **/ class CmsTemplate extends SilkObjectRelationalMapping { var $params = array('id' => -1, 'name' => '', 'content' => '', 'stylesheet' => '', 'encoding' => '', 'active' => true, 'default' => false); var $field_maps = array('template_name' => 'name', 'default_template' => 'default', 'template_content' => 'content'); var $table = 'templates'; var $blocks = array(); public function setup() { $this->create_has_many_association('stylesheet_associations', 'cms_template_stylesheet_association', 'template_id', array('order' => 'order_num ASC')); $this->create_has_and_belongs_to_many_association('stylesheets', 'cms_stylesheet', 'stylesheet_template_assoc', 'stylesheet_id', 'template_id', array('order' => 'order_num ASC')); $this->create_has_and_belongs_to_many_association('active_stylesheets', 'cms_stylesheet', 'stylesheet_template_assoc', 'stylesheet_id', 'template_id', array('order' => 'order_num ASC', 'conditions' => 'stylesheets.active = 1')); } function usage_count() { return orm('CmsTemplateAssociation')->find_count_by_template_id($this->id); } function validate() { $this->validate_not_blank('name'); $this->validate_not_blank('content'); if ($this->name != '') { $result = orm('cms_template')->find_all_by_name($this->name); if (count($result) > 0) { if ($result[0]->id != $this->id) { $this->add_validation_error('Template Exists'); } } } } public function get_stylesheet_media_types($show_inactive = false) { $result = array(); foreach ($this->active_stylesheets as $stylesheet) { foreach ($stylesheet->get_media_types_as_array() as $media_type) { if (!in_array($media_type, $result)) $result[] = $media_type; } } return $result; } public function assign_stylesheet_by_id($stylesheet_id) { $exists = false; $cur_stylesheets = $this->stylesheets; foreach ($cur_stylesheets as $one_stylesheet) { if ($one_stylesheet->stylesheet_id == $stylesheet_id) { $exists = true; break; } } if (!$exists) { $new_assoc = new CmsTemplateStylesheetAssociation; $new_assoc->template_id = $this->id; $new_assoc->stylesheet_id = $stylesheet_id; $new_assoc->save(); } } public function remove_assigned_stylesheet_by_id($stylesheet_id) { $cur_stylesheets = $this->stylesheet_associations; foreach ($cur_stylesheets as $one_stylesheet) { if ($one_stylesheet->stylesheet_id == $stylesheet_id) { $one_stylesheet->delete(); break; } } } public function get_page_blocks() { $smarty = smarty(); $this->blocks = array(); $old_function = $smarty->_plugins['function']['content']; - $smarty->register_function('content', array($this, 'parse_block_callback')); + $smarty->register->templateFunction('content', array($this, 'parse_block_callback')); - $smarty->_compile_source('temporary template', $this->content, $_compiled); - @ob_start(); - $smarty->_eval('?>' . $_compiled); - $_contents = @ob_get_contents(); - @ob_end_clean(); + $smarty->fetch("string:" . $this->content); - $smarty->unregister_function('content'); + $smarty->unregister->templateFunction('content'); $smarty->_plugins['function']['content'] = $old_function; return $this->blocks; } - public function parse_block_callback($params, &$smarty) + public function parse_block_callback($params, $smarty) { $name = 'default'; if (isset($params['block'])) { $name = $params['block']; unset($params['block']); } if (!isset($params['type'])) { $params['type'] = 'CmsHtmlContentType'; } $this->blocks[$name] = $params; } function process() { $smarty = smarty(); return $smarty->fetch('template:' . $this->id); } //Callback handlers function before_save() { //Make sure we have a default template set or we'll probably break stuff down the road if (orm('CmsTemplate')->find_count_by_default_template(1) == 0) { $this->default_template = 1; } //CmsEvents::send_event( 'Core', ($this->id == -1 ? 'AddTemplatePre' : 'EditTemplatePre'), array('template' => &$this)); } function after_save() { /* CmsEvents::send_event( 'Core', ($this->create_date == $this->modified_date ? 'AddTemplatePost' : 'EditTemplatePost'), array('template' => &$this)); CmsCache::clear(); CmsContentOperations::clear_cache(); */ } function before_delete() { //CmsEvents::send_event('Core', 'DeleteTemplatePre', array('template' => &$this)); } function after_delete() { /* CmsEvents::send_event('Core', 'DeleteTemplatePost', array('template' => &$this)); CmsCache::clear(); CmsContentOperations::clear_cache(); */ } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/content_types/templates/edit.cms_html_content.tpl b/lib/cmsms/classes/content_types/templates/edit.cms_html_content.tpl index 1719596..5acf1c6 100644 --- a/lib/cmsms/classes/content_types/templates/edit.cms_html_content.tpl +++ b/lib/cmsms/classes/content_types/templates/edit.cms_html_content.tpl @@ -1 +1 @@ -[[textarea name="block[$block_name][contents]" value=$obj->contents]] +{textarea name="block[$block_name][contents]" value=$obj->contents} diff --git a/lib/cmsms/classes/content_types/templates/edit.cms_other_content.tpl b/lib/cmsms/classes/content_types/templates/edit.cms_other_content.tpl index e74cfe6..71be2fc 100644 --- a/lib/cmsms/classes/content_types/templates/edit.cms_other_content.tpl +++ b/lib/cmsms/classes/content_types/templates/edit.cms_other_content.tpl @@ -1 +1 @@ -[[textbox name="block[$block_name][contents]" value=$obj->contents]] +{textbox name="block[$block_name][contents]" value=$obj->contents} diff --git a/modules/MenuManager/MenuManager.module.php b/modules/MenuManager/MenuManager.module.php index 896c5b5..ab2c941 100644 --- a/modules/MenuManager/MenuManager.module.php +++ b/modules/MenuManager/MenuManager.module.php @@ -1,178 +1,178 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2009 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class MenuManager extends CmsModuleBase { function __construct() { parent::__construct(); } function setup() { $this->register_module_plugin('menu_children', 'menu_children_plugin_callback'); } public function menu_children_plugin_callback($params, &$smarty) { - $orig_params = $smarty->get_template_vars('orig_params'); + $orig_params = $smarty->getTemplateVars('orig_params'); $params = array_merge($orig_params, $params); if (!isset($params['node'])) { return; } if ($params['node']->has_children()) { $this->current_depth++; //Handle number_of_levels param if (!isset($params['number_of_levels']) || $params['number_of_levels'] > $this->current_depth) { //Handle collapse param if (!isset($params['collapse']) || $params['collapse'] != true || starts_with(cmsms()->variables['position'] . '.', $params['node']->hierarchy . '.')) { $this->display_menu($params['node']->get_children(), $params, false); } } $this->current_depth--; } } public function display_menu(&$nodes, $params, $first_call = true) { $usefile = true; //$lang = CmsMultiLanguage::get_client_language(); $lang = 'en_US'; $mdid = md5('12345'); //md5(cmsms()->variables['content_id'].implode('|', $params).$lang); $tpl_name = coalesce_key($params, 'template', ''); if (!ends_with($tpl_name, '.tpl')) { $usefile = false; } if (is_array($nodes)) { $count = 0; foreach ($nodes as &$node) { $this->add_fields_to_node($node); $node->show = $this->should_show_node($node, $params); //Numeric Stuff $node->first = ($count == 0); $node->last = ($count + 1 == count($nodes)); $node->index = $count; $count++; } $smarty = smarty(); $smarty->assign('count', count($nodes)); - $smarty->assign_by_ref('nodelist', $nodes); + $smarty->assignByRef('nodelist', $nodes); if ($first_call) { $smarty->assign('orig_params', $params); $this->current_depth = 1; } //echo $this->process_template_from_database($id, $return_id, 'menu_template', $tpl_name); echo $this->process_template_from_data($this->get_default_template()); } } public function add_fields_to_node(&$node) { $node->url = $node->get_url(true, $lang); $node->menutext = $node->get_property_value('menu_text', $lang); $node->haschildren = $node->has_children(); $node->target = ''; if ($node->has_property('target')) $node->target = $node->get_property_value('target'); $node->depth = $this->current_depth; } public function should_show_node(&$node, $params) { $include = true; $exclude = false; if (isset($params['includeprefix'])) { $include = false; $prefixes = explode(',', $params['includeprefix']); foreach ($prefixes as $oneprefix) { if (starts_with(strtolower($node->alias), strtolower($oneprefix))) { $include = true; break; } } } if (isset($params['excludeprefix'])) { $prefixes = explode(',', $params['excludeprefix']); foreach ($prefixes as $oneprefix) { if (starts_with(strtolower($node->alias), strtolower($oneprefix))) { $exclude = true; break; } } } $should_show = $node->active && $node->show_in_menu && ($include && !$exclude); //Override is show_all is true if (isset($params['show_all']) && $params['show_all']) $should_show = true; return $should_show; } function get_default_template() { return '[[if $count > 0]] <ul> [[foreach from=$nodelist item=node]] [[if $node->show]] <li> <a href="[[$node->get_url()]]">[[$node->menu_text]]</a> [[menu_children node=$node]] </li> [[/if]] [[/foreach]] </ul> [[/if]] '; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file
tedkulp/cmsms-nouveau
137958e9190c598beda8dac1cb877276dd111822
Some dummy modules and content types. Needs to be deleted at some point.
diff --git a/lib/cmsms/classes/content_types/class.cms_other_content.php b/lib/cmsms/classes/content_types/class.cms_other_content.php new file mode 100644 index 0000000..6cdafd2 --- /dev/null +++ b/lib/cmsms/classes/content_types/class.cms_other_content.php @@ -0,0 +1,35 @@ +<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- +#CMS - CMS Made Simple +#(c)2004-2008 by Ted Kulp ([email protected]) +#This project's homepage is: http://cmsmadesimple.org +# +#This program is free software; you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation; either version 2 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +#You should have received a copy of the GNU General Public License +#along with this program; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +#$Id$ + +class CmsOtherContent extends CmsContentBase +{ + function __construct() + { + parent::__construct(); + } + + function get_content() + { + return $this->contents; + } +} + +# vim:ts=4 sw=4 noet +?> \ No newline at end of file diff --git a/lib/cmsms/classes/content_types/templates/edit.cms_other_content.tpl b/lib/cmsms/classes/content_types/templates/edit.cms_other_content.tpl new file mode 100644 index 0000000..e74cfe6 --- /dev/null +++ b/lib/cmsms/classes/content_types/templates/edit.cms_other_content.tpl @@ -0,0 +1 @@ +[[textbox name="block[$block_name][contents]" value=$obj->contents]] diff --git a/modules/CGExtensions/CGExtensions.info.xml b/modules/CGExtensions/CGExtensions.info.xml new file mode 100644 index 0000000..8c1c50c --- /dev/null +++ b/modules/CGExtensions/CGExtensions.info.xml @@ -0,0 +1,18 @@ +<module_info> + <name>CGExtensions</name> + <version>1.0</version> + <summary>Does some test things that are really awesome.</summary> + <minimum_core_version>2.0</minimum_core_version> + <authors> + <author> + <name>Robert Campbell</name> + <email>[email protected]</email> + </author> + </authors> + <dependencies> + <module> + <name>Mail</name> + </module> + </dependencies> + <admin_interface>true</admin_interface> +</module_info> diff --git a/modules/CGExtensions/CGExtensions.module.php b/modules/CGExtensions/CGExtensions.module.php new file mode 100644 index 0000000..619fcb9 --- /dev/null +++ b/modules/CGExtensions/CGExtensions.module.php @@ -0,0 +1,30 @@ +<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- +#CMS - CMS Made Simple +#(c)2004-2008 by Ted Kulp ([email protected]) +#This project's homepage is: http://cmsmadesimple.org +# +#This program is free software; you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation; either version 2 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +#You should have received a copy of the GNU General Public License +#along with this program; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +#$Id$ + +class CGExtensions extends CmsModuleBase +{ + function __construct() + { + parent::__construct(); + } +} + +# vim:ts=4 sw=4 noet +?> \ No newline at end of file diff --git a/modules/Mail/Mail.info.xml b/modules/Mail/Mail.info.xml new file mode 100644 index 0000000..b05cbd3 --- /dev/null +++ b/modules/Mail/Mail.info.xml @@ -0,0 +1,12 @@ +<module_info> + <name>Mail</name> + <version>1.0</version> + <summary>Does some test things that are really awesome.</summary> + <authors> + <author> + <name>Ted Kulp</name> + <email>[email protected]</email> + </author> + </authors> + <admin_interface>true</admin_interface> +</module_info> diff --git a/modules/Mail/Mail.module.php b/modules/Mail/Mail.module.php new file mode 100644 index 0000000..c87381b --- /dev/null +++ b/modules/Mail/Mail.module.php @@ -0,0 +1,30 @@ +<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- +#CMS - CMS Made Simple +#(c)2004-2008 by Ted Kulp ([email protected]) +#This project's homepage is: http://cmsmadesimple.org +# +#This program is free software; you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation; either version 2 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +#You should have received a copy of the GNU General Public License +#along with this program; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +#$Id$ + +class Mail extends CmsModuleBase +{ + function __construct() + { + parent::__construct(); + } +} + +# vim:ts=4 sw=4 noet +?> \ No newline at end of file diff --git a/modules/Test/Test.info.xml b/modules/Test/Test.info.xml new file mode 100644 index 0000000..964ee08 --- /dev/null +++ b/modules/Test/Test.info.xml @@ -0,0 +1,49 @@ +<module_info> + <name>Test</name> + <version>1.0</version> + <summary>Does some test things that are really awesome.</summary> + <minimum_core_version>1.99</minimum_core_version> + <authors> + <author> + <name>Ted Kulp</name> + <email>[email protected]</email> + </author> + <author> + <name>Robert Campbell</name> + <email>[email protected]</email> + </author> + </authors> + <!-- + <dependencies> + <module> + <name>CGExtensions</name> + <minimum_version>1.0</minimum_version> + </module> + </dependencies> + --> + <events_watched> + <module> + <name>Core</name> + <events> + <event>edit_content_pre</event> + <event>edit_content_post</event> + </events> + </module> + <module> + <name>News</name> + <events> + <event>news_item_created</event> + </events> + </module> + </events_watched> + <events_sent> + <event>TestEventThing</event> + </events_sent> + <content_types> + <type>TestContentType</type> + </content_types> + <page_types> + <type>TestPageType</type> + </page_types> + <admin_interface>true</admin_interface> +</module_info> diff --git a/modules/Test/Test.module.php b/modules/Test/Test.module.php new file mode 100644 index 0000000..30848c7 --- /dev/null +++ b/modules/Test/Test.module.php @@ -0,0 +1,33 @@ +<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- +#CMS - CMS Made Simple +#(c)2004-2008 by Ted Kulp ([email protected]) +#This project's homepage is: http://cmsmadesimple.org +# +#This program is free software; you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation; either version 2 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +#You should have received a copy of the GNU General Public License +#along with this program; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +class Test extends CmsModuleBase +{ + function __construct() + { + parent::__construct(); + } + + function do_action($request, $action_name, $params) + { + return "Blah blah " . $action_name; + } +} + +# vim:ts=4 sw=4 noet +?> \ No newline at end of file
tedkulp/cmsms-nouveau
47aae865a3ada01545c23b70f374d058e158dfad
Another one of those "too long and many to count" commits. PHP 5.3 only compatibility, for one.
diff --git a/components/admin/controllers/class.content_controller.php b/components/admin/controllers/class.content_controller.php new file mode 100644 index 0000000..44c67f8 --- /dev/null +++ b/components/admin/controllers/class.content_controller.php @@ -0,0 +1,27 @@ +<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- +#CMS - CMS Made Simple +#(c)2004-2008 by Ted Kulp ([email protected]) +#This project's homepage is: http://cmsmadesimple.org +# +#This program is free software; you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation; either version 2 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +#You should have received a copy of the GNU General Public License +#along with this program; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +class ContentController extends AdminController +{ + function index($params) + { + $this->set('list', orm('CmsContentBase')->find_all()); + } +} + +?> \ No newline at end of file diff --git a/components/admin/controllers/class.page_controller.php b/components/admin/controllers/class.page_controller.php index 56b5adb..a501269 100644 --- a/components/admin/controllers/class.page_controller.php +++ b/components/admin/controllers/class.page_controller.php @@ -1,135 +1,139 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class PageController extends AdminController { function index($params) { $this->set('tree', CmsPageTree::get_instance()); } function main_content($params) { $page_id = substr($params['node_id'], 5); - $page = orm('CmsPage')->find_by_id($page_id); + $page = CmsPage::find_by_id($page_id); $this->set('page', $page); $ajax = new SilkAjax(); $ajax->replace_html('#main_section', $this->render_partial('main_section.tpl')); $ajax->script('reset_main_content();'); return $ajax->get_result(); } function update_content($params) { $ajax = new SilkAjax(); - $content = new $params['value']; + $page = CmsPage::load($params['page_id']); + $name = substr($params['name'], 11, -1); + $content = $page->get_content_block($name, true); + if ($content == null || get_class($content) != $params['value']) + $content = new $params['value']; $target_id = str_replace('select_', '', $params['parent_id']); $ajax->replace_html('#' . $target_id, $content->get_edit_form()); $ajax->script('setup_content();'); return $ajax->get_result(); } function update_page($params) { - $page = orm('CmsPage')->load($params['page']); + $page = CmsPage::load($params['page']); $ajax = new SilkAjax(); if ($page) { $page->update_parameters($params['page']); } $this->set('page', $page); $ajax->replace_html('#main_section', $this->render_partial('main_section.tpl')); $ajax->script('reset_main_content();'); return $ajax->get_result(); } function check_unique_alias($params) { $ajax = new SilkAjax(); - $count = orm('CmsPage')->find_count(array('conditions' => array('unique_alias = ? AND id != ?', $params['alias'], $params['page_id']))); + $count = CmsPage::find_count(array('conditions' => array('unique_alias = ? AND id != ?', $params['alias'], $params['page_id']))); if ($params['alias'] == '') { $ajax->replace_html('#unique_alias_ok', 'Empty'); $ajax->script('$("#unique_alias_ok").attr("style", "color: red;")'); } else if ($count > 0 || $params['alias'] == '') { $ajax->replace_html('#unique_alias_ok', 'Used'); $ajax->script('$("#unique_alias_ok").attr("style", "color: red;")'); } else { $ajax->replace_html('#unique_alias_ok', 'Ok'); $ajax->script('$("#unique_alias_ok").attr("style", "color: green;")'); } $ajax->script('reset_main_content();'); return $ajax->get_result(); } function check_alias($params) { $ajax = new SilkAjax(); - $count = orm('CmsPage')->find_count(array('conditions' => array('alias = ? AND id != ?', $params['alias'], $params['page_id']))); + $count = CmsPage::find_count(array('conditions' => array('alias = ? AND id != ?', $params['alias'], $params['page_id']))); if ($params['alias'] == '') { $ajax->replace_html('#alias_ok', 'Empty'); $ajax->script('$("#alias_ok").attr("style", "color: red;")'); } else if ($count > 0 || $params['alias'] == '') { $ajax->replace_html('#alias_ok', 'Used'); $ajax->script('$("#alias_ok").attr("style", "color: red;")'); } else { $ajax->replace_html('#alias_ok', 'Ok'); $ajax->script('$("#alias_ok").attr("style", "color: green;")'); } $ajax->script('reset_main_content();'); return $ajax->get_result(); } function save($params) { $ajax = new SilkAjax(); if (isset($params['save']) || isset($params['apply'])) { - $page = orm('CmsPage')->load($params['page']); + $page = CmsPage::load($params['page']); if ($page) { $page->update_parameters($params['page']); if ($page->save()) { $ajax->show('.pagemcontainer'); $ajax->replace_html('#pagemessage', 'Page Saved'); $ajax->script('$(".pagemcontainer").fadeOut(2000)'); return $ajax->get_result(); } } $ajax->show('.pagemcontainer'); $ajax->replace_html('#pagemessage', 'Error Saving Page'); $ajax->script('$(".pagemcontainer").fadeOut(2000)'); } return $ajax->get_result(); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/controllers/class.page_template_controller.php b/components/admin/controllers/class.page_template_controller.php index b9e2bfb..624a275 100644 --- a/components/admin/controllers/class.page_template_controller.php +++ b/components/admin/controllers/class.page_template_controller.php @@ -1,87 +1,87 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class PageTemplateController extends AdminController { function index($params) { - $templates = orm('CmsTemplate')->find_all(); + $templates = CmsTemplate::find_all(); $this->set('templates', $templates); } function add($params) { if ($params['cancel']) { SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); } $template = new CmsTemplate(); if ($params['submit']) { $template->update_parameters($params['template']); if ($template->save()) { $this->flash = 'Template Added'; SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); } } $this->set('template', $template); } function edit($params) { if ($params['cancel'] or !$params['id']) { SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); } - $template = orm('cms_template')->find_by_id($params['id']); + $template = CmsTemplate::find_by_id($params['id']); if ($params['submit'] || $params['apply']) { $template->update_parameters($params['template']); if ($template->save()) { $this->flash = 'Template Updated'; if (!$params['is_silk_ajax']) { SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); } } } $this->set('template', $template); if ($params['is_silk_ajax']) { $ajax = new SilkAjax(); $ajax->replace_html('#pagecontent', $this->render_partial('editform.tpl')); return $ajax->get_result(); } } function delete($params) { $this->flash = orm('CmsTemplate')->delete($params['id']) ? 'Template Deleted' : 'There was an error deleteing the template'; SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/controllers/class.stylesheet_controller.php b/components/admin/controllers/class.stylesheet_controller.php index db56a29..8d9e9eb 100644 --- a/components/admin/controllers/class.stylesheet_controller.php +++ b/components/admin/controllers/class.stylesheet_controller.php @@ -1,77 +1,77 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class StylesheetController extends AdminController { function index($params) { - $stylesheets = orm('CmsStylesheet')->find_all(); + $stylesheets = CmsStylesheet::find_all(); $this->set('stylesheets', $stylesheets); } function add($params) { if ($params['cancel']) { SilkResponse::redirect_to_action(array('controller' => 'stylesheet', 'action' => 'index')); } $stylesheet = new CmsStylesheet(); if ($params['submit']) { $stylesheet->update_parameters($params['stylesheet']); if ($stylesheet->save()) { $this->flash = 'Stylesheet Added'; SilkResponse::redirect_to_action(array('controller' => 'stylesheet', 'action' => 'index')); } } $this->set('stylesheet', $stylesheet); } function edit($params) { if ($params['cancel'] or !$params['id']) { SilkResponse::redirect_to_action(array('controller' => 'stylesheet', 'action' => 'index')); } $stylesheet = orm('CmsStylesheet')->find_by_id($params['id']); if ($params['submit']) { $stylesheet->update_parameters($params['stylesheet']); if ($stylesheet->save()) { $this->flash = 'Stylesheet Updated'; SilkResponse::redirect_to_action(array('controller' => 'stylesheet', 'action' => 'index')); } } $this->set('stylesheet', $stylesheet); } function delete($params) { $this->flash = orm('CmsStylesheet')->delete($params['id']) ? 'Stylesheet Deleted' : 'There was an error deleteing the stylesheet'; SilkResponse::redirect_to_action(array('controller' => 'stylesheet', 'action' => 'index')); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/views/content/index.tpl b/components/admin/views/content/index.tpl new file mode 100644 index 0000000..61c443b --- /dev/null +++ b/components/admin/views/content/index.tpl @@ -0,0 +1,35 @@ +<div class="pageoverflow"> + <div class="pageheader">Content + <span class="helptext"> + <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Stylesheets" rel="external"> + <img src="[[$layout_root_url]]/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> + </a> + <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Stylesheets" rel="external">Help</a> (new window) + </span> + </div> +</div> + +<table cellspacing="0" class="pagetable"> + <thead> + <tr> + <th class="pagew50">Template</th> + <th class="pagepos">Active</th> + <th class="pageicon">&nbsp;</th> + <th class="pageicon">&nbsp;</th> + </tr> + </thead> + <tbody id="tablebody"> + [[render_partial template='indextablebody.tpl']] + </tbody> +</table> + +<div class="pageoptions"> + <p class="pageoptions"> + <span style="float: left;"> + <a href="[[link only_href='true' controller='stylesheet' action='add']]"><img src="[[$layout_root_url]]/images/icons/system/newobject.gif" class="systemicon" alt="Add Stylesheet" title="Add Stylesheet" /></a> + [[link html_class="pageoptions" text="Add Stylesheet" controller="stylesheet" action="add"]] + </span> + </p> +</div> + +<br /> diff --git a/components/admin/views/page/index.tpl b/components/admin/views/page/index.tpl index 3cb2eb0..683ca6b 100644 --- a/components/admin/views/page/index.tpl +++ b/components/admin/views/page/index.tpl @@ -1,95 +1,95 @@ [[assign var='page' value=$tree->get_root_node()]] <h2>Content</h2> <div style="width: 1000px; margin-top: 15px;"> <div id="content_tree" style="width: 240px; float: left; border-right: 1px solid black"> <ul> <li id="node_1" class="open"> <a href="#">ROOT</a> [[if $page->has_children()]] [[assign var='subpages' value=$page->get_children()]] [[render_partial template='branch.tpl']] [[/if]] </li> </ul> </div> <div id="main_section" style="float: right; min-width: 750px; text-align: left;"> </div> </div> <br style="clear: both;" /> <script type="text/javascript"> //<![CDATA[ $('#content_tree').tree( { 'rules' : { 'draggable' : 'all' }, 'callback' : { 'onselect' : function(node, tree_obj) { if (node.id != 'node_1') { silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'main_content'))[[/php]]', [{name:'node_id', value:node.id}]); } else { clear_main_content(); } }, 'ondeselect' : function(node, tree_obj) { clear_main_content(); } } } ); function clear_main_content() { $('#main_section').html(''); } function reset_main_content() { $('#module_page_tabs > ul').tabs(); setup_form(); $('#unique_alias').delayedObserver(function() { silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_unique_alias'))[[/php]]', [{name:'alias', value:$('#unique_alias').val()}, {name:'page_id', value:$('#page_id').html()}]); }, 0.5); $('#alias').delayedObserver(function() { silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_alias'))[[/php]]', [{name:'alias', value:$('#alias').val()}, {name:'page_id', value:$('#page_id').html()}]); }, 0.5); $('#page_template_id').delayedObserver(function() { silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'update_page'))[[/php]]', $('#form_save').serializeArray()); }, 0.5, { event: 'change'}); setup_content(); } function setup_content() { $('.content_type_picker').each(function() { $(this).delayedObserver(function() { - silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'update_content'))[[/php]]', [{name:'parent_id', value:$(this).attr('id')}, {name:'name', value:$(this).attr('name')}, {name:'value', value:$(this).val()}]); + silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'update_content'))[[/php]]', [{name:'parent_id', value:$(this).attr('id')}, {name:'name', value:$(this).attr('name')}, {name:'value', value:$(this).val()}, {name:'page_id', value:$('#page_id').html()}]); }, 0.5, { event: 'change'}); }); } $(document).ready(function() { reset_main_content(); }); //]]></script> diff --git a/components/admin/views/stylesheet/edit.tpl b/components/admin/views/stylesheet/edit.tpl index 6d04f7e..fd0b009 100644 --- a/components/admin/views/stylesheet/edit.tpl +++ b/components/admin/views/stylesheet/edit.tpl @@ -1,10 +1,10 @@ -[[validation_errors for=$stylesheet} +[[validation_errors for=$stylesheet]] -[[form} +[[form]] -[[label for='stylesheet[name]'}Name[[/label}: [[textbox name='stylesheet[name]' value=$stylesheet.name}<br /> -[[label for='stylesheet[value]'}Content[[/label}: [[textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10'}<br /> -[[label for='stylesheet[active]'}Active[[/label}: [[checkbox name='stylesheet[active]' checked=$stylesheet.active}<br /> -[[hidden name='stylesheet[id]' value=$stylesheet.id}[[submit name='submit' value="Submit"}[[submit name='cancel' value="Cancel"} +[[label for='stylesheet[name]']]Name[[/label]]: [[textbox name='stylesheet[name]' value=$stylesheet.name]]<br /> +[[label for='stylesheet[value]']]Content[[/label]]: [[textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10']]<br /> +[[label for='stylesheet[active]']]Active[[/label]]: [[checkbox name='stylesheet[active]' checked=$stylesheet.active]]<br /> +[[hidden name='stylesheet[id]' value=$stylesheet.id]][[submit name='submit' value="Submit"]][[submit name='cancel' value="Cancel"]] -[[/form} \ No newline at end of file +[[/form]] \ No newline at end of file diff --git a/layouts/themes/default/images/black_busy.gif b/layouts/themes/default/images/black_busy.gif new file mode 100644 index 0000000..0630fad Binary files /dev/null and b/layouts/themes/default/images/black_busy.gif differ diff --git a/lib/cmsms/classes/class.cms_module_base.php b/lib/cmsms/classes/class.cms_module_base.php index f994cc7..c6de248 100644 --- a/lib/cmsms/classes/class.cms_module_base.php +++ b/lib/cmsms/classes/class.cms_module_base.php @@ -1,110 +1,110 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class CmsModuleBase extends SilkObject { function __construct() { parent::__construct(); } public function get_name() { return get_class($this); } public function get_module_path() { if (is_subclass_of($this, 'CmsModuleBase')) { return join_path(ROOT_DIR, 'modules' , $this->get_name()); } else { return dirname(__FILE__); } } public static function cms_module_plugin($params, &$smarty) { $module_name = coalesce_key($params, 'module', ''); $action = coalesce_key($params, 'action', 'default'); if ($module_name != '') { $module = CmsModuleLoader::get_module_class($module_name); if ($module) { - @ob_start(); + //@ob_start(); $id = '1'; $request = $module->create_request_instance($id, $returnid); $result = $request->do_action_base($action, $params); if ($result !== FALSE) { echo $result; } - $modresult = @ob_get_contents(); - @ob_end_clean(); + //$modresult = @ob_get_contents(); + //@ob_end_clean(); - return $modresult; + //return $modresult; } } } function create_request_instance($id, $return_id = '') { return new CmsModuleRequest($this, $id, $return_id); } /** * Register a plugin to smarty with the * name of the module. This method should be called * from the module constructor, or from the setup() * method. */ public function register_module_plugin($plugin_name = '', $method_name = 'function_plugin') { if ($plugin_name == '') $plugin_name = $this->get_name(); smarty()->register_function($plugin_name, array($this, $method_name)); } /** * Given a template in a variable, this method processes it through smarty * note, there is no caching involved. */ public function process_template_from_data($data) { $smarty = smarty(); $smarty->_compile_source('temporary template', $data, $_compiled ); @ob_start(); $smarty->_eval('?>' . $_compiled); $_contents = @ob_get_contents(); @ob_end_clean(); return $_contents; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_request.php b/lib/cmsms/classes/class.cms_module_request.php index 819b288..15e15fe 100644 --- a/lib/cmsms/classes/class.cms_module_request.php +++ b/lib/cmsms/classes/class.cms_module_request.php @@ -1,632 +1,641 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ /** * Class to represent one module "request". Basically a wrapper * object to hold a call to a module's action. It will hold * specifc module "session" variables, and also hold methods only * used during a session, including form generation. * * @package cmsms * @author Ted Kulp * @version $Revision$ * @modifiedby $LastChangedBy$ * @lastmodified $Date$ * @license GPL */ class CmsModuleRequest extends SilkObject { var $module = null; var $id = ''; var $return_id = ''; function __construct($module, $id, $return_id = '') { parent::__construct(); $this->module = $module; $this->id = $id; $this->return_id = $return_id; } /** * Getter overload method. Called when a field * does not exist in the object's variable list. * * @param string The field to look up * @return mixed The value for that field, if it exists * @author Ted Kulp **/ function __get($n) { if ($this->module != null) { if (property_exists($this->module, $n)) { return $this->module->$n; } } } /** * Setter overload method. Called when a field * does not exist in the object's variable list. * * @param string The field to set * @param mixed The value to set for said field * @return void * @author Ted Kulp **/ function __set($n, $val) { if ($this->module != null) { if (property_exists($this->module, $n)) { $this->module->$n = $val; } } } /** * Caller overload method. Called when a method does not exist. * * @param string The name of the method called * @param array The parameters sent along with that method call * @return mixed The result of the method call * @author Ted Kulp **/ function __call($function, $arguments) { + if ($arguments == null) + $arguments = array(); + if ($this->module != null) { if (method_exists($this->module, $function)) { return call_user_func_array(array($this->module, $function), $arguments); } } } /** * Used for navigation between "pages" of a module. Forms and links should * pass an action with them so that the module will know what to do next. * By default, DoAction will be passed 'default' and 'defaultadmin', * depending on where the module was called from. If being used as a module * or content type, 'default' will be passed. If the module was selected * from the list on the admin menu, then 'defaultadmin' will be passed. * * @param string Name of the action to perform * @param string The ID of the module * @param string The parameters targeted for this module */ public function do_action($action_name, $params) { + //In case the module overrides it + if (method_exists($this->module, 'do_action')) + { + return $this->module->do_action($this, $action_name, $params); + } + $return_id = $this->return_id; //avoid confusion $returnid = $return_id; if ($action_name != '') { $filename = join_path($this->module->get_module_path(), 'action.' . $action_name . '.php'); if (@is_file($filename)) { { $db = db(); //$config = cms_config(); $smarty = smarty(); $id = $this->id; $smarty->assign_by_ref('request', $this); $smarty->assign('module_action',$action_name); include($filename); } } } } public function do_action_base($name, $incoming_params) { return $this->do_action($name, $incoming_params); } static public function strip_extra_params(&$params, $default_params, $other_params_key = '') { $extra_params = array_diff_key($params, $default_params); $params = $default_params; if ($other_params_key != '' && isset($params[$other_params_key]) && is_array($params[$other_params_key])) { $extra_params = array_merge($extra_params, $params[$other_params_key]); unset($params[$other_params_key]); } return $extra_params; } static public function create_start_tag($name, $params, $self_close = false, $extra_html = '') { $text = "<{$name}"; foreach ($params as $key=>$value) { $text .= " {$key}=\"{$value}\""; } if ($extra_html != '') { $text .= " {$extra}"; } $text .= ($self_close ? ' />' : '>'); return $text; } static public function create_end_tag($name) { return "</{$name}>"; } /** * Returns the start of a module form\n * Parameters: * - 'action' - The action that this form should do when the form is submitted. Defaults to 'default'. * - 'method' - Method to put in the form tag. Defaults to 'post'. * - 'enctype' - Optional enctype for the form. Only real option is 'multipart/form-data'. Defaults to null. * - 'inline' - Boolean to tell whether or not we want the form's result to be "inline". Defaults to false. * - 'id_suffix' - Text to append to the end of the id and name of the form. Defaults to ''. * - 'extra' - Text to append to the <form>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'use_current_page_as_action' - A flag to determine if the action should just * redirect back to this exact page. Defaults to false. * - 'params' - An array of key/value pairs to add as extra hidden parameters. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as hidden * variables to the form and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp **/ public function create_form_start($params = array(), $check_keys = false) { $default_params = array( 'action' => coalesce_key($params, 'action', 'default', FILTER_SANITIZE_URL), 'method' => coalesce_key($params, 'method', 'post', FILTER_SANITIZE_STRING), 'enctype' => coalesce_key($params, 'enctype', '', FILTER_SANITIZE_STRING), 'inline' => coalesce_key($params, 'inline', false, FILTER_VALIDATE_BOOLEAN), 'id_suffix' => coalesce_key($params, 'id_suffix', '', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'use_current_page_as_action' => coalesce_key($params, 'use_current_page_as_action', false, FILTER_VALIDATE_BOOLEAN), 'params' => coalesce_key($params, 'params', array()), 'id' => coalesce_key($params, 'id', $this->id), 'return_id' => coalesce_key($params, 'return_id', $this->return_id) ); $default_params['html_id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['id'].$default_params['action'].$default_params['id_suffix']), FILTER_SANITIZE_STRING ); $default_params['html_name'] = coalesce_key($params, 'html_name', $default_params['html_id'], FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Strip out any straggling parameters to their own array //Merge in anything if it was passed in the params key to the method $extra_params = $this->strip_extra_params($params, $default_params, 'params'); $form_count = cmsms()->get('formcount'); if ($form_count == null) $form_count = 1; $mact = $this->module->get_name().','.$params['id'].','.$params['action'].','.($inline == true?1:0); $goto = ''; $use_current_page_as_action = $params['use_current_page_as_action']; unset($params['use_current_page_as_action']); if ($use_current_page_as_action) $goto = CmsRequest::get_requested_uri(); else $goto = ($params['return_id'] == '' ? 'moduleinterface.php' : 'index.php'); $form_params = array( 'id' => $params['html_id'], 'name' => $params['html_name'], 'method' => $params['method'], 'action' => $goto ); if ($enctype != '') { $form_params['enctype'] = $params['enctype']; } $extra = ''; if ($params['extra']) { $extra = $params['extra']; unset($params['extra']); } $text .= $this->create_start_tag('form', $form_params, false, $extra); $text .= $this->create_start_tag('div', array('class' => 'hidden')); if (!$use_current_page_as_action) $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => 'mact', 'value' => $mact), true); if ($params['return_id'] != '') { $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['id'].'returnid', 'value' => $params['return_id']), true); if ($inline) { $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => cms_config()->get('query_var'), 'value' => $params['return_id']), true); } } foreach ($extra_params as $key=>$value) { if ($key != 'module' && $key != 'action' && $key != 'id') $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['id'].$key, 'value' => $value), true); } $text .= $this->create_end_tag('div'); //end "hidden" cmsms()->set('formcount', $form_count + 1); return $text; } /** * Returns the end of a module form\n * Parameters: * - none * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as hidden * variables to the form and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp **/ public function create_form_end($params = array(), $check_keys = false) { return $this->create_end_tag('form'); } /** * Returns the xhtml equivalent of an input textbox. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant. * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'value' - The value of the field. Defaults to ''. * - 'size' - The length of the input field when displayed. Defaults to 10. * - 'maxlength' - The max length of the value allowed. Defaults to 255. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'label' - If set to a string, a label will be created with the proper "for" value for the input. * - 'label_extra' - Text to append to the <label>-statement, ex. for javascript-validation code. Defaults to ''. * - 'in_between_text' - Text to put between the label and input fields. Defaults to ''. * - 'password' - Boolean to tell whether or not we want it to be a password input. Defaults to false. * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_text($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), 'size' => coalesce_key($params, 'size', 25, FILTER_SANITIZE_NUMBER_INT), 'maxlength' => coalesce_key($params, 'maxlength', 255, FILTER_SANITIZE_NUMBER_INT), 'extra' => coalesce_key($params, 'extra', ''), 'label' => coalesce_key($params, 'label', '', FILTER_SANITIZE_STRING), 'label_extra' => coalesce_key($params, 'label_extra', ''), 'in_between_text' => coalesce_key($params, 'in_between_text', ''), 'password' => coalesce_key($params, 'password', false, FILTER_VALIDATE_BOOLEAN), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); $params['type'] = ($params['password'] == true ? 'password' : 'text'); $text = ''; if ($params['label'] != '') { $text .= $this->create_start_tag('form', array('for' => $params['id']), true, $params['label_extra']); $text .= $params['in_between_text']; } unset($params['label']); unset($params['label_extra']); $text .= $this->create_start_tag('input', $params, true, $extra); return $text; } /** * Returns the xhtml equivalent of an hidden input. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'value' - The value of the field. Defaults to ''. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_hidden($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); $params['type'] = 'hidden'; //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); return $this->create_start_tag('input', $params, true, $extra); } /** * Returns the xhtml equivalent of an checkbox input. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant. Also adds the feature * of making sure that even unchecked checkboxes return a value back to the form.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'checked' - Boolean of whether or not the checkbox is checked. Defaults to false. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_checkbox($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'checked' => coalesce_key($params, 'checked', false, FILTER_VALIDATE_BOOLEAN), 'extra' => coalesce_key($params, 'extra', ''), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); $params['type'] = 'checkbox'; $params['value'] = '1'; if ($params['checked']) $params['checked'] = 'checked'; else unset($params['checked']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; } unset($params['extra']); return $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['name'], 'value' => '0'), true) . $this->create_start_tag('input', $params, true, $extra); } /** * Returns the xhtml equivalent of an submit button. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'value' - The value (text) of the button. Defaults to ''. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'image' - The name of an image to display instead of the text. Defaults to ''. * - 'confirm_text' - If set, a message to display to confirm the click. Defaults to ''. * - 'params' - An array of key/value pairs to add as attributes to the input tag. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * - 'reset' - Boolean of whether or not this is a reset buton. Defaults to false. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_submit($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'image' => coalesce_key($params, 'image', '', FILTER_SANITIZE_STRING), 'confirm_text' => coalesce_key($params, 'confirm_text', '', FILTER_SANITIZE_STRING), 'reset' => coalesce_key($params, 'reset', false, FILTER_VALIDATE_BOOLEAN), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); if ($reset) { $params['type'] = 'reset'; } else if ($params['image'] != '') { $params['type'] = 'image'; $params['src'] = CmsConfig::get('root_url') . '/' . $params['image']; } else { $params['type'] = 'submit'; } unset($params['image']); $extra = ''; if ($params['extra']) { $extra = $params['extra']; if ($params['confirm_text'] != '') { $extra .= ' onclick="return confirm(\''.$params['confirm_text'].'\');"'; } } unset($params['extra']); unset($params['confirm_text']); return $this->create_start_tag('input', $params, true, $extra); } /** * Returns the xhtml equivalent of the opening of a select input. This is basically a nice little wrapper * to make sure that id's are placed in names and also that it's xhtml compliant.\n * Parameters: * - 'name' - The name of the field. Defaults to 'input'. * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. * - 'multiple' - Boolean of whether or not this is should show multiple items. Defaults to false. * - 'size' - Number of items to show if multiple is set to true. Defaults to 3. * - 'params' - An array of key/value pairs to add as attributes to the input tag. These will merge into any * additional parameters you pass along in to the $params hash that aren't parsed by the function. * * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the * tag and merged correctly with anything in the 'params' key if passed. * @param boolean Test whether keys are all valid or not. Not helpful if you're * passing extra key/values along, but good for debugging. * @return string * @author Ted Kulp */ public function create_input_select($params = array(), $check_keys = false) { $default_params = array( 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), 'extra' => coalesce_key($params, 'extra', ''), 'multiple' => coalesce_key($params, 'multiple', false, FILTER_VALIDATE_BOOLEAN), 'size' => coalesce_key($params, 'size', 3, FILTER_SANITIZE_NUMBER_INT), 'params' => coalesce_key($params, 'params', array()) ); $default_params['id'] = coalesce_key($params, 'html_id', CmsResponse::make_dom_id($default_params['name']), FILTER_SANITIZE_STRING ); if ($check_keys && !are_all_keys_valid($params, $default_params)) throw new CmsInvalidKeyException(invalid_key($params, $default_params)); //Combine EVERYTHING together into a big managerie $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); unset($params['params']); if ($params['multiple']) { $params['multiple'] = 'multiple'; } else { unset($params['multiple']); unset($params['size']); } $extra = ''; if ($params['extra']) { $extra = $params['extra']; diff --git a/lib/cmsms/classes/class.cms_page.php b/lib/cmsms/classes/class.cms_page.php index c3f2c9a..44d1e82 100644 --- a/lib/cmsms/classes/class.cms_page.php +++ b/lib/cmsms/classes/class.cms_page.php @@ -1,210 +1,239 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** * Base page class. Extend this to create new content types for * the system. * * @author Ted Kulp * @since 2.0 **/ class CmsPage extends SilkObjectRelationalMapping { var $table = 'pages'; var $params = array('id' => -1, 'template_id' => -1, 'active' => true, 'default_content' => false, 'parent_id' => -1, 'lft' => 1, 'rgt' => 1, 'blocks' => array()); #Stuff needed to do a doppleganger for CmsNode -- Multiple inheritence would rock right now var $tree = null; var $parentnode = null; var $children = array(); function __construct() { parent::__construct(); } function setup() { $this->create_belongs_to_association('template', 'CmsTemplate', 'template_id'); $this->assign_acts_as('NestedSet'); } function display() { smarty()->register_object('current_page', $this); $template_content = $this->template->process(); return $template_content; } + function get_url($rewrite = true, $lang = '') + { + $url = SilkRequest::get_calculated_url_base() . $this->hierarchy_path(); + + /* + $config = cms_config(); + $alias = ($this->alias != ''?$this->alias:$this->id); + if ($config["assume_mod_rewrite"] && $rewrite == true) + { + $url = $config['root_url']. '/' . ($lang != '' ? "$lang/" : '') . $this->HierarchyPath() . (isset($config['page_extension'])?$config['page_extension']:'.html'); + } + else + { + if (isset($_SERVER['PHP_SELF']) && $config['internal_pretty_urls'] == true) + { + $url = $config['root_url'] . '/index.php/' . ($lang != '' ? "$lang/" : '') . $this->HierarchyPath() . (isset($config['page_extension']) ? $config['page_extension + '] : '.html'); + } + else + { + $url = $config['root_url'] . '/index.php?' . $config['query_var'] . '=' . $alias . ($lang != '' ? '&amp;lang=' . $lang : ''); + } + } + */ + + return $url; + } + + function get_content_block($block_name = 'default', $can_return_new = false) { if (isset($this->blocks[$block_name])) { if (isset($this->blocks[$block_name]['id'])) { $content = orm('CmsContentBase')->find_by_id($this->blocks[$block_name]['id']); if ($content != null) { return $content; } } } if ($can_return_new) return new CmsHtmlContent(); //TODO: Fix me else return null; } function get_content($block_name = 'default') { $block = $this->get_content_block($block_name); if ($block != null) { return $block->get_content(); } return '<!-- No content found for ' . $block_name . ' -->'; } /** * Function content types to use to say whether or not they should show * up in lists where parents of content are set. This will default to true, * but should be used in cases like Separator where you don't want it to * have any children. * * @since 0.11 */ function wants_children() { return true; } function can_preview() { return false; } function template_name() { $tmp = $this->template; if ($tmp) return $tmp->name; return ''; } function add_child($node) { $node->set_parent($this); $node->tree = $this->tree; $this->children[] = $node; } function get_tree() { return $this->tree; } function has_children() { return $this->rgt > $this->lft + 1; } function depth() { $depth = 0; $currLevel = &$this; while ($currLevel->parentnode) { $depth++; $currLevel = &$currLevel->parentnode; } return $depth; } function get_level() { return $this->depth(); } function getLevel() { return $this->depth(); } function get_parent() { return $this->parentnode; } function set_parent($node) { $this->parentnode = $node; } function get_children_count() { return count($this->children); } function getChildrenCount() { return $this->get_children_count(); } function &get_children() { if ($this->has_children()) { //We know there are children, but no nodes have been //created yet. We should probably do that. if (!$this->children_loaded()) { //$this->tree->load_child_nodes(-1, $this->lft, $this->rgt); $this->tree->load_child_nodes($this->id); } } return $this->children; } function &get_flat_list() { $return = array(); if ($this->has_children()) { for ($i=0; $i<count($this->children); $i++) { $return[] = &$this->children[$i]; $return = array_merge($return, $this->children[$i]->get_flat_list()); } } return $return; } function &getFlatList() { $tmp =& $this->get_flat_list(); return $tmp; } } ?> diff --git a/lib/cmsms/classes/class.cms_route.php b/lib/cmsms/classes/class.cms_route.php index 7832364..7a54141 100644 --- a/lib/cmsms/classes/class.cms_route.php +++ b/lib/cmsms/classes/class.cms_route.php @@ -1,92 +1,92 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ /** * Class to handle url routes for modules to handle pretty urls. * * @author Ted Kulp * @since 2.0 **/ class CmsRoute extends SilkObject { var $module; var $regex; var $defaults; function __construct() { parent::__construct(); } /* public static function run($params, $page) { $page_obj = SilkCache::get_instance()->call('CmsRoute::match_route', $page); if ($page_obj) { echo SilkCache::get_instance()->call(array($page_obj, 'display')); } //TODO: Remove me echo SilkProfiler::get_instance()->report(); } */ public static function run($params, $page) { CmsModuleLoader::load_module_data(); - echo SilkCache::get_instance()->call('CmsRoute::_run', $params, $page); + //TODO: This is a full page cahce. It needs options. + //echo SilkCache::get_instance()->call('CmsRoute::_run', $params, $page); + echo CmsRoute::_run($params, $page); //TODO: Remove me echo SilkProfiler::get_instance()->report(); } public static function _run($params, $page) { $page_obj = CmsRoute::match_route($page); if ($page_obj) { return $page_obj->display(); } + //TODO: This is where we do some 404 logic. + var_dump('404'); + return ''; } public static function match_route($page) { $page_obj = null; if ($page == '' || $page == '/') - $page_obj = orm('CmsPage')->find_by_default_page(true); + $page_obj = CmsPage::find_by_default_page(true); else - $page_obj = orm('CmsPage')->find_by_hierarchy_path($page); + $page_obj = CmsPage::find_by_hierarchy_path($page); - if ($page_obj == null) - { - var_dump('404 here'); - } - return $page_obj; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/modules/MenuManager/MenuManager.module.php b/modules/MenuManager/MenuManager.module.php index 43ee7ee..896c5b5 100644 --- a/modules/MenuManager/MenuManager.module.php +++ b/modules/MenuManager/MenuManager.module.php @@ -1,178 +1,178 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2009 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class MenuManager extends CmsModuleBase { function __construct() { parent::__construct(); } function setup() { $this->register_module_plugin('menu_children', 'menu_children_plugin_callback'); } public function menu_children_plugin_callback($params, &$smarty) { $orig_params = $smarty->get_template_vars('orig_params'); $params = array_merge($orig_params, $params); if (!isset($params['node'])) { return; } if ($params['node']->has_children()) { $this->current_depth++; //Handle number_of_levels param if (!isset($params['number_of_levels']) || $params['number_of_levels'] > $this->current_depth) { //Handle collapse param if (!isset($params['collapse']) || $params['collapse'] != true || starts_with(cmsms()->variables['position'] . '.', $params['node']->hierarchy . '.')) { $this->display_menu($params['node']->get_children(), $params, false); } } $this->current_depth--; } } public function display_menu(&$nodes, $params, $first_call = true) { $usefile = true; //$lang = CmsMultiLanguage::get_client_language(); $lang = 'en_US'; $mdid = md5('12345'); //md5(cmsms()->variables['content_id'].implode('|', $params).$lang); $tpl_name = coalesce_key($params, 'template', ''); if (!ends_with($tpl_name, '.tpl')) { $usefile = false; } if (is_array($nodes)) { $count = 0; foreach ($nodes as &$node) { $this->add_fields_to_node($node); $node->show = $this->should_show_node($node, $params); //Numeric Stuff $node->first = ($count == 0); $node->last = ($count + 1 == count($nodes)); $node->index = $count; $count++; } $smarty = smarty(); $smarty->assign('count', count($nodes)); $smarty->assign_by_ref('nodelist', $nodes); if ($first_call) { $smarty->assign('orig_params', $params); $this->current_depth = 1; } //echo $this->process_template_from_database($id, $return_id, 'menu_template', $tpl_name); echo $this->process_template_from_data($this->get_default_template()); } } public function add_fields_to_node(&$node) { $node->url = $node->get_url(true, $lang); $node->menutext = $node->get_property_value('menu_text', $lang); $node->haschildren = $node->has_children(); $node->target = ''; if ($node->has_property('target')) $node->target = $node->get_property_value('target'); $node->depth = $this->current_depth; } public function should_show_node(&$node, $params) { $include = true; $exclude = false; if (isset($params['includeprefix'])) { $include = false; $prefixes = explode(',', $params['includeprefix']); foreach ($prefixes as $oneprefix) { if (starts_with(strtolower($node->alias), strtolower($oneprefix))) { $include = true; break; } } } if (isset($params['excludeprefix'])) { $prefixes = explode(',', $params['excludeprefix']); foreach ($prefixes as $oneprefix) { if (starts_with(strtolower($node->alias), strtolower($oneprefix))) { $exclude = true; break; } } } $should_show = $node->active && $node->show_in_menu && ($include && !$exclude); //Override is show_all is true if (isset($params['show_all']) && $params['show_all']) $should_show = true; return $should_show; } function get_default_template() { return '[[if $count > 0]] <ul> [[foreach from=$nodelist item=node]] [[if $node->show]] <li> - <a href="[[$node->url]]">[[$node->menutext]]</a> + <a href="[[$node->get_url()]]">[[$node->menu_text]]</a> [[menu_children node=$node]] </li> [[/if]] [[/foreach]] </ul> [[/if]] '; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/modules/MenuManager/action.default.php b/modules/MenuManager/action.default.php index ae1309f..77c22d2 100644 --- a/modules/MenuManager/action.default.php +++ b/modules/MenuManager/action.default.php @@ -1,93 +1,93 @@ <?php SilkProfiler::get_instance()->mark('Start of Menu Manager Display'); $root_node = null; if (isset($params['start_page']) || isset($params['start_element'])) { $tree = CmsPageTree::get_instance(); $root_node = null; if (isset($params['start_page'])) { $root_node = $tree->get_node_by_alias($params['start_page']); } else { $root_node = $tree->get_node_by_hierarchy($params['start_element']); } if ($root_node != null) { if (isset($params['show_root_siblings']) && $params['show_root_siblings']) { $parent_node = $root_node->get_parent(); if ($parent_node != null) { - $this->display_menu($parent_node->get_children(), $params); + $this->module->display_menu($parent_node->get_children(), $params); } } else if (isset($params['show_only_children']) && $params['show_only_children']) { - $this->display_menu($root_node->get_children(), $params); + $this->module->display_menu($root_node->get_children(), $params); } else { //Hack alert! //Make an array of one and pass that $ary = array($root_node); - $this->display_menu($ary, $params); + $this->module->display_menu($ary, $params); } } } else if (isset($params['start_level']) && $params['start_level'] > 1) { $tree = CmsPageTree::get_instance(); $curnode = $tree->get_node_by_id(cmsms()->variables['content_id']); if ($curnode != null) { $ids = explode('.', $curnode->id_hierarchy()); if (count($ids) >= $params['start_level'] - 2) { $parent_node = $tree->get_node_by_id($ids[$params['start_level'] - 2]); if ($parent_node != null && $parent_node->has_children()) { - $this->display_menu($parent_node->get_children(), $params); + $this->module->display_menu($parent_node->get_children(), $params); } } } } else if (isset($params['items'])) { $result = array(); $tree = CmsPageTree::get_instance(); $items = explode(',', $params['items']); if ($tree != null && count($items) > 0) { foreach ($items as $oneitem) { $curnode = $tree->get_node_by_alias(trim($oneitem)); if ($curnode) { $result[] = $curnode; } } } if (count($result) > 0) { $params['number_of_levels'] = 1; - $this->display_menu($result, $params); + $this->module->display_menu($result, $params); } } else { - $this->display_menu(CmsPageTree::get_instance()->get_root_node()->get_children(), $params); + $this->module->display_menu(CmsPageTree::get_instance()->get_root_node()->get_children(), $params); } SilkProfiler::get_instance()->mark('End of Menu Manager Display'); ?> \ No newline at end of file
tedkulp/cmsms-nouveau
889c844a5f5c57876844992fb1570b071a43f79a
Working on module handling
diff --git a/lib/cmsms/classes/class.cms_module_base.php b/lib/cmsms/classes/class.cms_module_base.php index 60adc8d..f994cc7 100644 --- a/lib/cmsms/classes/class.cms_module_base.php +++ b/lib/cmsms/classes/class.cms_module_base.php @@ -1,39 +1,110 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class CmsModuleBase extends SilkObject { function __construct() { parent::__construct(); } - function do_action_base($name, $id = '', $params = '', $return_id = '') + public function get_name() { - return $this->do_action($name, $id, $params, $return_id); + return get_class($this); } - function do_action($name, $id = '', $params = '', $return_id = '') + public function get_module_path() { + if (is_subclass_of($this, 'CmsModuleBase')) + { + return join_path(ROOT_DIR, 'modules' , $this->get_name()); + } + else + { + return dirname(__FILE__); + } } + + public static function cms_module_plugin($params, &$smarty) + { + $module_name = coalesce_key($params, 'module', ''); + $action = coalesce_key($params, 'action', 'default'); + if ($module_name != '') + { + $module = CmsModuleLoader::get_module_class($module_name); + if ($module) + { + @ob_start(); + + $id = '1'; + + $request = $module->create_request_instance($id, $returnid); + $result = $request->do_action_base($action, $params); + if ($result !== FALSE) + { + echo $result; + } + $modresult = @ob_get_contents(); + @ob_end_clean(); + + return $modresult; + } + } + } + + function create_request_instance($id, $return_id = '') + { + return new CmsModuleRequest($this, $id, $return_id); + } + + /** + * Register a plugin to smarty with the + * name of the module. This method should be called + * from the module constructor, or from the setup() + * method. + */ + public function register_module_plugin($plugin_name = '', $method_name = 'function_plugin') + { + if ($plugin_name == '') + $plugin_name = $this->get_name(); + + smarty()->register_function($plugin_name, array($this, $method_name)); + } + + + /** + * Given a template in a variable, this method processes it through smarty + * note, there is no caching involved. + */ + public function process_template_from_data($data) + { + $smarty = smarty(); + $smarty->_compile_source('temporary template', $data, $_compiled ); + @ob_start(); + $smarty->_eval('?>' . $_compiled); + $_contents = @ob_get_contents(); + @ob_end_clean(); + return $_contents; + } + } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_loader.php b/lib/cmsms/classes/class.cms_module_loader.php index 44a4027..63c39d1 100644 --- a/lib/cmsms/classes/class.cms_module_loader.php +++ b/lib/cmsms/classes/class.cms_module_loader.php @@ -1,266 +1,286 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class CmsModuleLoader extends SilkObject { public static $module_list = null; function __construct() { parent::__construct(); } public static function load_module_data() { $files = CmsModuleLoader::find_module_info_files(); //Actually slower if it's cached -- have to retest with lots of modules $installed_data = SilkCache::get_instance()->call('CmsModuleLoader::get_installed_module_details'); $module_list = array(); foreach ($files as $one_file) { $module_data = self::xmlify_module_info_file($one_file); $module_data = self::inject_installed_data_for_module($module_data, $installed_data); $module_list[$module_data['name']] = $module_data; } self::check_core_version($module_list); self::check_dependencies($module_list); self::$module_list = $module_list; } public static function check_core_version(&$module_list) { foreach ($module_list as &$one_module) { if (isset($one_module['minimum_core_version'])) { if (version_compare($one_module['minimum_core_version'], '2.0', '>')) //Use a real version number here { $one_module['meets_minimum_core'] = false; $one_module['active'] = false; } } } } public static function check_dependencies(&$module_list) { foreach ($module_list as $one_module) { self::check_dependencies_for_module($one_module['name'], $module_list); } } public static function check_dependencies_for_module($module_name, &$module_list) { //Make sure we haven't done this one yet -- no point in repeating if (!isset($module_list[$module_name]['meets_dependencies'])) { $module_list[$module_name]['meets_dependencies'] = true; if (isset($module_list[$module_name]['dependencies']) && is_array($module_list[$module_name]['dependencies'])) { //Hack for handling 1 module dependency if (isset($module_list[$module_name]['dependencies']['module'])) { $tmp = $module_list[$module_name]['dependencies']['module']; unset($module_list[$module_name]['dependencies']['module']); $module_list[$module_name]['dependencies'][0]['module'] = $tmp; } for ($i = 0; $i < count($module_list[$module_name]['dependencies']); $i++) { //If a module dependency (only kind for now) if (isset($module_list[$module_name]['dependencies'][$i]['module'])) { $one_dep = $module_list[$module_name]['dependencies'][$i]['module']; //Does this dependency exist at all? if (isset($module_list[$one_dep['name']])) { //Make sure we process any dependencies first self::check_dependencies_for_module($one_dep['name'], $module_list); //Now that it's processed, check for active and installed_version stuff if ($module_list[$one_dep['name']]['active'] == false) { //var_dump('parent is not active: ' . $one_dep['name'] . ' from ' . $module_name); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } else if (isset($one_dep['minimum_version']) && version_compare($one_dep['minimum_version'], $module_list[$one_dep['name']]['installed_version'], '>')) { //var_dump('does not meet minimum version: ' . $one_dep['name'] . ' from ' . $module_name); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } } else { //var_dump('does not exist: ' . $one_dep['name']); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } } } } } } + public static function get_proper_module_case($name) + { + if (self::$module_list != null) + { + foreach (self::$module_list as $k=>$v) + { + if (strtolower($k) == strtolower($name)) + { + return $k; + } + } + } + + return name; + } + public static function get_module_class($name) { if (self::$module_list != null) { + //Make sure we can call modules without checking case + $name = self::get_proper_module_case($name); + if (isset(self::$module_list[$name]) && self::$module_list[$name]['active'] == true) { if (isset(self::$module_list[$name]['object'])) { return self::$module_list[$name]['object']; } else { require_once(join_path(ROOT_DIR, 'modules', $name, $name . '.module.php')); if (class_exists($name) && is_subclass_of($name, 'CmsModuleBase')) { if (isset(self::$module_list[$name]['dependencies'])) { foreach (self::$module_list[$name]['dependencies'] as $dep) { self::get_module_class($dep['module']['name']); } } //var_dump('Instantiating: ' . $name); self::$module_list[$name]['object'] = new $name(); + self::$module_list[$name]['object']->setup(); return self::$module_list[$name]['object']; } } } } return null; } public static function is_installed($name) { if (isset(self::$module_list[$name]) && isset(self::$module_list[$name]['installed'])) return self::$module_list[$name]['installed']; return false; } public static function is_active($name) { if (isset(self::$module_list[$name]) && isset(self::$module_list[$name]['active'])) return self::$module_list[$name]['active']; return false; } public static function get_installed_module_details() { $db_prefix = db_prefix(); return db()->GetAll("select * from {$db_prefix}modules"); } public static function inject_installed_data_for_module($module_data, $installed_data) { $module_data['installed'] = false; $module_data['active'] = false; $module_data['installed_version'] = $module_data['version']; $module_data['needs_upgrade'] = false; $module_data['meets_minimum_core'] = true; foreach($installed_data as $one_row) { if ($one_row['module_name'] == $module_data['name']) { $module_data['installed'] = true; $module_data['active'] = ($one_row['active'] == '1' ? true : false); $module_data['installed_version'] = $one_row['version']; $module_data['needs_upgrade'] = version_compare($module_data['installed_version'], $one_row['version'], '<'); } } return $module_data; } public static function xmlify_module_info_file($file) { $xml = simplexml_load_file($file); return self::convert_xml_to_array($xml); } public static function convert_xml_to_array($xml) { if (!($xml->children())) { return (string) $xml; } foreach ($xml->children() as $child) { $name = $child->getName(); if (count($xml->$name) == 1) { $element[$name] = self::convert_xml_to_array($child); } else { $element[][$name] = self::convert_xml_to_array($child); } } return $element; } public static function find_module_info_files() { $filelist = array(); $dir = join_path(ROOT_DIR, 'modules'); if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..') { $mod_dir = join_path($dir, $file); if (is_dir($mod_dir)) { $mod_info_file = join_path($dir, $file, $file . '.info.xml'); if (is_file($mod_info_file) && is_readable($mod_info_file)) { $filelist[] = $mod_info_file; } } } } closedir($dh); } } return $filelist; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_request.php b/lib/cmsms/classes/class.cms_module_request.php new file mode 100644 index 0000000..819b288 --- /dev/null +++ b/lib/cmsms/classes/class.cms_module_request.php @@ -0,0 +1,728 @@ +<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- +#CMS - CMS Made Simple +#(c)2004-2008 by Ted Kulp ([email protected]) +#This project's homepage is: http://cmsmadesimple.org +# +#This program is free software; you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation; either version 2 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +#You should have received a copy of the GNU General Public License +#along with this program; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +#$Id$ + +/** + * Class to represent one module "request". Basically a wrapper + * object to hold a call to a module's action. It will hold + * specifc module "session" variables, and also hold methods only + * used during a session, including form generation. + * + * @package cmsms + * @author Ted Kulp + * @version $Revision$ + * @modifiedby $LastChangedBy$ + * @lastmodified $Date$ + * @license GPL + */ +class CmsModuleRequest extends SilkObject +{ + var $module = null; + var $id = ''; + var $return_id = ''; + + function __construct($module, $id, $return_id = '') + { + parent::__construct(); + + $this->module = $module; + $this->id = $id; + $this->return_id = $return_id; + } + + /** + * Getter overload method. Called when a field + * does not exist in the object's variable list. + * + * @param string The field to look up + * @return mixed The value for that field, if it exists + * @author Ted Kulp + **/ + function __get($n) + { + if ($this->module != null) + { + if (property_exists($this->module, $n)) + { + return $this->module->$n; + } + } + } + + /** + * Setter overload method. Called when a field + * does not exist in the object's variable list. + * + * @param string The field to set + * @param mixed The value to set for said field + * @return void + * @author Ted Kulp + **/ + function __set($n, $val) + { + if ($this->module != null) + { + if (property_exists($this->module, $n)) + { + $this->module->$n = $val; + } + } + } + + /** + * Caller overload method. Called when a method does not exist. + * + * @param string The name of the method called + * @param array The parameters sent along with that method call + * @return mixed The result of the method call + * @author Ted Kulp + **/ + function __call($function, $arguments) + { + if ($this->module != null) + { + if (method_exists($this->module, $function)) + { + return call_user_func_array(array($this->module, $function), $arguments); + } + } + } + + /** + * Used for navigation between "pages" of a module. Forms and links should + * pass an action with them so that the module will know what to do next. + * By default, DoAction will be passed 'default' and 'defaultadmin', + * depending on where the module was called from. If being used as a module + * or content type, 'default' will be passed. If the module was selected + * from the list on the admin menu, then 'defaultadmin' will be passed. + * + * @param string Name of the action to perform + * @param string The ID of the module + * @param string The parameters targeted for this module + */ + public function do_action($action_name, $params) + { + $return_id = $this->return_id; //avoid confusion + $returnid = $return_id; + + if ($action_name != '') + { + $filename = join_path($this->module->get_module_path(), 'action.' . $action_name . '.php'); + + if (@is_file($filename)) + { + { + $db = db(); + //$config = cms_config(); + $smarty = smarty(); + $id = $this->id; + + $smarty->assign_by_ref('request', $this); + $smarty->assign('module_action',$action_name); + + include($filename); + + } + } + } + } + + public function do_action_base($name, $incoming_params) + { + return $this->do_action($name, $incoming_params); + } + + static public function strip_extra_params(&$params, $default_params, $other_params_key = '') + { + $extra_params = array_diff_key($params, $default_params); + $params = $default_params; + if ($other_params_key != '' && isset($params[$other_params_key]) && is_array($params[$other_params_key])) + { + $extra_params = array_merge($extra_params, $params[$other_params_key]); + unset($params[$other_params_key]); + } + return $extra_params; + } + + static public function create_start_tag($name, $params, $self_close = false, $extra_html = '') + { + $text = "<{$name}"; + + foreach ($params as $key=>$value) + { + $text .= " {$key}=\"{$value}\""; + } + + if ($extra_html != '') + { + $text .= " {$extra}"; + } + + $text .= ($self_close ? ' />' : '>'); + + return $text; + } + + static public function create_end_tag($name) + { + return "</{$name}>"; + } + + /** + * Returns the start of a module form\n + * Parameters: + * - 'action' - The action that this form should do when the form is submitted. Defaults to 'default'. + * - 'method' - Method to put in the form tag. Defaults to 'post'. + * - 'enctype' - Optional enctype for the form. Only real option is 'multipart/form-data'. Defaults to null. + * - 'inline' - Boolean to tell whether or not we want the form's result to be "inline". Defaults to false. + * - 'id_suffix' - Text to append to the end of the id and name of the form. Defaults to ''. + * - 'extra' - Text to append to the <form>-statement, ex. for javascript-validation code. Defaults to ''. + * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. + * - 'use_current_page_as_action' - A flag to determine if the action should just + * redirect back to this exact page. Defaults to false. + * - 'params' - An array of key/value pairs to add as extra hidden parameters. These will merge into any + * additional parameters you pass along in to the $params hash that aren't parsed by the function. + * + * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as hidden + * variables to the form and merged correctly with anything in the 'params' key if passed. + * @param boolean Test whether keys are all valid or not. Not helpful if you're + * passing extra key/values along, but good for debugging. + * @return string + * @author Ted Kulp + **/ + public function create_form_start($params = array(), $check_keys = false) + { + $default_params = array( + 'action' => coalesce_key($params, 'action', 'default', FILTER_SANITIZE_URL), + 'method' => coalesce_key($params, 'method', 'post', FILTER_SANITIZE_STRING), + 'enctype' => coalesce_key($params, 'enctype', '', FILTER_SANITIZE_STRING), + 'inline' => coalesce_key($params, 'inline', false, FILTER_VALIDATE_BOOLEAN), + 'id_suffix' => coalesce_key($params, 'id_suffix', '', FILTER_SANITIZE_STRING), + 'extra' => coalesce_key($params, 'extra', ''), + 'use_current_page_as_action' => coalesce_key($params, 'use_current_page_as_action', false, FILTER_VALIDATE_BOOLEAN), + 'params' => coalesce_key($params, 'params', array()), + 'id' => coalesce_key($params, 'id', $this->id), + 'return_id' => coalesce_key($params, 'return_id', $this->return_id) + ); + $default_params['html_id'] = coalesce_key($params, + 'html_id', + CmsResponse::make_dom_id($default_params['id'].$default_params['action'].$default_params['id_suffix']), + FILTER_SANITIZE_STRING + ); + $default_params['html_name'] = coalesce_key($params, + 'html_name', + $default_params['html_id'], + FILTER_SANITIZE_STRING + ); + + if ($check_keys && !are_all_keys_valid($params, $default_params)) + throw new CmsInvalidKeyException(invalid_key($params, $default_params)); + + //Strip out any straggling parameters to their own array + //Merge in anything if it was passed in the params key to the method + $extra_params = $this->strip_extra_params($params, $default_params, 'params'); + + $form_count = cmsms()->get('formcount'); + if ($form_count == null) + $form_count = 1; + + $mact = $this->module->get_name().','.$params['id'].','.$params['action'].','.($inline == true?1:0); + $goto = ''; + $use_current_page_as_action = $params['use_current_page_as_action']; unset($params['use_current_page_as_action']); + if ($use_current_page_as_action) + $goto = CmsRequest::get_requested_uri(); + else + $goto = ($params['return_id'] == '' ? 'moduleinterface.php' : 'index.php'); + + $form_params = array( + 'id' => $params['html_id'], + 'name' => $params['html_name'], + 'method' => $params['method'], + 'action' => $goto + ); + + if ($enctype != '') + { + $form_params['enctype'] = $params['enctype']; + } + + $extra = ''; + if ($params['extra']) + { + $extra = $params['extra']; + unset($params['extra']); + } + + $text .= $this->create_start_tag('form', $form_params, false, $extra); + $text .= $this->create_start_tag('div', array('class' => 'hidden')); + + if (!$use_current_page_as_action) + $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => 'mact', 'value' => $mact), true); + + if ($params['return_id'] != '') + { + $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['id'].'returnid', 'value' => $params['return_id']), true); + if ($inline) + { + $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => cms_config()->get('query_var'), 'value' => $params['return_id']), true); + } + } + + foreach ($extra_params as $key=>$value) + { + if ($key != 'module' && $key != 'action' && $key != 'id') + $text .= $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['id'].$key, 'value' => $value), true); + } + + $text .= $this->create_end_tag('div'); //end "hidden" + + cmsms()->set('formcount', $form_count + 1); + + return $text; + } + + /** + * Returns the end of a module form\n + * Parameters: + * - none + * + * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as hidden + * variables to the form and merged correctly with anything in the 'params' key if passed. + * @param boolean Test whether keys are all valid or not. Not helpful if you're + * passing extra key/values along, but good for debugging. + * @return string + * @author Ted Kulp + **/ + public function create_form_end($params = array(), $check_keys = false) + { + return $this->create_end_tag('form'); + } + + /** + * Returns the xhtml equivalent of an input textbox. This is basically a nice little wrapper + * to make sure that id's are placed in names and also that it's xhtml compliant. + * Parameters: + * - 'name' - The name of the field. Defaults to 'input'. + * - 'value' - The value of the field. Defaults to ''. + * - 'size' - The length of the input field when displayed. Defaults to 10. + * - 'maxlength' - The max length of the value allowed. Defaults to 255. + * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. + * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. + * - 'label' - If set to a string, a label will be created with the proper "for" value for the input. + * - 'label_extra' - Text to append to the <label>-statement, ex. for javascript-validation code. Defaults to ''. + * - 'in_between_text' - Text to put between the label and input fields. Defaults to ''. + * - 'password' - Boolean to tell whether or not we want it to be a password input. Defaults to false. + * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any + * additional parameters you pass along in to the $params hash that aren't parsed by the function. + * + * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the + * tag and merged correctly with anything in the 'params' key if passed. + * @param boolean Test whether keys are all valid or not. Not helpful if you're + * passing extra key/values along, but good for debugging. + * @return string + * @author Ted Kulp + */ + public function create_input_text($params = array(), $check_keys = false) + { + $default_params = array( + 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), + 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), + 'size' => coalesce_key($params, 'size', 25, FILTER_SANITIZE_NUMBER_INT), + 'maxlength' => coalesce_key($params, 'maxlength', 255, FILTER_SANITIZE_NUMBER_INT), + 'extra' => coalesce_key($params, 'extra', ''), + 'label' => coalesce_key($params, 'label', '', FILTER_SANITIZE_STRING), + 'label_extra' => coalesce_key($params, 'label_extra', ''), + 'in_between_text' => coalesce_key($params, 'in_between_text', ''), + 'password' => coalesce_key($params, 'password', false, FILTER_VALIDATE_BOOLEAN), + 'params' => coalesce_key($params, 'params', array()) + ); + $default_params['id'] = coalesce_key($params, + 'html_id', + CmsResponse::make_dom_id($default_params['name']), + FILTER_SANITIZE_STRING + ); + + if ($check_keys && !are_all_keys_valid($params, $default_params)) + throw new CmsInvalidKeyException(invalid_key($params, $default_params)); + + //Combine EVERYTHING together into a big managerie + $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); + unset($params['params']); + + $extra = ''; + if ($params['extra']) + { + $extra = $params['extra']; + } + unset($params['extra']); + + $params['type'] = ($params['password'] == true ? 'password' : 'text'); + + $text = ''; + + if ($params['label'] != '') + { + $text .= $this->create_start_tag('form', array('for' => $params['id']), true, $params['label_extra']); + $text .= $params['in_between_text']; + } + + unset($params['label']); + unset($params['label_extra']); + + $text .= $this->create_start_tag('input', $params, true, $extra); + + return $text; + } + + /** + * Returns the xhtml equivalent of an hidden input. This is basically a nice little wrapper + * to make sure that id's are placed in names and also that it's xhtml compliant.\n + * Parameters: + * - 'name' - The name of the field. Defaults to 'input'. + * - 'value' - The value of the field. Defaults to ''. + * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. + * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. + * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any + * additional parameters you pass along in to the $params hash that aren't parsed by the function. + * + * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the + * tag and merged correctly with anything in the 'params' key if passed. + * @param boolean Test whether keys are all valid or not. Not helpful if you're + * passing extra key/values along, but good for debugging. + * @return string + * @author Ted Kulp + */ + public function create_input_hidden($params = array(), $check_keys = false) + { + $default_params = array( + 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), + 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), + 'extra' => coalesce_key($params, 'extra', ''), + 'params' => coalesce_key($params, 'params', array()) + ); + $default_params['id'] = coalesce_key($params, + 'html_id', + CmsResponse::make_dom_id($default_params['name']), + FILTER_SANITIZE_STRING + ); + + if ($check_keys && !are_all_keys_valid($params, $default_params)) + throw new CmsInvalidKeyException(invalid_key($params, $default_params)); + + $params['type'] = 'hidden'; + + //Combine EVERYTHING together into a big managerie + $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); + unset($params['params']); + + $extra = ''; + if ($params['extra']) + { + $extra = $params['extra']; + } + unset($params['extra']); + + return $this->create_start_tag('input', $params, true, $extra); + } + + /** + * Returns the xhtml equivalent of an checkbox input. This is basically a nice little wrapper + * to make sure that id's are placed in names and also that it's xhtml compliant. Also adds the feature + * of making sure that even unchecked checkboxes return a value back to the form.\n + * Parameters: + * - 'name' - The name of the field. Defaults to 'input'. + * - 'checked' - Boolean of whether or not the checkbox is checked. Defaults to false. + * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. + * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. + * - 'params' - An array of key/value pairs to add as attributes to the input command. These will merge into any + * additional parameters you pass along in to the $params hash that aren't parsed by the function. + * + * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the + * tag and merged correctly with anything in the 'params' key if passed. + * @param boolean Test whether keys are all valid or not. Not helpful if you're + * passing extra key/values along, but good for debugging. + * @return string + * @author Ted Kulp + */ + public function create_input_checkbox($params = array(), $check_keys = false) + { + $default_params = array( + 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), + 'checked' => coalesce_key($params, 'checked', false, FILTER_VALIDATE_BOOLEAN), + 'extra' => coalesce_key($params, 'extra', ''), + 'params' => coalesce_key($params, 'params', array()) + ); + $default_params['id'] = coalesce_key($params, + 'html_id', + CmsResponse::make_dom_id($default_params['name']), + FILTER_SANITIZE_STRING + ); + + if ($check_keys && !are_all_keys_valid($params, $default_params)) + throw new CmsInvalidKeyException(invalid_key($params, $default_params)); + + //Combine EVERYTHING together into a big managerie + $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); + unset($params['params']); + + $params['type'] = 'checkbox'; + $params['value'] = '1'; + + if ($params['checked']) + $params['checked'] = 'checked'; + else + unset($params['checked']); + + $extra = ''; + if ($params['extra']) + { + $extra = $params['extra']; + } + unset($params['extra']); + + return $this->create_start_tag('input', array('type' => 'hidden', 'name' => $params['name'], 'value' => '0'), true) . + $this->create_start_tag('input', $params, true, $extra); + } + + /** + * Returns the xhtml equivalent of an submit button. This is basically a nice little wrapper + * to make sure that id's are placed in names and also that it's xhtml compliant.\n + * Parameters: + * - 'name' - The name of the field. Defaults to 'input'. + * - 'value' - The value (text) of the button. Defaults to ''. + * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. + * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. + * - 'image' - The name of an image to display instead of the text. Defaults to ''. + * - 'confirm_text' - If set, a message to display to confirm the click. Defaults to ''. + * - 'params' - An array of key/value pairs to add as attributes to the input tag. These will merge into any + * additional parameters you pass along in to the $params hash that aren't parsed by the function. + * - 'reset' - Boolean of whether or not this is a reset buton. Defaults to false. + * + * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the + * tag and merged correctly with anything in the 'params' key if passed. + * @param boolean Test whether keys are all valid or not. Not helpful if you're + * passing extra key/values along, but good for debugging. + * @return string + * @author Ted Kulp + */ + public function create_input_submit($params = array(), $check_keys = false) + { + $default_params = array( + 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), + 'value' => coalesce_key($params, 'value', '', FILTER_SANITIZE_STRING), + 'extra' => coalesce_key($params, 'extra', ''), + 'image' => coalesce_key($params, 'image', '', FILTER_SANITIZE_STRING), + 'confirm_text' => coalesce_key($params, 'confirm_text', '', FILTER_SANITIZE_STRING), + 'reset' => coalesce_key($params, 'reset', false, FILTER_VALIDATE_BOOLEAN), + 'params' => coalesce_key($params, 'params', array()) + ); + $default_params['id'] = coalesce_key($params, + 'html_id', + CmsResponse::make_dom_id($default_params['name']), + FILTER_SANITIZE_STRING + ); + + if ($check_keys && !are_all_keys_valid($params, $default_params)) + throw new CmsInvalidKeyException(invalid_key($params, $default_params)); + + //Combine EVERYTHING together into a big managerie + $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); + unset($params['params']); + + if ($reset) + { + $params['type'] = 'reset'; + } + else if ($params['image'] != '') + { + $params['type'] = 'image'; + $params['src'] = CmsConfig::get('root_url') . '/' . $params['image']; + } + else + { + $params['type'] = 'submit'; + } + unset($params['image']); + + $extra = ''; + if ($params['extra']) + { + $extra = $params['extra']; + if ($params['confirm_text'] != '') + { + $extra .= ' onclick="return confirm(\''.$params['confirm_text'].'\');"'; + } + } + unset($params['extra']); + unset($params['confirm_text']); + + return $this->create_start_tag('input', $params, true, $extra); + } + + /** + * Returns the xhtml equivalent of the opening of a select input. This is basically a nice little wrapper + * to make sure that id's are placed in names and also that it's xhtml compliant.\n + * Parameters: + * - 'name' - The name of the field. Defaults to 'input'. + * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. + * - 'html_id' - Id to use for the html id="". Defaults to an autogenerated value. + * - 'multiple' - Boolean of whether or not this is should show multiple items. Defaults to false. + * - 'size' - Number of items to show if multiple is set to true. Defaults to 3. + * - 'params' - An array of key/value pairs to add as attributes to the input tag. These will merge into any + * additional parameters you pass along in to the $params hash that aren't parsed by the function. + * + * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the + * tag and merged correctly with anything in the 'params' key if passed. + * @param boolean Test whether keys are all valid or not. Not helpful if you're + * passing extra key/values along, but good for debugging. + * @return string + * @author Ted Kulp + */ + public function create_input_select($params = array(), $check_keys = false) + { + $default_params = array( + 'name' => $this->id . coalesce_key($params, 'name', 'input', FILTER_SANITIZE_STRING), + 'extra' => coalesce_key($params, 'extra', ''), + 'multiple' => coalesce_key($params, 'multiple', false, FILTER_VALIDATE_BOOLEAN), + 'size' => coalesce_key($params, 'size', 3, FILTER_SANITIZE_NUMBER_INT), + 'params' => coalesce_key($params, 'params', array()) + ); + $default_params['id'] = coalesce_key($params, + 'html_id', + CmsResponse::make_dom_id($default_params['name']), + FILTER_SANITIZE_STRING + ); + + if ($check_keys && !are_all_keys_valid($params, $default_params)) + throw new CmsInvalidKeyException(invalid_key($params, $default_params)); + + //Combine EVERYTHING together into a big managerie + $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); + unset($params['params']); + + if ($params['multiple']) + { + $params['multiple'] = 'multiple'; + } + else + { + unset($params['multiple']); + unset($params['size']); + } + + $extra = ''; + if ($params['extra']) + { + $extra = $params['extra']; + } + unset($params['extra']); + + return $this->create_start_tag('select', $params, false, $extra); + } + + /** + * Returns the xhtml equivalent of options tags. This is basically a nice little wrapper + * to make sure that id's are placed in names and also that it's xhtml compliant.\n + * Parameters: + * - 'items' - An associative array of key/values to represent the value and text of the items in the list. This can also be + * passed a string in the form of 'key,value,key,value'. Defaults to array(). + * - 'selected_value' - A string that will set the matching item (by value) as selected. Defaults = ''. + * - 'selected_index' - An integer that will set the matching item (by index) as selected. Defaults to -1 (no selection). + * - 'selected_values' - An array of strings that will set the matching item as selected. This is for multiple select items. + * - 'extra' - Text to append to the <input>-statement, ex. for javascript-validation code. Defaults to ''. + * - 'flip_items' - Boolean that tells whether or not the value and text of the given items should be swapped. Defaults to false. + * + * @param array An array of parameters to pass to the method. Unrecognized parameters will be added as attributes to the + * tag and merged correctly with anything in the 'params' key if passed. + * @param boolean Test whether keys are all valid or not. Not helpful if you're + * passing extra key/values along, but good for debugging. + * @return string + * @author Ted Kulp + */ + public function create_input_options($params = array(), $check_keys = false) + { + $default_params = array( + 'items' => coalesce_key($params, 'items', array()), + 'selected_value' => coalesce_key($params, 'selected_value', '', FILTER_SANITIZE_STRING), + 'selected_index' => coalesce_key($params, 'selected_index', -1, FILTER_SANITIZE_NUMBER_INT), + 'selected_values' => coalesce_key($params, 'selected_value', array()), + 'flip_items' => coalesce_key($params, 'flip_items', false, FILTER_VALIDATE_BOOLEAN), + 'params' => coalesce_key($params, 'params', array()) + ); + + if ($check_keys && !are_all_keys_valid($params, $default_params)) + throw new CmsInvalidKeyException(invalid_key($params, $default_params)); + + //Combine EVERYTHING together into a big managerie + $params = array_merge($default_params, $this->strip_extra_params($params, $default_params, 'params')); + unset($params['params']); + + $selected_index = $params['selected_index']; unset($params['selected_index']); + $selected_value = $params['selected_value']; unset($params['selected_value']); + $selected_values = $params['selected_values']; unset($params['selected_values']); + + $items = $params['items']; + unset($params['items']); + if (!is_array($items) && strlen($items) > 0) + { + $ary = array_chunk(explode(',', $items), 2); + $items = array(); + foreach ($ary as $one_item) + { + if (count($one_item) == 2) + $items[$one_item[0]] = $one_item[1]; + } + } + + if ($params['flip_items']) + $items = array_flip($items); + unset($params['flip_items']); + + $text = ''; + + $count = 0; + foreach ($items as $k=>$v) + { + $hash = array('value' => $k); + if ($count == $selected_index || $k == $selected_value || in_array($k, $selected_values)) + { + $hash['selected'] = 'selected'; + } + $text .= $this->create_start_tag('option', $hash) . $v . $this->create_end_tag('option'); + $count++; + } + + return $text; + } +} + +class CmsInvalidKeyException extends Exception +{ + // Redefine the exception so message isn't optional + public function __construct($message = null, $code = 0) + { + if ($message != null) + $message = "Invalid Key: " . $message; + + parent::__construct($message, $code); + } +} + +# vim:ts=4 sw=4 noet +?> diff --git a/lib/cmsms/classes/class.cms_page_tree.php b/lib/cmsms/classes/class.cms_page_tree.php index f016679..fa34de0 100644 --- a/lib/cmsms/classes/class.cms_page_tree.php +++ b/lib/cmsms/classes/class.cms_page_tree.php @@ -1,176 +1,181 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** * Classes for storing the frontend page hierarchy. Includes methods to load * the structure from the database and properly return related Content objects. * * @author Ted Kulp * @since 2.0 **/ class CmsPageTree extends SilkTree { static public $content = array(); static private $instance = NULL; function __construct() { parent::__construct(); $this->root = new SilkNode(); $this->root->tree = $this; $this->load_child_nodes(); //Fill the base of the tree } static public function get_instance() { if (self::$instance == NULL) { self::$instance = new CmsPageTree(); } return self::$instance; } + function get_root() + { + return $this->root; + } + function getRootNode() { return $this->root; } public function load_child_nodes($parent_id = 1, $lft = -1, $rgt = -1) { $pages = array(); if ($lft == -1 && $rgt == -1) { $pages = orm('CmsPage')->find_all_by_parent_id($parent_id, array('order' => 'lft ASC')); } else { $pages = orm('CmsPage')->find_all(array('conditions' => array('lft > ? AND rgt < ?', $lft, $rgt), 'order' => 'lft ASC')); } //var_dump(count($pages)); //debug_print_backtrace(); foreach ($pages as $page) { $parent_node = $this->get_node_by_id($page->parent_id); if ($parent_node != null) { $parent_node->add_child($page); self::$content[(string)$page->id] = $page; //Put a reference up so we can quickly check to see if it's loaded already $parent_node->children_loaded = true; } } } public function load_parent_nodes($id) { //TODO: Optimize this more -- right now we're just making sure it works //First we find the page. If it exists, we then grab the great-great-grandparent //and load all of the nodes in between. $page = orm('CmsPage')->find_by_id($id); if ($page) { $ancestor = null; $top_nodes = $this->tree->get_root_node()->get_children(); foreach ($top_nodes as $one_node) { //Don't bother doing this if we're only level 2 if ($one_node->lft < $page->lft && $one_node->rgt > $page->rgt && $one_node->id != $page->id) { $ancestor = $one_node; break; } } if ($ancestor != null) { $this->load_child_nodes(1, $ancestor->lft, $ancestor->rgt); } } } public function get_node_by_id($id) { if ($id) { if ($id == 1) { return $this->get_root_node(); } else if (array_key_exists((string)$id, self::$content)) { return self::$content[(string)$id]; } else { $this->load_parent_nodes($id); return self::$content[(string)$id]; } } } function getNodeByID($id) { return $this->get_node_by_id($id); } function sureGetNodeByID($id) { return $this->get_node_by_id($id); } public function get_node_by_alias($alias) { $result = null; $id = SilkCache::get_instance()->call('CmsContentOperations::get_page_id_from_alias', $alias); if ($id) { $result = $this->get_node_by_id($id); } return $result; } function getNodeByAlias($alias) { return $this->get_node_by_alias($alias); } function sureGetNodeByAlias($alias) { return $this->get_node_by_alias($alias); } function get_node_by_hierarchy($position) { $result = null; $id = SilkCache::get_instance()->call('CmsContentOperations::get_page_id_from_hierarchy', $position); if ($id) { $result = $this->get_node_by_id($id); } return $result; } function getNodeByHierarchy($position) { return $this->get_node_by_hierarchy($position); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/plugins/function.cms_module.php b/lib/cmsms/plugins/function.cms_module.php index 24d229f..307c10d 100644 --- a/lib/cmsms/plugins/function.cms_module.php +++ b/lib/cmsms/plugins/function.cms_module.php @@ -1,34 +1,25 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function smarty_function_cms_module($params, &$smarty) { - $module_name = coalesce_key($params, 'module', ''); - $action = coalesce_key($params, 'action', 'default'); - if ($module_name != '') - { - $module = CmsModuleLoader::get_module_class($module_name); - if ($module) - { - return $module->do_action_base($action); - } - } + return CmsModuleBase::cms_module_plugin($params,$smarty); } # vim:ts=4 sw=4 noet ?> diff --git a/modules/MenuManager/MenuManager.info.xml b/modules/MenuManager/MenuManager.info.xml new file mode 100644 index 0000000..d83d41b --- /dev/null +++ b/modules/MenuManager/MenuManager.info.xml @@ -0,0 +1,13 @@ +<module_info> + <name>MenuManager</name> + <version>2.0</version> + <summary>Displays menus based on the CMSMS page structure.</summary> + <minimum_core_version>1.99</minimum_core_version> + <authors> + <author> + <name>Ted Kulp</name> + <email>[email protected]</email> + </author> + </authors> + <admin_interface>true</admin_interface> +</module_info> diff --git a/modules/MenuManager/MenuManager.module.php b/modules/MenuManager/MenuManager.module.php new file mode 100644 index 0000000..43ee7ee --- /dev/null +++ b/modules/MenuManager/MenuManager.module.php @@ -0,0 +1,178 @@ +<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- +#CMS - CMS Made Simple +#(c)2004-2009 by Ted Kulp ([email protected]) +#This project's homepage is: http://cmsmadesimple.org +# +#This program is free software; you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation; either version 2 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +#You should have received a copy of the GNU General Public License +#along with this program; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +#$Id$ + +class MenuManager extends CmsModuleBase +{ + function __construct() + { + parent::__construct(); + } + + function setup() + { + $this->register_module_plugin('menu_children', 'menu_children_plugin_callback'); + } + + public function menu_children_plugin_callback($params, &$smarty) + { + $orig_params = $smarty->get_template_vars('orig_params'); + $params = array_merge($orig_params, $params); + + if (!isset($params['node'])) + { + return; + } + + if ($params['node']->has_children()) + { + $this->current_depth++; + + //Handle number_of_levels param + if (!isset($params['number_of_levels']) || $params['number_of_levels'] > $this->current_depth) + { + //Handle collapse param + if (!isset($params['collapse']) || $params['collapse'] != true || starts_with(cmsms()->variables['position'] . '.', $params['node']->hierarchy . '.')) + { + $this->display_menu($params['node']->get_children(), $params, false); + } + } + + $this->current_depth--; + } + } + + public function display_menu(&$nodes, $params, $first_call = true) + { + $usefile = true; + //$lang = CmsMultiLanguage::get_client_language(); + $lang = 'en_US'; + $mdid = md5('12345'); //md5(cmsms()->variables['content_id'].implode('|', $params).$lang); + $tpl_name = coalesce_key($params, 'template', ''); + + if (!ends_with($tpl_name, '.tpl')) + { + $usefile = false; + } + + if (is_array($nodes)) + { + $count = 0; + + foreach ($nodes as &$node) + { + $this->add_fields_to_node($node); + $node->show = $this->should_show_node($node, $params); + + //Numeric Stuff + $node->first = ($count == 0); + $node->last = ($count + 1 == count($nodes)); + $node->index = $count; + + $count++; + } + + $smarty = smarty(); + $smarty->assign('count', count($nodes)); + $smarty->assign_by_ref('nodelist', $nodes); + + if ($first_call) + { + $smarty->assign('orig_params', $params); + $this->current_depth = 1; + } + + //echo $this->process_template_from_database($id, $return_id, 'menu_template', $tpl_name); + echo $this->process_template_from_data($this->get_default_template()); + } + } + + public function add_fields_to_node(&$node) + { + $node->url = $node->get_url(true, $lang); + $node->menutext = $node->get_property_value('menu_text', $lang); + $node->haschildren = $node->has_children(); + $node->target = ''; + if ($node->has_property('target')) + $node->target = $node->get_property_value('target'); + $node->depth = $this->current_depth; + } + + public function should_show_node(&$node, $params) + { + $include = true; + $exclude = false; + + if (isset($params['includeprefix'])) + { + $include = false; + $prefixes = explode(',', $params['includeprefix']); + foreach ($prefixes as $oneprefix) + { + if (starts_with(strtolower($node->alias), strtolower($oneprefix))) + { + $include = true; + break; + } + } + } + + if (isset($params['excludeprefix'])) + { + $prefixes = explode(',', $params['excludeprefix']); + foreach ($prefixes as $oneprefix) + { + if (starts_with(strtolower($node->alias), strtolower($oneprefix))) + { + $exclude = true; + break; + } + } + } + + $should_show = $node->active && $node->show_in_menu && ($include && !$exclude); + + //Override is show_all is true + if (isset($params['show_all']) && $params['show_all']) + $should_show = true; + + return $should_show; + } + + function get_default_template() + { + return '[[if $count > 0]] +<ul> + [[foreach from=$nodelist item=node]] + [[if $node->show]] + <li> + <a href="[[$node->url]]">[[$node->menutext]]</a> + [[menu_children node=$node]] + </li> + [[/if]] + [[/foreach]] +</ul> +[[/if]] +'; + } + +} + +# vim:ts=4 sw=4 noet +?> \ No newline at end of file diff --git a/modules/MenuManager/action.default.php b/modules/MenuManager/action.default.php new file mode 100644 index 0000000..ae1309f --- /dev/null +++ b/modules/MenuManager/action.default.php @@ -0,0 +1,93 @@ +<?php +SilkProfiler::get_instance()->mark('Start of Menu Manager Display'); + +$root_node = null; + +if (isset($params['start_page']) || isset($params['start_element'])) +{ + $tree = CmsPageTree::get_instance(); + $root_node = null; + + if (isset($params['start_page'])) + { + $root_node = $tree->get_node_by_alias($params['start_page']); + } + else + { + $root_node = $tree->get_node_by_hierarchy($params['start_element']); + } + + if ($root_node != null) + { + if (isset($params['show_root_siblings']) && $params['show_root_siblings']) + { + $parent_node = $root_node->get_parent(); + if ($parent_node != null) + { + $this->display_menu($parent_node->get_children(), $params); + } + } + else if (isset($params['show_only_children']) && $params['show_only_children']) + { + $this->display_menu($root_node->get_children(), $params); + } + else + { + //Hack alert! + //Make an array of one and pass that + $ary = array($root_node); + $this->display_menu($ary, $params); + } + } +} +else if (isset($params['start_level']) && $params['start_level'] > 1) +{ + $tree = CmsPageTree::get_instance(); + $curnode = $tree->get_node_by_id(cmsms()->variables['content_id']); + if ($curnode != null) + { + $ids = explode('.', $curnode->id_hierarchy()); + if (count($ids) >= $params['start_level'] - 2) + { + $parent_node = $tree->get_node_by_id($ids[$params['start_level'] - 2]); + if ($parent_node != null && $parent_node->has_children()) + { + $this->display_menu($parent_node->get_children(), $params); + } + } + } +} +else if (isset($params['items'])) +{ + $result = array(); + + $tree = CmsPageTree::get_instance(); + $items = explode(',', $params['items']); + + if ($tree != null && count($items) > 0) + { + foreach ($items as $oneitem) + { + $curnode = $tree->get_node_by_alias(trim($oneitem)); + if ($curnode) + { + $result[] = $curnode; + } + } + } + + if (count($result) > 0) + { + $params['number_of_levels'] = 1; + + $this->display_menu($result, $params); + } +} +else +{ + $this->display_menu(CmsPageTree::get_instance()->get_root_node()->get_children(), $params); +} + +SilkProfiler::get_instance()->mark('End of Menu Manager Display'); + +?> \ No newline at end of file
tedkulp/cmsms-nouveau
40130b6d814b9ac8e9304f748c58ff773ee0639d
Lots of catch up commits
diff --git a/components/admin/controllers/class.page_controller.php b/components/admin/controllers/class.page_controller.php index 5a622d4..56b5adb 100644 --- a/components/admin/controllers/class.page_controller.php +++ b/components/admin/controllers/class.page_controller.php @@ -1,85 +1,135 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class PageController extends AdminController { function index($params) { $this->set('tree', CmsPageTree::get_instance()); } function main_content($params) { $page_id = substr($params['node_id'], 5); $page = orm('CmsPage')->find_by_id($page_id); $this->set('page', $page); $ajax = new SilkAjax(); $ajax->replace_html('#main_section', $this->render_partial('main_section.tpl')); $ajax->script('reset_main_content();'); return $ajax->get_result(); } + function update_content($params) + { + $ajax = new SilkAjax(); + $content = new $params['value']; + $target_id = str_replace('select_', '', $params['parent_id']); + $ajax->replace_html('#' . $target_id, $content->get_edit_form()); + $ajax->script('setup_content();'); + return $ajax->get_result(); + } + + function update_page($params) + { + $page = orm('CmsPage')->load($params['page']); + $ajax = new SilkAjax(); + if ($page) + { + $page->update_parameters($params['page']); + } + $this->set('page', $page); + $ajax->replace_html('#main_section', $this->render_partial('main_section.tpl')); + $ajax->script('reset_main_content();'); + return $ajax->get_result(); + } + function check_unique_alias($params) { $ajax = new SilkAjax(); $count = orm('CmsPage')->find_count(array('conditions' => array('unique_alias = ? AND id != ?', $params['alias'], $params['page_id']))); if ($params['alias'] == '') { $ajax->replace_html('#unique_alias_ok', 'Empty'); $ajax->script('$("#unique_alias_ok").attr("style", "color: red;")'); } else if ($count > 0 || $params['alias'] == '') { $ajax->replace_html('#unique_alias_ok', 'Used'); $ajax->script('$("#unique_alias_ok").attr("style", "color: red;")'); } else { $ajax->replace_html('#unique_alias_ok', 'Ok'); $ajax->script('$("#unique_alias_ok").attr("style", "color: green;")'); } $ajax->script('reset_main_content();'); return $ajax->get_result(); } function check_alias($params) { $ajax = new SilkAjax(); $count = orm('CmsPage')->find_count(array('conditions' => array('alias = ? AND id != ?', $params['alias'], $params['page_id']))); if ($params['alias'] == '') { $ajax->replace_html('#alias_ok', 'Empty'); $ajax->script('$("#alias_ok").attr("style", "color: red;")'); } else if ($count > 0 || $params['alias'] == '') { $ajax->replace_html('#alias_ok', 'Used'); $ajax->script('$("#alias_ok").attr("style", "color: red;")'); } else { $ajax->replace_html('#alias_ok', 'Ok'); $ajax->script('$("#alias_ok").attr("style", "color: green;")'); } $ajax->script('reset_main_content();'); return $ajax->get_result(); } + + function save($params) + { + $ajax = new SilkAjax(); + + if (isset($params['save']) || isset($params['apply'])) + { + $page = orm('CmsPage')->load($params['page']); + if ($page) + { + $page->update_parameters($params['page']); + if ($page->save()) + { + $ajax->show('.pagemcontainer'); + $ajax->replace_html('#pagemessage', 'Page Saved'); + $ajax->script('$(".pagemcontainer").fadeOut(2000)'); + return $ajax->get_result(); + } + } + + $ajax->show('.pagemcontainer'); + $ajax->replace_html('#pagemessage', 'Error Saving Page'); + $ajax->script('$(".pagemcontainer").fadeOut(2000)'); + } + return $ajax->get_result(); + } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/helpers/class.page_helper.php b/components/admin/helpers/class.page_helper.php index 6984c88..a97eb4b 100644 --- a/components/admin/helpers/class.page_helper.php +++ b/components/admin/helpers/class.page_helper.php @@ -1,33 +1,41 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class PageHelper extends SilkHelperBase { function page_template_dropdown_options($params, &$smarty) { $opt = array(); foreach (orm('CmsTemplate')->find_all_by_active(true) as $tpl) { $opt[$tpl->id] = $tpl->name; } return forms()->create_input_options(array('items' => $opt, 'selected_value' => $params['selected'])); } + + function content_type_dropdown_options($params, &$smarty) + { + $opt = array(); + $opt['CmsHtmlContent'] = 'HTML Content'; + $opt['CmsOtherContent'] = 'Other Content'; + return forms()->create_input_options(array('items' => $opt, 'selected_value' => $params['selected'])); + } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/views/login/index.tpl b/components/admin/views/login/index.tpl index 5586aa7..90704c4 100644 --- a/components/admin/views/login/index.tpl +++ b/components/admin/views/login/index.tpl @@ -1,19 +1,19 @@ -{validation_errors for=$user_session} +[[validation_errors for=$user_session]] -{form} +[[form]] -<div id="regular" {if $params.login.openid ne '' or $smarty.request.openid_mode ne ''}style="display: none;"{/if}> -{label for="login[username]"}Username:{/label}{textbox name="login[username]" value=$params.login.username}<br /> -{label for="login[password]"}Password:{/label}{password name="login[password]" value=$params.login.password}<br /> +<div id="regular" [[if $params.login.openid ne '' or $smarty.request.openid_mode ne '']]style="display: none;"[[/if]]> +[[label for="login[username]"]]Username:[[/label]][[textbox name="login[username]" value=$params.login.username]]<br /> +[[label for="login[password]"]]Password:[[/label]][[password name="login[password]" value=$params.login.password]]<br /> <a href="#" onclick="$('#regular').hide();$('#openid').show();return false;">Use OpenID</a> </div> -<div id="openid" {if $params.login.openid eq '' and $smarty.request.openid_mode eq ''}style="display: none;"{/if}> -{label for="login[openid]"}Open ID:{/label}{textbox name="login[openid]" value=$params.login.openid}<br /> +<div id="openid" [[if $params.login.openid eq '' and $smarty.request.openid_mode eq '']]style="display: none;"[[/if]]> +[[label for="login[openid]"]]Open ID:[[/label]][[textbox name="login[openid]" value=$params.login.openid]]<br /> <a href="#" onclick="$('#regular').show();$('#openid').hide();return false;">Use Username/Password</a> </div> -{submit value="Submit"} +[[submit value="Submit"]] -{/form} \ No newline at end of file +[[/form]] \ No newline at end of file diff --git a/components/admin/views/page/branch.tpl b/components/admin/views/page/branch.tpl index 28778b4..f468e61 100644 --- a/components/admin/views/page/branch.tpl +++ b/components/admin/views/page/branch.tpl @@ -1,11 +1,11 @@ -{foreach from=$subpages item='page'} +[[foreach from=$subpages item='page']] <ul> - <li id="node_{$page->id}"> - <a href="#">{$page->alias}</a> - {if $page->has_children()} - {assign var='subpages' value=$page->get_children()} - {render_partial template='branch.tpl'} - {/if} + <li id="node_[[$page->id]]"> + <a href="#">[[$page->alias]]</a> + [[if $page->has_children()]] + [[assign var='subpages' value=$page->get_children()]] + [[render_partial template='branch.tpl']] + [[/if]] </li> </ul> -{/foreach} \ No newline at end of file +[[/foreach]] \ No newline at end of file diff --git a/components/admin/views/page/content.tpl b/components/admin/views/page/content.tpl index b2d9491..6c37858 100644 --- a/components/admin/views/page/content.tpl +++ b/components/admin/views/page/content.tpl @@ -1,4 +1,12 @@ -{foreach from=$page->template->get_page_blocks() key='name' item='block'} - <h3>{$name}</h3> - <h4>{$block.type}</h4> -{/foreach} +[[if $page->template]] + [[foreach from=$page->template->get_page_blocks() key='name' item='block' name='foo']] + [[assign var=block_obj value=$page->get_content_block($name, true)]] + [[if $block_obj]] + <h3>[[$name]]</h3> + <label>Content Type:</label> [[select class='content_type_picker' html_id="block_select_`$smarty.foreach.foo.index`" name="block_type[$name]"]][[content_type_dropdown_options selected=$block_obj.type]][[/select]]<br /> + <div id="block_[[$smarty.foreach.foo.index]]"> + [[$block_obj->get_edit_form($name)]] + </div> + [[/if]] + [[/foreach]] +[[/if]] diff --git a/components/admin/views/page/index.tpl b/components/admin/views/page/index.tpl index c71a4f2..3cb2eb0 100644 --- a/components/admin/views/page/index.tpl +++ b/components/admin/views/page/index.tpl @@ -1,81 +1,95 @@ -{assign var='page' value=$tree->get_root_node()} +[[assign var='page' value=$tree->get_root_node()]] <h2>Content</h2> <div style="width: 1000px; margin-top: 15px;"> <div id="content_tree" style="width: 240px; float: left; border-right: 1px solid black"> <ul> <li id="node_1" class="open"> <a href="#">ROOT</a> - {if $page->has_children()} - {assign var='subpages' value=$page->get_children()} - {render_partial template='branch.tpl'} - {/if} + [[if $page->has_children()]] + [[assign var='subpages' value=$page->get_children()]] + [[render_partial template='branch.tpl']] + [[/if]] </li> </ul> </div> <div id="main_section" style="float: right; min-width: 750px; text-align: left;"> </div> </div> <br style="clear: both;" /> -{literal} <script type="text/javascript"> //<![CDATA[ $('#content_tree').tree( { 'rules' : { 'draggable' : 'all' }, 'callback' : { 'onselect' : function(node, tree_obj) { if (node.id != 'node_1') { - silk_ajax_call('{/literal}{php}echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'main_content')){/php}{literal}', [{name:'node_id', value:node.id}]); + silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'main_content'))[[/php]]', [{name:'node_id', value:node.id}]); } else { clear_main_content(); } }, 'ondeselect' : function(node, tree_obj) { clear_main_content(); } } } ); function clear_main_content() { $('#main_section').html(''); } function reset_main_content() { $('#module_page_tabs > ul').tabs(); setup_form(); $('#unique_alias').delayedObserver(function() { - silk_ajax_call('{/literal}{php}echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_unique_alias')){/php}{literal}', [{name:'alias', value:$('#unique_alias').val()}, {name:'page_id', value:$('#page_id').html()}]); + silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_unique_alias'))[[/php]]', [{name:'alias', value:$('#unique_alias').val()}, {name:'page_id', value:$('#page_id').html()}]); }, 0.5); $('#alias').delayedObserver(function() { - silk_ajax_call('{/literal}{php}echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_alias')){/php}{literal}', [{name:'alias', value:$('#alias').val()}, {name:'page_id', value:$('#page_id').html()}]); + silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'check_alias'))[[/php]]', [{name:'alias', value:$('#alias').val()}, {name:'page_id', value:$('#page_id').html()}]); }, 0.5); + $('#page_template_id').delayedObserver(function() + { + silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'update_page'))[[/php]]', $('#form_save').serializeArray()); + }, 0.5, { event: 'change'}); + setup_content(); + } + + function setup_content() + { + $('.content_type_picker').each(function() + { + $(this).delayedObserver(function() + { + silk_ajax_call('[[php]]echo SilkResponse::create_url(array('controller' => 'page', 'action' => 'update_content'))[[/php]]', [{name:'parent_id', value:$(this).attr('id')}, {name:'name', value:$(this).attr('name')}, {name:'value', value:$(this).val()}]); + }, 0.5, { event: 'change'}); + }); } $(document).ready(function() { reset_main_content(); }); //]]></script> -{/literal} diff --git a/components/admin/views/page/info.tpl b/components/admin/views/page/info.tpl index 5e0660b..e55263c 100644 --- a/components/admin/views/page/info.tpl +++ b/components/admin/views/page/info.tpl @@ -1,8 +1,8 @@ -<label>Id:</label> <span id="page_id">{$page.id}</span><br /> -<label>Page Name:</label> {textbox name='page_name' value='Page 1'}<br /> -<label>Menu Text:</label> {textbox name='menu_text' value='Page 1'}<br /> -<label>Page Template:</label> {select name='page_template'}{page_template_dropdown_options selected=$page.template_id}{/select}<br /> +<label>Id:</label> <span id="page_id">[[$page.id]]</span><br /> +<label>Page Name:</label> [[textbox name='page[page_name]' value=$page.page_name]]<br /> +<label>Menu Text:</label> [[textbox name='page[menu_text]' value=$page.menu_text]]<br /> +<label>Page Template:</label> [[select name='page[template_id]']][[page_template_dropdown_options selected=$page.template_id]][[/select]]<br /> <label>Active:</label> <span><a href="#">True</a></span><br /> <label>Show In Menu:</label> <span><a href="#">True</a></span><br /> -<label>Path to Page:</label> /{textbox html_id='alias' name='alias' autocomplete="off" value=$page.alias}&nbsp;&nbsp;<span id="alias_ok" style="color: green;">Ok</span><br /> -<label>Unique Alias:</label> {textbox html_id='unique_alias' name='unqiue_alias' autocomplete="off" value=$page.unique_alias}&nbsp;&nbsp;<span id="unique_alias_ok" style="color: green;">Ok</span><br /> +<label>Path to Page:</label> /[[textbox html_id='alias' name='page[alias]' autocomplete="off" value=$page.alias]]&nbsp;&nbsp;<span id="alias_ok" style="color: green;">Ok</span><br /> +<label>Unique Alias:</label> [[textbox html_id='unique_alias' name='page[unique_alias]' autocomplete="off" value=$page.unique_alias]]&nbsp;&nbsp;<span id="unique_alias_ok" style="color: green;">Ok</span><br /> diff --git a/components/admin/views/page/main_section.tpl b/components/admin/views/page/main_section.tpl index e26025a..3308a35 100644 --- a/components/admin/views/page/main_section.tpl +++ b/components/admin/views/page/main_section.tpl @@ -1,28 +1,30 @@ -{form} +[[form action="save" controller="page"]] <div id="module_page_tabs"> <ul> <li><a href="#info"><span>Information</span></a></li> <li><a href="#edit"><span>Content</span></a></li> <li><a href="#attributes"><span>Attributes</span></a></li> <li><a href="#metadata"><span>Metadata</span></a></li> <li><a href="#preview"><span>Preview</span></a></li> </ul> <div id="info"> - {render_partial template="info.tpl"} + [[render_partial template="info.tpl"]] </div> <div id="edit"> - {render_partial template="content.tpl"} + [[render_partial template="content.tpl"]] </div> <div id="attributes"> </div> <div id="metadata"> </div> <div id="preview"> </div> </div> <br /> + + [[hidden name='page[id]' value=$page.id]] - {submit value="Save"} {submit name="cancel" value="Cancel"} {submit value="Apply"} + [[submit name="save" value="Save" remote="true" action="save" controller="page"]] [[submit name="cancel" value="Cancel" onclick="clear_main_content(); return false;"]] [[submit name="apply" value="Apply" remote="true" action="save" controller="page"]] -{/form} \ No newline at end of file +[[/form]] \ No newline at end of file diff --git a/components/admin/views/page_template/add.tpl b/components/admin/views/page_template/add.tpl index dfee3af..e560fe6 100644 --- a/components/admin/views/page_template/add.tpl +++ b/components/admin/views/page_template/add.tpl @@ -1 +1 @@ -{render_partial template='editform.tpl'} +[[render_partial template='editform.tpl']] diff --git a/components/admin/views/page_template/edit.tpl b/components/admin/views/page_template/edit.tpl index dfee3af..e560fe6 100644 --- a/components/admin/views/page_template/edit.tpl +++ b/components/admin/views/page_template/edit.tpl @@ -1 +1 @@ -{render_partial template='editform.tpl'} +[[render_partial template='editform.tpl']] diff --git a/components/admin/views/page_template/editform.tpl b/components/admin/views/page_template/editform.tpl index 2bb101b..5a6cbe5 100644 --- a/components/admin/views/page_template/editform.tpl +++ b/components/admin/views/page_template/editform.tpl @@ -1,10 +1,10 @@ -{cms_validation_errors for=$template} +[[cms_validation_errors for=$template]] -{form} +[[form]] -{label for='template[name]'}Name{/label}: {textbox name='template[name]' value=$template.name}<br /> -{label for='template[name]'}Content{/label}: {textarea name='template[content]' value=$template.content cols='80' rows='10'}<br /> -{label for='template[active]'}Active{/label}: {checkbox name='template[active]' checked=$template.active}<br /> -{hidden name='template[id]' value=$template.id}{submit name='submit' value="Submit"}{submit name='cancel' value="Cancel"}{submit name='apply' value="Apply" remote="true"} +[[label for='template[name]']]Name[[/label]]: [[textbox name='template[name]' value=$template.name]]<br /> +[[label for='template[name]']]Content[[/label]]: [[textarea name='template[content]' value=$template.content cols='80' rows='10']]<br /> +[[label for='template[active]']]Active[[/label]]: [[checkbox name='template[active]' checked=$template.active]]<br /> +[[hidden name='template[id]' value=$template.id]][[submit name='submit' value="Submit"]][[submit name='cancel' value="Cancel"]][[submit name='apply' value="Apply" remote="true"]] -{/form} \ No newline at end of file +[[/form]] \ No newline at end of file diff --git a/components/admin/views/page_template/index.tpl b/components/admin/views/page_template/index.tpl index 7271f23..8bd09b6 100644 --- a/components/admin/views/page_template/index.tpl +++ b/components/admin/views/page_template/index.tpl @@ -1,36 +1,36 @@ <div class="pageoverflow"> <div class="pageheader">Page Templates <span class="helptext"> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Templates" rel="external"> - <img src="{$layout_root_url}/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> + <img src="[[$layout_root_url]]/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> </a> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Templates" rel="external">Help</a> (new window) </span> </div> </div> <table cellspacing="0" class="pagetable"> <thead> <tr> <th class="pagew50">Template</th> <th class="pagepos">Default</th> <th class="pagepos">Active</th> <th class="pageicon">&nbsp;</th> <th class="pageicon">&nbsp;</th> </tr> </thead> <tbody id="tablebody"> - {render_partial template='indextablebody.tpl'} + [[render_partial template='indextablebody.tpl']] </tbody> </table> <div class="pageoptions"> <p class="pageoptions"> <span style="float: left;"> - <a href="{link only_href='true' controller='page_template' action='add'}"><img src="{$layout_root_url}/images/icons/system/newobject.gif" class="systemicon" alt="Add New Template" title="Add New Template" /></a> - {link html_class="pageoptions" text="Add Template" controller="page_template" action="add"} + <a href="[[link only_href='true' controller='page_template' action='add']]"><img src="[[$layout_root_url]]/images/icons/system/newobject.gif" class="systemicon" alt="Add New Template" title="Add New Template" /></a> + [[link html_class="pageoptions" text="Add Template" controller="page_template" action="add"]] </span> </p> </div> <br /> diff --git a/components/admin/views/page_template/indextablebody.tpl b/components/admin/views/page_template/indextablebody.tpl index 6bd6af1..c367fcf 100644 --- a/components/admin/views/page_template/indextablebody.tpl +++ b/components/admin/views/page_template/indextablebody.tpl @@ -1,9 +1,9 @@ -{foreach from=$templates item='template'} -<tr class="{cycle values='row1,row2'}"> - <td>{link text=$template.name controller='page_template' action='edit' id=$template.id}</td> - <td class="pagepos">{if $template.default}{img src="images/icons/system/true.gif" alt="True" title="True"}{else}{img src="images/icons/system/false.gif" title="False" alt="False"}{/if}</td> - <td class="pagepos">{if $template.active}{img src="images/icons/system/true.gif" alt="True" title="True"}{else}{img src="images/icons/system/false.gif" alt="False" title="False"}{/if}</td> - <td class="icons_wide">{img_link src="images/icons/system/edit.gif" alt="Edit" title="Edit" controller='page_template' action='edit' id=$template.id}</td> - <td class="icons_wide">{img_link src="images/icons/system/delete.gif" alt="Delete" title="Delete" controller='page_template' action='delete' id=$template.id confirm_text='Are you sure you want to delete?'}</td> +[[foreach from=$templates item='template']] +<tr class="[[cycle values='row1,row2']]"> + <td>[[link text=$template.name controller='page_template' action='edit' id=$template.id]]</td> + <td class="pagepos">[[if $template.default]][[img src="images/icons/system/true.gif" alt="True" title="True"]][[else]][[img src="images/icons/system/false.gif" title="False" alt="False"]][[/if]]</td> + <td class="pagepos">[[if $template.active]][[img src="images/icons/system/true.gif" alt="True" title="True"]][[else]][[img src="images/icons/system/false.gif" alt="False" title="False"]][[/if]]</td> + <td class="icons_wide">[[img_link src="images/icons/system/edit.gif" alt="Edit" title="Edit" controller='page_template' action='edit' id=$template.id]]</td> + <td class="icons_wide">[[img_link src="images/icons/system/delete.gif" alt="Delete" title="Delete" controller='page_template' action='delete' id=$template.id confirm_text='Are you sure you want to delete?']]</td> </tr> -{/foreach} \ No newline at end of file +[[/foreach]] \ No newline at end of file diff --git a/components/admin/views/stylesheet/add.tpl b/components/admin/views/stylesheet/add.tpl index ea66c56..23dfe61 100644 --- a/components/admin/views/stylesheet/add.tpl +++ b/components/admin/views/stylesheet/add.tpl @@ -1,10 +1,10 @@ -{validation_errors for=$stylesheet} +[[validation_errors for=$stylesheet]] -{form} +[[form]] -{label for='stylesheet[name]'}Name{/label}: {textbox name='stylesheet[name]' value=$stylesheet.name}<br /> -{label for='stylesheet[value]'}Content{/label}: {textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10'}<br /> -{label for='stylesheet[active]'}Active{/label}: {checkbox name='stylesheet[active]' checked=$stylesheet.active}<br /> -{submit name='submit' value="Submit"}{submit name='cancel' value="Cancel"} +[[label for='stylesheet[name]']]Name[[/label]]: [[textbox name='stylesheet[name]' value=$stylesheet.name]]<br /> +[[label for='stylesheet[value]']]Content[[/label]]: [[textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10']]<br /> +[[label for='stylesheet[active]']]Active[[/label]]: [[checkbox name='stylesheet[active]' checked=$stylesheet.active]]<br /> +[[submit name='submit' value="Submit"]][[submit name='cancel' value="Cancel"]] -{/form} \ No newline at end of file +[[/form]] \ No newline at end of file diff --git a/components/admin/views/stylesheet/edit.tpl b/components/admin/views/stylesheet/edit.tpl index cab4704..6d04f7e 100644 --- a/components/admin/views/stylesheet/edit.tpl +++ b/components/admin/views/stylesheet/edit.tpl @@ -1,10 +1,10 @@ -{validation_errors for=$stylesheet} +[[validation_errors for=$stylesheet} -{form} +[[form} -{label for='stylesheet[name]'}Name{/label}: {textbox name='stylesheet[name]' value=$stylesheet.name}<br /> -{label for='stylesheet[value]'}Content{/label}: {textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10'}<br /> -{label for='stylesheet[active]'}Active{/label}: {checkbox name='stylesheet[active]' checked=$stylesheet.active}<br /> -{hidden name='stylesheet[id]' value=$stylesheet.id}{submit name='submit' value="Submit"}{submit name='cancel' value="Cancel"} +[[label for='stylesheet[name]'}Name[[/label}: [[textbox name='stylesheet[name]' value=$stylesheet.name}<br /> +[[label for='stylesheet[value]'}Content[[/label}: [[textarea name='stylesheet[value]' value=$stylesheet.value cols='80' rows='10'}<br /> +[[label for='stylesheet[active]'}Active[[/label}: [[checkbox name='stylesheet[active]' checked=$stylesheet.active}<br /> +[[hidden name='stylesheet[id]' value=$stylesheet.id}[[submit name='submit' value="Submit"}[[submit name='cancel' value="Cancel"} -{/form} \ No newline at end of file +[[/form} \ No newline at end of file diff --git a/components/admin/views/stylesheet/index.tpl b/components/admin/views/stylesheet/index.tpl index 3419989..5fc9c76 100644 --- a/components/admin/views/stylesheet/index.tpl +++ b/components/admin/views/stylesheet/index.tpl @@ -1,35 +1,35 @@ <div class="pageoverflow"> <div class="pageheader">Stylesheets <span class="helptext"> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Stylesheets" rel="external"> - <img src="{$layout_root_url}/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> + <img src="[[$layout_root_url]]/images/icons/system/info-external.gif" class="systemicon" alt="Help" title="Help" /> </a> <a href="http://wiki.cmsmadesimple.org/index.php/User_Handbook/Admin_Panel/Layout/Stylesheets" rel="external">Help</a> (new window) </span> </div> </div> <table cellspacing="0" class="pagetable"> <thead> <tr> <th class="pagew50">Template</th> <th class="pagepos">Active</th> <th class="pageicon">&nbsp;</th> <th class="pageicon">&nbsp;</th> </tr> </thead> <tbody id="tablebody"> - {render_partial template='indextablebody.tpl'} + [[render_partial template='indextablebody.tpl']] </tbody> </table> <div class="pageoptions"> <p class="pageoptions"> <span style="float: left;"> - <a href="{link only_href='true' controller='stylesheet' action='add'}"><img src="{$layout_root_url}/images/icons/system/newobject.gif" class="systemicon" alt="Add Stylesheet" title="Add Stylesheet" /></a> - {link html_class="pageoptions" text="Add Stylesheet" controller="stylesheet" action="add"} + <a href="[[link only_href='true' controller='stylesheet' action='add']]"><img src="[[$layout_root_url]]/images/icons/system/newobject.gif" class="systemicon" alt="Add Stylesheet" title="Add Stylesheet" /></a> + [[link html_class="pageoptions" text="Add Stylesheet" controller="stylesheet" action="add"]] </span> </p> </div> <br /> diff --git a/components/admin/views/stylesheet/indextablebody.tpl b/components/admin/views/stylesheet/indextablebody.tpl index 248a252..ec22f52 100644 --- a/components/admin/views/stylesheet/indextablebody.tpl +++ b/components/admin/views/stylesheet/indextablebody.tpl @@ -1,8 +1,8 @@ -{foreach from=$stylesheets item='stylesheet'} -<tr class="{cycle values='row1,row2'}"> - <td>{link text=$stylesheet.name controller='stylesheet' action='edit' id=$stylesheet.id}</td> - <td class="pagepos">{if $stylesheet.active}{img src="images/icons/system/true.gif" alt="True" title="True"}{else}{img src="images/icons/system/false.gif" alt="False" title="False"}{/if}</td> - <td class="icons_wide">{img_link src="images/icons/system/edit.gif" alt="Edit" title="Edit" controller='stylesheet' action='edit' id=$stylesheet.id}</td> - <td class="icons_wide">{img_link src="images/icons/system/delete.gif" alt="Delete" title="Delete" controller='stylesheet' action='delete' id=$stylesheet.id confirm_text='Are you sure you want to delete?'}</td> +[[foreach from=$stylesheets item='stylesheet']] +<tr class="[[cycle values='row1,row2']]"> + <td>[[link text=$stylesheet.name controller='stylesheet' action='edit' id=$stylesheet.id]]</td> + <td class="pagepos">[[if $stylesheet.active]][[img src="images/icons/system/true.gif" alt="True" title="True"]][[else]][[img src="images/icons/system/false.gif" alt="False" title="False"]][[/if]]</td> + <td class="icons_wide">[[img_link src="images/icons/system/edit.gif" alt="Edit" title="Edit" controller='stylesheet' action='edit' id=$stylesheet.id]]</td> + <td class="icons_wide">[[img_link src="images/icons/system/delete.gif" alt="Delete" title="Delete" controller='stylesheet' action='delete' id=$stylesheet.id confirm_text='Are you sure you want to delete?']]</td> </tr> -{/foreach} +[[/foreach]] diff --git a/layouts/themes/default/login.tpl b/layouts/themes/default/login.tpl index cfa8196..22bef7a 100644 --- a/layouts/themes/default/login.tpl +++ b/layouts/themes/default/login.tpl @@ -1,63 +1,63 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>CMS Login</title> <link rel="stylesheet" type="text/css" media="screen, projection" href="themes/default/css/style.css" /> -<base href="{$base_url}" /> +<base href="[[$base_url]]" /> </head> <body> <div class="login-all clear"> <div class="info"> - <h1>{tr}Information{/tr}</h1> + <h1>[[tr]]Information[[/tr]]</h1> <div class="centerLogin"> - <p id="img">{tr}From this point should take into consideration the following parameters:{/tr}:</p> -{tr}<ol> + <p id="img">[[tr]]From this point should take into consideration the following parameters:[[/tr]]:</p> +[[tr]]<ol> <li>Cookies enabled in your browser</li> <li>Javascript enabled in your browser </li> <li>Windows popup active to the following address:</li> -</ol>{/tr} -<span>( {$smarty.server.SERVER_NAME} +</ol>[[/tr]] +<span>( [[$smarty.server.SERVER_NAME]] )</span> </div> </div> <div class="login"> -<div class="top">{tr}logintitle{/tr}</div> +<div class="top">[[tr]]logintitle[[/tr]]</div> <div id="centerLogin" class="formcontainer"> - {$debug_buffer} - {if !empty($error)} - <div class="erroLogin">{$error}</div > - {/if} + [[$debug_buffer]] + [[if !empty($error)]] + <div class="erroLogin">[[$error]]</div > + [[/if]] <div class="lbfieldstext"> - <p class="lbuser">{tr}username{/tr}:</p> - <p class="lbpass">{tr}password{/tr}:</p> - <p class="lbopenid">{tr}openid{/tr}:</p> + <p class="lbuser">[[tr]]username[[/tr]]:</p> + <p class="lbpass">[[tr]]password[[/tr]]:</p> + <p class="lbopenid">[[tr]]openid[[/tr]]:</p> </div> <div class="login-fields"> <form method="post" action="login.php"> <p> - <input id="lbusername" name="username" class="defaultfocus" type="text" size="15" value="{$username}" /><br /> - {if !empty($error)} + <input id="lbusername" name="username" class="defaultfocus" type="text" size="15" value="[[$username]]" /><br /> + [[if !empty($error)]] <input id="lbpassword" class="defaultfocus" name="password" type="password" size="15" /><br /> - {else} + [[else]] <input id="lbpassword" name="password" type="password" size="15" /><br /> - {/if} - <input name="openid" id="openid" type="text" size="15" value="{$openid}" /><br /><br /> - {html_submit name="loginsubmit" name="loginsubmit" value=$submit_text} - {html_submit name="logincancel" name="logincancel" value=$cancel_text} + [[/if]] + <input name="openid" id="openid" type="text" size="15" value="[[$openid]]" /><br /><br /> + [[html_submit name="loginsubmit" name="loginsubmit" value=$submit_text]] + [[html_submit name="logincancel" name="logincancel" value=$cancel_text]] </p> </form> </div> </div> </div> </div> <div class="login-footer"></div> <div id="copy"> &copy; <a rel="external" href="http://www.cmsmadesimple.org" >CMS Made Simple</a> <br /> Is free software released under the General Public Licence.</div> </body> </html> diff --git a/layouts/themes/default/main.tpl b/layouts/themes/default/main.tpl index 227c358..a20e872 100644 --- a/layouts/themes/default/main.tpl +++ b/layouts/themes/default/main.tpl @@ -1,118 +1,115 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="Generator" content="CMS Made Simple - Copyright (C) 2004-2009 Ted Kulp. All rights reserved." /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> - <title>{$sitename} - {$title}</title> + <title>[[$sitename]] - [[$title]]</title> - <link rel="stylesheet" href="{$layout_root_url}/css/kevin_tabs.css" type="text/css" /> - <link rel="stylesheet" href="{$layout_root_url}/css/style.css" type="text/css" /> + <link rel="stylesheet" href="[[$layout_root_url]]/css/kevin_tabs.css" type="text/css" /> + <link rel="stylesheet" href="[[$layout_root_url]]/css/style.css" type="text/css" /> <!--[if IE]> - <script type="text/javascript" src="{$layout_root_url}/includes/ie7-standard-p.js"></script> + <script type="text/javascript" src="[[$layout_root_url]]/includes/ie7-standard-p.js"></script> <![endif]--> - <!-- <script type="text/javascript" src="{$layout_root_url}/includes/standard.js"></script> --> + <!-- <script type="text/javascript" src="[[$layout_root_url]]/includes/standard.js"></script> --> <!-- jQuery and tabs --> - <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.js"></script> - <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.color.js"></script> - <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.silk.js"></script> - <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.tabs.js"></script> + <script type="text/javascript" src="[[$silk_lib_root_url]]/jquery/jquery.js"></script> + <script type="text/javascript" src="[[$silk_lib_root_url]]/jquery/jquery.color.js"></script> + <script type="text/javascript" src="[[$silk_lib_root_url]]/jquery/jquery.silk.js"></script> + <script type="text/javascript" src="[[$silk_lib_root_url]]/jquery/ui/ui.tabs.js"></script> <!-- Tree stuff --> - <link rel="stylesheet" type="text/css" href="{$cmsms_lib_root_url}/js/jstree/source/tree_component.css" /> - <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/css.js"></script> - <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/source/tree_component.js"></script> - <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/jquery.metadata.js"></script> - <script type="text/javascript" src="{$cmsms_lib_root_url}/js/jstree/lib/jquery.cookie.js"></script> + <link rel="stylesheet" type="text/css" href="[[$cmsms_lib_root_url]]/js/jstree/source/tree_component.css" /> + <script type="text/javascript" src="[[$cmsms_lib_root_url]]/js/jstree/lib/css.js"></script> + <script type="text/javascript" src="[[$cmsms_lib_root_url]]/js/jstree/source/tree_component.js"></script> + <script type="text/javascript" src="[[$cmsms_lib_root_url]]/js/jstree/lib/jquery.metadata.js"></script> + <script type="text/javascript" src="[[$cmsms_lib_root_url]]/js/jstree/lib/jquery.cookie.js"></script> - {literal} <script type="text/javascript"> //<![CDATA[ // form handling stuff $(document).ready(function() { setup_form(); }); function setup_form() { // disable all buttons $('button').addClass("disabled").attr("disabled", true); // but enable cancel $('button[@name="cancel"]').removeClass("disabled").attr("disabled", false); // assign event for every input $('form :input').one("change", function() { // on change call enable form enableForm(this.form); // mark in title if(document.title[0] != "*") { document.title = "*"+document.title; } }); // fill the default help text var help = $('#default_helptext').html(); $('#HelpContent').html(help); // assign an event for every form row $("div[id*='formrow']").bind("click", function() { var help = $(this).children("input[id*='help_']").val(); $('#HelpContent').html(help); }); } function enableForm(form) { var input = $('button', form); input.attr('disabled', false).removeClass('disabled'); } //]]></script> - {/literal} - {$headtext} + [[$headtext]] - <base href="{$root_url}" /> + <base href="[[$root_url]]" /> </head> <body> <div id="clean-container"> - {include file="$layout_root_path/topmenu.tpl"} + [[include file="$layout_root_path/topmenu.tpl"]] <div id="MainContent"> - {* - <div class="pagemcontainer"> + [[capture assign="errmsg"]][[php]]echo SilkFlash::get_instance()->get('std')[[/php]][[/capture]] + <div class="pagemcontainer"[[if empty($errmsg)]] style="display: none;"[[/if]]> <p class="pagemessage" id="pagemessage"> - {php}echo SilkFlash::get_instance()->get('std'){/php} + [[$errmsg]] </p> </div> - *} <div class="pagecontainer" id="pagecontent"> - {$content} + [[$content]] </div> <div class="clearb"></div> <div id="HelpContent"></div> </div><!-- end MainContent --> <div id="footer"> - <a rel="external" href="http://www.cmsmadesimple.org"><b>CMS Made Simple</b></a> {$cms_version} "{$cms_versionname}"<br /><b>CMS Made Simple</b> is free software released under the General Public Licence. + <a rel="external" href="http://www.cmsmadesimple.org"><b>CMS Made Simple</b></a> [[$cms_version]] "[[$cms_versionname]]"<br /><b>CMS Made Simple</b> is free software released under the General Public Licence. </div> </div><!--end clean-container--> </body> </html> -{php}echo SilkProfiler::get_instance()->report();{/php} \ No newline at end of file +[[php]]echo SilkProfiler::get_instance()->report();[[/php]] \ No newline at end of file diff --git a/layouts/themes/default/topmenu.tpl b/layouts/themes/default/topmenu.tpl index f0ee427..b27c334 100644 --- a/layouts/themes/default/topmenu.tpl +++ b/layouts/themes/default/topmenu.tpl @@ -1,58 +1,58 @@ -<div id="logocontainer"><img src="layouts/themes/default/images/logoCMS.png" alt="{$adminpaneltitle}" title="{$adminpaneltitle}" /><div class="logotext">{$adminpaneltitle} +<div id="logocontainer"><img src="layouts/themes/default/images/logoCMS.png" alt="[[$adminpaneltitle]]" title="[[$adminpaneltitle]]" /><div class="logotext">[[$adminpaneltitle]] -<br />Welcome User: {$its_me} +<br />Welcome User: [[$its_me]] </div></div> -{if $root_node->has_children()} +[[if $root_node->has_children()]] <div class="topmenucontainer"> <ul id="nav"> - {foreach from=$root_node->get_children() item=node name=node} - <li><a href="{$node->url|escape:'html'}" class="{if $node->selected} selected{/if}"{if $node->target ne ''} rel="external"{/if}>{$node->title}</a> + [[foreach from=$root_node->get_children() item=node name=node]] + <li><a href="[[$node->url|escape:'html']]" class="[[if $node->selected]] selected[[/if]]"[[if $node->target ne '']] rel="external"[[/if]]>[[$node->title]]</a> - {if $node->has_children()} + [[if $node->has_children()]] <ul> - {foreach from=$node->get_children() item=subnode name=subnode} - {if $subnode->show_in_menu} - <li><a href="{$subnode->url|escape:'html'}" class="{if $subnode->selected} selected{/if}{if $subnode->first_module} firstmodule{elseif $subnode->module} module{/if}"{if $subnode->target ne ''} rel="external"{/if}>{$subnode->title}</a></li> - {/if} - {/foreach} + [[foreach from=$node->get_children() item=subnode name=subnode]] + [[if $subnode->show_in_menu]] + <li><a href="[[$subnode->url|escape:'html']]" class="[[if $subnode->selected]] selected[[/if]][[if $subnode->first_module]] firstmodule[[elseif $subnode->module]] module[[/if]]"[[if $subnode->target ne '']] rel="external"[[/if]]>[[$subnode->title]]</a></li> + [[/if]] + [[/foreach]] </ul> - {/if} + [[/if]] </li> - {/foreach} + [[/foreach]] </ul> <!-- ICONS--> <div id="nav-icons_all"> <ul id="nav-icons"> <li class="viewsite-icon"><a rel="external" title="View Site" href="../">View Site</a></li> <li class="logout-icon"><a title="Logout" href="logout.php">Logout</a></li> </ul> </div><!--end nav-icons_all--> <div class="clearb"></div> </div> <div class="breadcrumbs"> - {if count($breadcrumbs) gt 0} - {foreach from=$breadcrumbs item=breadcrumb name=breadcrumb} - {if $breadcrumb.url ne ''} - <a class="breadcrumbs" href="{$breadcrumb.url|escape:'html'}">{$breadcrumb.title}</a> - {else} - {$breadcrumb.title} - {/if} - {if !$smarty.foreach.breadcrumb.last} + [[if count($breadcrumbs) gt 0]] + [[foreach from=$breadcrumbs item=breadcrumb name=breadcrumb]] + [[if $breadcrumb.url ne '']] + <a class="breadcrumbs" href="[[$breadcrumb.url|escape:'html']]">[[$breadcrumb.title]]</a> + [[else]] + [[$breadcrumb.title]] + [[/if]] + [[if !$smarty.foreach.breadcrumb.last]] &#187; - {/if} - {/foreach} - {/if} + [[/if]] + [[/foreach]] + [[/if]] </div> -{/if} +[[/if]] diff --git a/lib/cmsms/classes/class.cms_content_base.php b/lib/cmsms/classes/class.cms_content_base.php index 8884bed..1696aad 100644 --- a/lib/cmsms/classes/class.cms_content_base.php +++ b/lib/cmsms/classes/class.cms_content_base.php @@ -1,37 +1,51 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class CmsContentBase extends SilkObjectRelationalMapping { var $table = 'content'; function __construct() { parent::__construct(); + $this->type = get_class(); } function get_content() { return ''; } + + function get_edit_form($block_name = 'default') + { + $file_name = underscore(get_class($this)); + $tpl_file = join_path(dirname(__FILE__), 'content_types', 'templates', 'edit.' . $file_name . '.tpl'); + if (is_file($tpl_file)) + { + smarty()->assign_by_ref('obj', $this); + smarty()->assign('block_name', $block_name); + return smarty()->fetch($tpl_file); + } + return ''; + } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_base.php b/lib/cmsms/classes/class.cms_module_base.php index 1d9bb48..60adc8d 100644 --- a/lib/cmsms/classes/class.cms_module_base.php +++ b/lib/cmsms/classes/class.cms_module_base.php @@ -1,30 +1,39 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class CmsModuleBase extends SilkObject { function __construct() { parent::__construct(); } + + function do_action_base($name, $id = '', $params = '', $return_id = '') + { + return $this->do_action($name, $id, $params, $return_id); + } + + function do_action($name, $id = '', $params = '', $return_id = '') + { + } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_module_loader.php b/lib/cmsms/classes/class.cms_module_loader.php index eab36ed..44a4027 100644 --- a/lib/cmsms/classes/class.cms_module_loader.php +++ b/lib/cmsms/classes/class.cms_module_loader.php @@ -1,253 +1,266 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #$Id$ class CmsModuleLoader extends SilkObject { public static $module_list = null; function __construct() { parent::__construct(); } public static function load_module_data() { $files = CmsModuleLoader::find_module_info_files(); //Actually slower if it's cached -- have to retest with lots of modules $installed_data = SilkCache::get_instance()->call('CmsModuleLoader::get_installed_module_details'); $module_list = array(); foreach ($files as $one_file) { $module_data = self::xmlify_module_info_file($one_file); $module_data = self::inject_installed_data_for_module($module_data, $installed_data); $module_list[$module_data['name']] = $module_data; } self::check_core_version($module_list); self::check_dependencies($module_list); + + self::$module_list = $module_list; } public static function check_core_version(&$module_list) { foreach ($module_list as &$one_module) { if (isset($one_module['minimum_core_version'])) { if (version_compare($one_module['minimum_core_version'], '2.0', '>')) //Use a real version number here { $one_module['meets_minimum_core'] = false; $one_module['active'] = false; } } } } public static function check_dependencies(&$module_list) { foreach ($module_list as $one_module) { self::check_dependencies_for_module($one_module['name'], $module_list); } } public static function check_dependencies_for_module($module_name, &$module_list) { //Make sure we haven't done this one yet -- no point in repeating if (!isset($module_list[$module_name]['meets_dependencies'])) { $module_list[$module_name]['meets_dependencies'] = true; if (isset($module_list[$module_name]['dependencies']) && is_array($module_list[$module_name]['dependencies'])) { //Hack for handling 1 module dependency if (isset($module_list[$module_name]['dependencies']['module'])) { $tmp = $module_list[$module_name]['dependencies']['module']; unset($module_list[$module_name]['dependencies']['module']); $module_list[$module_name]['dependencies'][0]['module'] = $tmp; } for ($i = 0; $i < count($module_list[$module_name]['dependencies']); $i++) { //If a module dependency (only kind for now) if (isset($module_list[$module_name]['dependencies'][$i]['module'])) { $one_dep = $module_list[$module_name]['dependencies'][$i]['module']; //Does this dependency exist at all? if (isset($module_list[$one_dep['name']])) { //Make sure we process any dependencies first self::check_dependencies_for_module($one_dep['name'], $module_list); //Now that it's processed, check for active and installed_version stuff if ($module_list[$one_dep['name']]['active'] == false) { //var_dump('parent is not active: ' . $one_dep['name'] . ' from ' . $module_name); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } else if (isset($one_dep['minimum_version']) && version_compare($one_dep['minimum_version'], $module_list[$one_dep['name']]['installed_version'], '>')) { //var_dump('does not meet minimum version: ' . $one_dep['name'] . ' from ' . $module_name); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } } else { //var_dump('does not exist: ' . $one_dep['name']); $module_list[$module_name]['meets_dependencies'] = false; $module_list[$module_name]['active'] = false; } } } } } } public static function get_module_class($name) { if (self::$module_list != null) { if (isset(self::$module_list[$name]) && self::$module_list[$name]['active'] == true) { if (isset(self::$module_list[$name]['object'])) { return self::$module_list[$name]['object']; } else { + require_once(join_path(ROOT_DIR, 'modules', $name, $name . '.module.php')); if (class_exists($name) && is_subclass_of($name, 'CmsModuleBase')) { + if (isset(self::$module_list[$name]['dependencies'])) + { + foreach (self::$module_list[$name]['dependencies'] as $dep) + { + self::get_module_class($dep['module']['name']); + } + } + + //var_dump('Instantiating: ' . $name); + self::$module_list[$name]['object'] = new $name(); return self::$module_list[$name]['object']; } } } } return null; } public static function is_installed($name) { if (isset(self::$module_list[$name]) && isset(self::$module_list[$name]['installed'])) return self::$module_list[$name]['installed']; return false; } public static function is_active($name) { if (isset(self::$module_list[$name]) && isset(self::$module_list[$name]['active'])) return self::$module_list[$name]['active']; return false; } public static function get_installed_module_details() { $db_prefix = db_prefix(); return db()->GetAll("select * from {$db_prefix}modules"); } public static function inject_installed_data_for_module($module_data, $installed_data) { $module_data['installed'] = false; $module_data['active'] = false; $module_data['installed_version'] = $module_data['version']; $module_data['needs_upgrade'] = false; $module_data['meets_minimum_core'] = true; foreach($installed_data as $one_row) { if ($one_row['module_name'] == $module_data['name']) { $module_data['installed'] = true; $module_data['active'] = ($one_row['active'] == '1' ? true : false); $module_data['installed_version'] = $one_row['version']; $module_data['needs_upgrade'] = version_compare($module_data['installed_version'], $one_row['version'], '<'); } } return $module_data; } public static function xmlify_module_info_file($file) { $xml = simplexml_load_file($file); return self::convert_xml_to_array($xml); } public static function convert_xml_to_array($xml) { if (!($xml->children())) { return (string) $xml; } foreach ($xml->children() as $child) { $name = $child->getName(); if (count($xml->$name) == 1) { $element[$name] = self::convert_xml_to_array($child); } else { $element[][$name] = self::convert_xml_to_array($child); } } return $element; } public static function find_module_info_files() { $filelist = array(); $dir = join_path(ROOT_DIR, 'modules'); if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..') { $mod_dir = join_path($dir, $file); if (is_dir($mod_dir)) { $mod_info_file = join_path($dir, $file, $file . '.info.xml'); if (is_file($mod_info_file) && is_readable($mod_info_file)) { $filelist[] = $mod_info_file; } } } } closedir($dh); } } return $filelist; } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_page.php b/lib/cmsms/classes/class.cms_page.php index 9a6e005..c3f2c9a 100644 --- a/lib/cmsms/classes/class.cms_page.php +++ b/lib/cmsms/classes/class.cms_page.php @@ -1,196 +1,210 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /** * Base page class. Extend this to create new content types for * the system. * * @author Ted Kulp * @since 2.0 **/ class CmsPage extends SilkObjectRelationalMapping { var $table = 'pages'; var $params = array('id' => -1, 'template_id' => -1, 'active' => true, 'default_content' => false, 'parent_id' => -1, 'lft' => 1, 'rgt' => 1, 'blocks' => array()); #Stuff needed to do a doppleganger for CmsNode -- Multiple inheritence would rock right now var $tree = null; var $parentnode = null; var $children = array(); function __construct() { parent::__construct(); } function setup() { $this->create_belongs_to_association('template', 'CmsTemplate', 'template_id'); $this->assign_acts_as('NestedSet'); } function display() { smarty()->register_object('current_page', $this); $template_content = $this->template->process(); return $template_content; } - function get_content($block_name = 'default') + function get_content_block($block_name = 'default', $can_return_new = false) { if (isset($this->blocks[$block_name])) { if (isset($this->blocks[$block_name]['id'])) { $content = orm('CmsContentBase')->find_by_id($this->blocks[$block_name]['id']); if ($content != null) { - return $content->get_content(); + return $content; } } } + if ($can_return_new) + return new CmsHtmlContent(); //TODO: Fix me + else + return null; + } + + function get_content($block_name = 'default') + { + $block = $this->get_content_block($block_name); + if ($block != null) + { + return $block->get_content(); + } + return '<!-- No content found for ' . $block_name . ' -->'; } /** * Function content types to use to say whether or not they should show * up in lists where parents of content are set. This will default to true, * but should be used in cases like Separator where you don't want it to * have any children. * * @since 0.11 */ function wants_children() { return true; } function can_preview() { return false; } function template_name() { $tmp = $this->template; if ($tmp) return $tmp->name; return ''; } function add_child($node) { $node->set_parent($this); $node->tree = $this->tree; $this->children[] = $node; } function get_tree() { return $this->tree; } function has_children() { return $this->rgt > $this->lft + 1; } function depth() { $depth = 0; $currLevel = &$this; while ($currLevel->parentnode) { $depth++; $currLevel = &$currLevel->parentnode; } return $depth; } function get_level() { return $this->depth(); } function getLevel() { return $this->depth(); } function get_parent() { return $this->parentnode; } function set_parent($node) { $this->parentnode = $node; } function get_children_count() { return count($this->children); } function getChildrenCount() { return $this->get_children_count(); } function &get_children() { if ($this->has_children()) { //We know there are children, but no nodes have been //created yet. We should probably do that. if (!$this->children_loaded()) { //$this->tree->load_child_nodes(-1, $this->lft, $this->rgt); $this->tree->load_child_nodes($this->id); } } return $this->children; } function &get_flat_list() { $return = array(); if ($this->has_children()) { for ($i=0; $i<count($this->children); $i++) { $return[] = &$this->children[$i]; $return = array_merge($return, $this->children[$i]->get_flat_list()); } } return $return; } function &getFlatList() { $tmp =& $this->get_flat_list(); return $tmp; } } ?> diff --git a/lib/cmsms/classes/content_types/templates/edit.cms_html_content.tpl b/lib/cmsms/classes/content_types/templates/edit.cms_html_content.tpl new file mode 100644 index 0000000..1719596 --- /dev/null +++ b/lib/cmsms/classes/content_types/templates/edit.cms_html_content.tpl @@ -0,0 +1 @@ +[[textarea name="block[$block_name][contents]" value=$obj->contents]] diff --git a/lib/cmsms/plugins/function.cms_module.php b/lib/cmsms/plugins/function.cms_module.php new file mode 100644 index 0000000..24d229f --- /dev/null +++ b/lib/cmsms/plugins/function.cms_module.php @@ -0,0 +1,34 @@ +<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- +#CMS - CMS Made Simple +#(c)2004-2008 by Ted Kulp ([email protected]) +#This project's homepage is: http://cmsmadesimple.org +# +#This program is free software; you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation; either version 2 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +#You should have received a copy of the GNU General Public License +#along with this program; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +function smarty_function_cms_module($params, &$smarty) +{ + $module_name = coalesce_key($params, 'module', ''); + $action = coalesce_key($params, 'action', 'default'); + if ($module_name != '') + { + $module = CmsModuleLoader::get_module_class($module_name); + if ($module) + { + return $module->do_action_base($action); + } + } +} + +# vim:ts=4 sw=4 noet +?>
tedkulp/cmsms-nouveau
f66b7437a689022191a1c426c69e8ba61ab62a1f
Got ajax working for editing page templates.
diff --git a/components/admin/controllers/class.page_template_controller.php b/components/admin/controllers/class.page_template_controller.php index 6befce2..b9e2bfb 100644 --- a/components/admin/controllers/class.page_template_controller.php +++ b/components/admin/controllers/class.page_template_controller.php @@ -1,77 +1,87 @@ <?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- #CMS - CMS Made Simple #(c)2004-2008 by Ted Kulp ([email protected]) #This project's homepage is: http://cmsmadesimple.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class PageTemplateController extends AdminController { function index($params) { $templates = orm('CmsTemplate')->find_all(); $this->set('templates', $templates); } function add($params) { if ($params['cancel']) { SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); } $template = new CmsTemplate(); if ($params['submit']) { $template->update_parameters($params['template']); if ($template->save()) { $this->flash = 'Template Added'; SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); } } $this->set('template', $template); } function edit($params) { if ($params['cancel'] or !$params['id']) { SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); } $template = orm('cms_template')->find_by_id($params['id']); - - if ($params['submit']) + if ($params['submit'] || $params['apply']) { $template->update_parameters($params['template']); if ($template->save()) { $this->flash = 'Template Updated'; - SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); + if (!$params['is_silk_ajax']) + { + SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); + } } } + $this->set('template', $template); + + if ($params['is_silk_ajax']) + { + $ajax = new SilkAjax(); + $ajax->replace_html('#pagecontent', $this->render_partial('editform.tpl')); + return $ajax->get_result(); + } } function delete($params) { $this->flash = orm('CmsTemplate')->delete($params['id']) ? 'Template Deleted' : 'There was an error deleteing the template'; SilkResponse::redirect_to_action(array('controller' => 'page_template', 'action' => 'index')); } } # vim:ts=4 sw=4 noet ?> \ No newline at end of file diff --git a/components/admin/plugins/function.cms_validation_errors.php b/components/admin/plugins/function.cms_validation_errors.php new file mode 100644 index 0000000..0eadcb3 --- /dev/null +++ b/components/admin/plugins/function.cms_validation_errors.php @@ -0,0 +1,45 @@ +<?php +#CMS - CMS Made Simple +#(c)2004-2006 by Ted Kulp ([email protected]) +#This project's homepage is: http://cmsmadesimple.org +# +#This program is free software; you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation; either version 2 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +#You should have received a copy of the GNU General Public License +#along with this program; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +function smarty_function_cms_validation_errors($params, &$smarty) +{ + $default_params = array( + 'for' => coalesce_key($params, 'for', null), + 'params' => coalesce_key($params, 'params', array()) + ); + + $params = array_merge($default_params, forms()->strip_extra_params($params, $default_params, 'params')); + unset($params['params']); + + if ($params['for'] != null && is_object($params['for'])) + { + if (isset($params['for']->validation_errors) && is_array($params['for']->validation_errors) && count($params['for']->validation_errors) > 0) + { + echo '<div class="pagemcontainer">'; + echo '<p class="pagemessage">'; + foreach ($params['for']->validation_errors as $err) + { + echo '<img class="systemicon" title="Sucesso" alt="Sucesso" src="' . $smarty->get_template_vars('layout_root_url') . '/images/icons/system/stop.gif" />'.$err.'<br />'; + } + echo '</p>'; + echo '</div>'; + } + } +} + +?> diff --git a/components/admin/views/page_template/add.tpl b/components/admin/views/page_template/add.tpl index 0c1cd20..dfee3af 100644 --- a/components/admin/views/page_template/add.tpl +++ b/components/admin/views/page_template/add.tpl @@ -1,3 +1 @@ -{validation_errors for='template'} - {render_partial template='editform.tpl'} diff --git a/components/admin/views/page_template/edit.tpl b/components/admin/views/page_template/edit.tpl index 0c1cd20..dfee3af 100644 --- a/components/admin/views/page_template/edit.tpl +++ b/components/admin/views/page_template/edit.tpl @@ -1,3 +1 @@ -{validation_errors for='template'} - {render_partial template='editform.tpl'} diff --git a/components/admin/views/page_template/editform.tpl b/components/admin/views/page_template/editform.tpl index eee7073..2bb101b 100644 --- a/components/admin/views/page_template/editform.tpl +++ b/components/admin/views/page_template/editform.tpl @@ -1,8 +1,10 @@ +{cms_validation_errors for=$template} + {form} {label for='template[name]'}Name{/label}: {textbox name='template[name]' value=$template.name}<br /> {label for='template[name]'}Content{/label}: {textarea name='template[content]' value=$template.content cols='80' rows='10'}<br /> {label for='template[active]'}Active{/label}: {checkbox name='template[active]' checked=$template.active}<br /> -{hidden name='template[id]' value=$template.id}{submit name='submit' value="Submit"}{submit name='cancel' value="Cancel"} +{hidden name='template[id]' value=$template.id}{submit name='submit' value="Submit"}{submit name='cancel' value="Cancel"}{submit name='apply' value="Apply" remote="true"} {/form} \ No newline at end of file diff --git a/layouts/themes/default/main.tpl b/layouts/themes/default/main.tpl index c577491..e149d32 100644 --- a/layouts/themes/default/main.tpl +++ b/layouts/themes/default/main.tpl @@ -1,94 +1,106 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="Generator" content="CMS Made Simple - Copyright (C) 2004-2009 Ted Kulp. All rights reserved." /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> <title>{$sitename} - {$title}</title> <link rel="stylesheet" href="{$layout_root_url}/css/kevin_tabs.css" type="text/css" /> <link rel="stylesheet" href="{$layout_root_url}/css/style.css" type="text/css" /> <!--[if IE]> <script type="text/javascript" src="{$layout_root_url}/includes/ie7-standard-p.js"></script> <![endif]--> <script type="text/javascript" src="{$layout_root_url}/includes/standard.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.color.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.jcontext.1.0.js"></script> + <script type="text/javascript" src="{$silk_lib_root_url}/jquery/jquery.silk.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.tabs.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.accordion.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.mouse.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.draggable.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.droppable.js"></script> <script type="text/javascript" src="{$silk_lib_root_url}/jquery/ui/ui.sortable.js"></script> {literal} <script type="text/javascript"> //<![CDATA[ // form handling stuff $(document).ready(function() { // disable all buttons $('button').addClass("disabled").attr("disabled", true); // but enable cancel $('button[@name="cancel"]').removeClass("disabled").attr("disabled", false); // assign event for every input $('form :input').one("change", function() { // on change call enable form enableForm(this.form); // mark in title if(document.title[0] != "*") { document.title = "*"+document.title; } }); // fill the default help text var help = $('#default_helptext').html(); $('#HelpContent').html(help); // assign an event for every form row $("div[id*='formrow']").bind("click", function() { var help = $(this).children("input[id*='help_']").val(); $('#HelpContent').html(help); }); }); function enableForm(form) { var input = $('button', form); input.attr('disabled', false).removeClass('disabled'); } //]]></script> {/literal} {$headtext} <base href="{$root_url}" /> </head> <body> <div id="clean-container"> {include file="$layout_root_path/topmenu.tpl"} <div id="MainContent"> - <div class="pagecontainer"> + + {* + <div class="pagemcontainer"> + <p class="pagemessage" id="pagemessage"> + {php}echo SilkFlash::get_instance()->get('std'){/php} + </p> + </div> + *} + + <div class="pagecontainer" id="pagecontent"> {$content} </div> + <div class="clearb"></div> <div id="HelpContent"></div> + </div><!-- end MainContent --> <div id="footer"> <a rel="external" href="http://www.cmsmadesimple.org"><b>CMS Made Simple</b></a> {$cms_version} "{$cms_versionname}"<br /><b>CMS Made Simple</b> is free software released under the General Public Licence. </div> </div><!--end clean-container--> </body> </html>
tedkulp/cmsms-nouveau
32e28f0abd4c28028efc9f95b52efc8492cd8d18
Added dump.sql file for testing purposes.
diff --git a/dump.sql b/dump.sql new file mode 100644 index 0000000..6d0a48d --- /dev/null +++ b/dump.sql @@ -0,0 +1,1133 @@ +-- MySQL dump 10.11 +-- +-- Host: localhost Database: cms_innodb +-- ------------------------------------------------------ +-- Server version 5.0.51a + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `cms_additional_htmlblob_users` +-- + +DROP TABLE IF EXISTS `cms_additional_htmlblob_users`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_additional_htmlblob_users` ( + `id` int(11) NOT NULL auto_increment, + `user_id` int(11) default NULL, + `htmlblob_id` int(11) default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_additional_htmlblob_users` +-- + +LOCK TABLES `cms_additional_htmlblob_users` WRITE; +/*!40000 ALTER TABLE `cms_additional_htmlblob_users` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_additional_htmlblob_users` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_admin_bookmarks` +-- + +DROP TABLE IF EXISTS `cms_admin_bookmarks`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_admin_bookmarks` ( + `id` int(11) NOT NULL auto_increment, + `user_id` int(11) default NULL, + `title` varchar(255) default NULL, + `url` varchar(255) default NULL, + PRIMARY KEY (`id`), + KEY `user_id` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_admin_bookmarks` +-- + +LOCK TABLES `cms_admin_bookmarks` WRITE; +/*!40000 ALTER TABLE `cms_admin_bookmarks` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_admin_bookmarks` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_admin_recent_pages` +-- + +DROP TABLE IF EXISTS `cms_admin_recent_pages`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_admin_recent_pages` ( + `id` int(11) NOT NULL auto_increment, + `user_id` int(11) default NULL, + `title` varchar(255) default NULL, + `url` varchar(255) default NULL, + `access_time` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_admin_recent_pages` +-- + +LOCK TABLES `cms_admin_recent_pages` WRITE; +/*!40000 ALTER TABLE `cms_admin_recent_pages` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_admin_recent_pages` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_adminlog` +-- + +DROP TABLE IF EXISTS `cms_adminlog`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_adminlog` ( + `timestamp` int(11) default NULL, + `user_id` int(11) default NULL, + `username` varchar(25) default NULL, + `item_id` int(11) default NULL, + `item_name` varchar(50) default NULL, + `action` varchar(255) default NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_adminlog` +-- + +LOCK TABLES `cms_adminlog` WRITE; +/*!40000 ALTER TABLE `cms_adminlog` DISABLE KEYS */; +INSERT INTO `cms_adminlog` VALUES (1229288348,1,'',3,NULL,'Added Content'); +/*!40000 ALTER TABLE `cms_adminlog` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_attribute_defns` +-- + +DROP TABLE IF EXISTS `cms_attribute_defns`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_attribute_defns` ( + `id` int(11) NOT NULL auto_increment, + `module` varchar(100) default NULL, + `extra_attr` varchar(50) default NULL, + `name` varchar(50) default NULL, + `attribute_type` varchar(50) default NULL, + `optional` text, + `user_generated` tinyint(4) default '1', + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_attribute_defns` +-- + +LOCK TABLES `cms_attribute_defns` WRITE; +/*!40000 ALTER TABLE `cms_attribute_defns` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_attribute_defns` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_attributes` +-- + +DROP TABLE IF EXISTS `cms_attributes`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_attributes` ( + `id` int(11) NOT NULL auto_increment, + `attribute_id` int(11) default NULL, + `object_id` int(11) default NULL, + `language` varchar(50) default NULL, + `content` longtext, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `object_id` (`object_id`), + KEY `attribute_id` (`attribute_id`), + KEY `attribute_and_object` (`attribute_id`,`object_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_attributes` +-- + +LOCK TABLES `cms_attributes` WRITE; +/*!40000 ALTER TABLE `cms_attributes` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_attributes` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_blog_categories` +-- + +DROP TABLE IF EXISTS `cms_blog_categories`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_blog_categories` ( + `id` int(11) NOT NULL auto_increment, + `name` varchar(255) default NULL, + `slug` varchar(255) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_blog_categories` +-- + +LOCK TABLES `cms_blog_categories` WRITE; +/*!40000 ALTER TABLE `cms_blog_categories` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_blog_categories` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_blog_post_categories` +-- + +DROP TABLE IF EXISTS `cms_blog_post_categories`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_blog_post_categories` ( + `category_id` int(11) default NULL, + `post_id` int(11) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_blog_post_categories` +-- + +LOCK TABLES `cms_blog_post_categories` WRITE; +/*!40000 ALTER TABLE `cms_blog_post_categories` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_blog_post_categories` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_blog_posts` +-- + +DROP TABLE IF EXISTS `cms_blog_posts`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_blog_posts` ( + `id` int(11) NOT NULL auto_increment, + `author_id` int(11) default NULL, + `post_date` datetime default NULL, + `post_year` int(11) default NULL, + `post_month` int(11) default NULL, + `post_day` int(11) default NULL, + `title` varchar(255) default NULL, + `slug` varchar(255) default NULL, + `url` varchar(255) default NULL, + `content` longtext, + `summary` longtext, + `status` varchar(25) default NULL, + `use_comments` int(1) default '1', + `processor` varchar(25) default '', + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_blog_posts` +-- + +LOCK TABLES `cms_blog_posts` WRITE; +/*!40000 ALTER TABLE `cms_blog_posts` DISABLE KEYS */; +INSERT INTO `cms_blog_posts` VALUES (1,1,'2008-12-14 20:59:23',2008,12,14,'Test Post','test-post','2008/12/14/test-post','Test post','','publish',0,'none','2008-12-14 20:59:35','2008-12-14 20:59:35'),(2,1,'2008-12-14 20:59:23',2008,12,14,'Test Post','test-post','2008/12/14/test-post','Test post','And summary\r\n','publish',0,'none','2008-12-14 21:00:06','2008-12-14 21:01:22'); +/*!40000 ALTER TABLE `cms_blog_posts` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_content` +-- + +DROP TABLE IF EXISTS `cms_content`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_content` ( + `id` int(11) NOT NULL auto_increment, + `content_name` varchar(255) default NULL, + `type` varchar(25) default NULL, + `owner_id` int(11) default NULL, + `parent_id` int(11) default NULL, + `template_id` int(11) default NULL, + `item_order` int(11) default NULL, + `lft` int(11) default NULL, + `rgt` int(11) default NULL, + `hierarchy` varchar(255) default NULL, + `default_content` tinyint(4) default NULL, + `menu_text` varchar(255) default NULL, + `content_alias` varchar(255) default NULL, + `show_in_menu` tinyint(4) default NULL, + `collapsed` tinyint(4) default NULL, + `markup` varchar(25) default NULL, + `active` tinyint(4) default NULL, + `cachable` tinyint(4) default NULL, + `id_hierarchy` varchar(255) default NULL, + `hierarchy_path` text, + `prop_names` text, + `metadata` text, + `titleattribute` varchar(255) default NULL, + `tabindex` varchar(10) default NULL, + `accesskey` varchar(5) default NULL, + `last_modified_by` int(11) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `alias_and_active` (`content_alias`,`active`), + KEY `default_content` (`default_content`), + KEY `parent_id` (`parent_id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_content` +-- + +LOCK TABLES `cms_content` WRITE; +/*!40000 ALTER TABLE `cms_content` DISABLE KEYS */; +INSERT INTO `cms_content` VALUES (1,'__root_node__','root',1,-1,-1,1,1,6,'',0,'__root_node__','__root_node__',0,0,'none',1,0,'','__root_node__','','','','','',1,NULL,NULL),(2,'','content',1,1,1,1,2,3,'1',1,'','',1,0,'',1,0,'2','','default-block-type,default-content,front_page_image-block-type,front_page_image-content,name,menu_text','','','','',1,'2007-11-20 17:49:26','2007-11-20 17:49:41'),(3,'','content',1,1,1,2,4,5,'2',0,'','blog',1,0,'',1,0,'3','blog','name,menu_text,default-block-type,default-content','','','','',1,'2008-12-14 20:59:08','2008-12-14 20:59:08'); +/*!40000 ALTER TABLE `cms_content` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_content_props` +-- + +DROP TABLE IF EXISTS `cms_content_props`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_content_props` ( + `id` int(11) NOT NULL auto_increment, + `content_id` int(11) default NULL, + `type` varchar(25) default NULL, + `prop_name` varchar(255) default NULL, + `language` varchar(50) default NULL, + `content` longtext, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `content_id` (`content_id`) +) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_content_props` +-- + +LOCK TABLES `cms_content_props` WRITE; +/*!40000 ALTER TABLE `cms_content_props` DISABLE KEYS */; +INSERT INTO `cms_content_props` VALUES (1,2,'cmscontentproperty','default-block-type','en_US','html','2007-11-20 17:39:47','2007-11-20 18:07:27'),(2,2,'cmscontentproperty','default-content','en_US','<p>Congratulations! You now have a fully functional installation of CMS Made Simple and you are <em>almost</em> ready to start building your site. First thing though, you should click <a href=\"install/upgrade.php\" title=\"Check if your CMSMS system needs upgrading\">here</a> to check if your site requires a database upgrade. After you have confirmed you are up to date, then we can get cracking on the site development! </p>\r\n\r\n<p>These default pages are devoted to showing you the basics of how to get your site up with CMS Made Simple. </p>\r\n\r\n<p>To get to the Administration Panel you have to login as the administrator (with the username/password you mentioned during the installation process) on your site at http://yourwebsite.com/cmsmspath/admin. </p>\r\n\r\n<p>If you are right now on your own default install, you can probably just click <a title=\"CMSMS Demo Admin Panel\" href=\"admin/\">this link</a>. </p>\r\n\r\n<h3>Learning CMS Made Simple </h3>\r\n\r\n<p>On these example pages many of the features of the default installation of CMS Made Simple are described and demonstrated. You can learn about how to use different kinds of menus, templates, stylesheets and extensions. </p>\r\n\r\n<p>Read about how to use CMS Made Simple in the {cms_selflink ext=\"http://wiki.cmsmadesimple.org/\" title=\"CMS Made Simple Documentation\" text=\"documentation\" target=\"_blank\"}. In case you need any help the community is always at your service, in the \r\n{cms_selflink ext=\"http://forum.cmsmadesimple.org\" title=\"CMS Made Simple Forum\" text=\"forum\" target=\"_blank\"} or the {cms_selflink ext=\"http://www.cmsmadesimple.org/IRC.shtml\" title=\"Information about the CMS Made Simple IRC channel\" text=\"IRC\" target=\"_blank\"}. </p>\r\n\r\n<h3>License </h3>\r\n\r\n<p>CMS Made Simple is released under the {cms_selflink ext=\"http://www.gnu.org/licenses/licenses.html#GPL\" title=\"General Public License\" text=\"GPL\" target=\"_blank\"} license </p>','2007-11-20 17:39:47','2007-11-20 18:07:27'),(3,2,'cmscontentproperty','front_page_image-block-type','en_US','html','2007-11-20 17:39:47','2007-11-20 17:39:47'),(4,2,'cmscontentproperty','front_page_image-content','en_US','Test','2007-11-20 17:39:47','2007-11-20 17:39:47'),(5,2,'cmscontentproperty','name','en_US','Home','2007-11-20 17:39:47','2007-11-20 18:07:27'),(6,2,'cmscontentproperty','menu_text','en_US','Home','2007-11-20 17:39:47','2007-11-20 18:07:27'),(7,3,'cmscontentproperty','name','en_US','blog','2008-12-14 20:59:08','2008-12-14 20:59:08'),(8,3,'cmscontentproperty','menu_text','en_US','blog','2008-12-14 20:59:08','2008-12-14 20:59:08'),(9,3,'cmscontentproperty','default-block-type','en_US','html','2008-12-14 20:59:08','2008-12-14 20:59:08'),(10,3,'cmscontentproperty','default-content','en_US','{cms_module module=\'blog\'}\r\n','2008-12-14 20:59:08','2008-12-14 20:59:08'); +/*!40000 ALTER TABLE `cms_content_props` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_crossref` +-- + +DROP TABLE IF EXISTS `cms_crossref`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_crossref` ( + `child_type` varchar(100) default NULL, + `child_id` int(11) default NULL, + `parent_type` varchar(100) default NULL, + `parent_id` int(11) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + KEY `child_type_and_id` (`child_type`,`child_id`), + KEY `parent_type_and_id` (`parent_type`,`parent_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_crossref` +-- + +LOCK TABLES `cms_crossref` WRITE; +/*!40000 ALTER TABLE `cms_crossref` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_crossref` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_event_handlers` +-- + +DROP TABLE IF EXISTS `cms_event_handlers`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_event_handlers` ( + `id` int(11) NOT NULL auto_increment, + `event_id` int(11) default NULL, + `tag_name` varchar(255) default NULL, + `module_name` varchar(100) default NULL, + `removable` int(11) default NULL, + `handler_order` int(11) default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_event_handlers` +-- + +LOCK TABLES `cms_event_handlers` WRITE; +/*!40000 ALTER TABLE `cms_event_handlers` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_event_handlers` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_events` +-- + +DROP TABLE IF EXISTS `cms_events`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_events` ( + `id` int(11) NOT NULL auto_increment, + `originator` varchar(200) NOT NULL, + `event_name` varchar(200) NOT NULL, + PRIMARY KEY (`id`), + KEY `originator` (`originator`), + KEY `event_name` (`event_name`) +) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_events` +-- + +LOCK TABLES `cms_events` WRITE; +/*!40000 ALTER TABLE `cms_events` DISABLE KEYS */; +INSERT INTO `cms_events` VALUES (1,'Core','LoginPost'),(2,'Core','LogoutPost'),(3,'Core','LoginFailed'),(4,'Core','AddUserPre'),(5,'Core','AddUserPost'),(6,'Core','EditUserPre'),(7,'Core','EditUserPost'),(8,'Core','DeleteUserPre'),(9,'Core','DeleteUserPost'),(10,'Core','AddGroupPre'),(11,'Core','AddGroupPost'),(12,'Core','EditGroupPre'),(13,'Core','EditGroupPost'),(14,'Core','DeleteGroupPre'),(15,'Core','DeleteGroupPost'),(16,'Core','AddStylesheetPre'),(17,'Core','AddStylesheetPost'),(18,'Core','EditStylesheetPre'),(19,'Core','EditStylesheetPost'),(20,'Core','DeleteStylesheetPre'),(21,'Core','DeleteStylesheetPost'),(22,'Core','AddTemplatePre'),(23,'Core','AddTemplatePost'),(24,'Core','EditTemplatePre'),(25,'Core','EditTemplatePost'),(26,'Core','DeleteTemplatePre'),(27,'Core','DeleteTemplatePost'),(28,'Core','TemplatePreCompile'),(29,'Core','TemplatePostCompile'),(30,'Core','AddGlobalContentPre'),(31,'Core','AddGlobalContentPost'),(32,'Core','EditGlobalContentPre'),(33,'Core','EditGlobalContentPost'),(34,'Core','DeleteGlobalContentPre'),(35,'Core','DeleteGlobalContentPost'),(36,'Core','GlobalContentPreCompile'),(37,'Core','GlobalContentPostCompile'),(38,'Core','ContentEditPre'),(39,'Core','ContentEditPost'),(40,'Core','ContentDeletePre'),(41,'Core','ContentDeletePost'),(42,'Core','AddUserDefinedTagPre'),(43,'Core','AddUserDefinedTagPost'),(44,'Core','EditUserDefinedTagPre'),(45,'Core','EditUserDefinedTagPost'),(46,'Core','DeleteUserDefinedTagPre'),(47,'Core','DeleteUserDefinedTagPost'),(48,'Core','ModuleInstalled'),(49,'Core','ModuleUninstalled'),(50,'Core','ModuleUpgraded'),(51,'Core','AllModulesLoaded'),(52,'Core','HeaderTagRender'),(53,'Core','ContentStylesheet'),(54,'Core','ContentPreCompile'),(55,'Core','ContentPostCompile'),(56,'Core','ContentPostRender'),(57,'Core','SmartyPreCompile'),(58,'Core','SmartyPostCompile'),(59,'Core','SearchReindex'),(60,'Core','AdminDisplayStart'),(61,'Core','AdminDisplayFinish'),(62,'Core','MissingTranslation'); +/*!40000 ALTER TABLE `cms_events` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_group_permissions` +-- + +DROP TABLE IF EXISTS `cms_group_permissions`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_group_permissions` ( + `id` int(11) NOT NULL auto_increment, + `permission_defn_id` int(11) default NULL, + `group_id` int(11) default NULL, + `object_id` int(11) default NULL, + `has_access` tinyint(4) default '1', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_group_permissions` +-- + +LOCK TABLES `cms_group_permissions` WRITE; +/*!40000 ALTER TABLE `cms_group_permissions` DISABLE KEYS */; +INSERT INTO `cms_group_permissions` VALUES (2,1,1,1,1); +/*!40000 ALTER TABLE `cms_group_permissions` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_group_perms` +-- + +DROP TABLE IF EXISTS `cms_group_perms`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_group_perms` ( + `id` int(11) NOT NULL auto_increment, + `group_id` int(11) default NULL, + `permission_id` int(11) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `group_and_permission` (`group_id`,`permission_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_group_perms` +-- + +LOCK TABLES `cms_group_perms` WRITE; +/*!40000 ALTER TABLE `cms_group_perms` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_group_perms` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_groups` +-- + +DROP TABLE IF EXISTS `cms_groups`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_groups` ( + `id` int(11) NOT NULL auto_increment, + `group_name` varchar(25) default NULL, + `active` tinyint(4) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_groups` +-- + +LOCK TABLES `cms_groups` WRITE; +/*!40000 ALTER TABLE `cms_groups` DISABLE KEYS */; +INSERT INTO `cms_groups` VALUES (1,'Admin',1,'2007-11-25 16:01:31','2007-11-25 16:01:31'),(2,'Anonymous',1,'2007-11-25 16:01:31','2007-11-25 16:01:31'); +/*!40000 ALTER TABLE `cms_groups` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_htmlblobs` +-- + +DROP TABLE IF EXISTS `cms_htmlblobs`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_htmlblobs` ( + `id` int(11) NOT NULL auto_increment, + `htmlblob_name` varchar(255) default NULL, + `html` longtext, + `owner` int(11) default NULL, + `version` int(11) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `htmlblob_name` (`htmlblob_name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_htmlblobs` +-- + +LOCK TABLES `cms_htmlblobs` WRITE; +/*!40000 ALTER TABLE `cms_htmlblobs` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_htmlblobs` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_language_definitions` +-- + +DROP TABLE IF EXISTS `cms_language_definitions`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_language_definitions` ( + `id` int(11) NOT NULL auto_increment, + `name` varchar(75) default NULL, + `english_name` varchar(75) default NULL, + `aliases` varchar(255) default NULL, + `code` varchar(10) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_language_definitions` +-- + +LOCK TABLES `cms_language_definitions` WRITE; +/*!40000 ALTER TABLE `cms_language_definitions` DISABLE KEYS */; +INSERT INTO `cms_language_definitions` VALUES (1,'Afrikaans','Africaans','af,afr,afrikaans,af_ZA.ISO8859-1','af_ZA',NULL,NULL),(2,'Български','Bulgarian','bg,bulgari','bg_BG',NULL,NULL),(3,'Català','Catalan','ca,cat,català,ca_ES.ISO8859-1','ca_ES',NULL,NULL),(4,'Česky','Czech','cs,czech,cze,cs_CS,cs_CZ.WINDOWS-1250,cs_CZ.ISO8859-2','cs_CZ',NULL,NULL),(5,'Dansk','Danish','dk,dansk,dan,da_DK,da_DK.ISO8859-1','da_DK',NULL,NULL),(6,'Deutsch','German','de,deutsch,deu,de_DE.ISO8859-1','de_DE',NULL,NULL),(7,'Ελληνικα','Greek','gr,greek,hellenic,el,el_GR.ISO8859-7','el_GR',NULL,NULL),(8,'English','English','en,english,eng,en_CA,en_GB,en_US.ISO8859-1','en_US',NULL,NULL),(9,'Español','Spanish','es,espanol,español,esp,es_AR,es_PE,es_MX','es_ES',NULL,NULL),(10,'Eesti','Estonian','et,estonian,eti,et_EE.ISO8859-1,et_EE.ISO8859-15,et_EE.UTF-8','et_EE',NULL,NULL),(11,'Euskara','Basque','eu,basque,baq,eus,eu_ES,eu_ES.ISO8859-1','eu_ES',NULL,NULL),(12,'Suomi','Finnish','fi,finnish,fi_FI.ISO8859-1,fi_FI.ISO8859-15','fi_FI',NULL,NULL),(13,'Français','French','fr,french,fra,fr_BE,fr_CA,fr_LU,fr_CH,fr_FR.ISO8859-1','fr_FR',NULL,NULL),(14,'Magyar','Hungarian','hu,hungarian,magyar,hu_HU.WINDOWS-1250,hu_HU.ISO8859-2','hu_HU',NULL,NULL),(15,'Bahasa Indonesia','Indonesian','id,ind,id_ID,id_ID.ISO8859-15','id_ID',NULL,NULL),(16,'Íslenska','Icelandic','is,icelandic,ice,isl,is_IS.ISO8859-1,is_IS.ISO8859-15','is_IS',NULL,NULL),(17,'Italiano','Italian','it,italiano,ita,italian,it_IT.ISO8859-1,it_IT.ISO8859-15','it_IT',NULL,NULL),(18,'日本語','Japanese','ja,japanese,jap,ja_JP.EUC-JP,ja_JP.Shift_JIS,ja_JP.UTF-8','ja_JP',NULL,NULL),(19,'Lietuvių','Lithuanian','lt,lithuanian,lt_LT,lt_LT.ISO8859-13','lt_LT',NULL,NULL),(20,'Norsk bokmÃ¥l','Norwegian','no,norwegian,nor,nb_NO.ISO8859-1,nb_NO.ISO8859-15','nb_NO',NULL,NULL),(21,'Nederlands','Dutch','dutch,nl_NL.ISO8859-1','nl_NL',NULL,NULL),(22,'Polski','Polish','pl,polish,pl_PL.ISO8859-2','pl_PL',NULL,NULL),(23,'Português Brasileiro','Portuguese [Brazilian]','pt-BR','pt_BR',NULL,NULL),(24,'Português','Portuguese','pt-PT','pt_PT',NULL,NULL),(25,'Русский','Russian','ru,russian,rus','ru_RU',NULL,NULL),(26,'Slovenčina','Slovak','sk,slovak,svk,sk_SK,sk_SK.WINDOWS-1250,sk_SK.ISO8859-2','sk_SK',NULL,NULL),(27,'српски Srpski','Serbian','sr,serbian,srb,sr_YU,sr_YU.WINDOWS-1250,sr_YU.ISO8859-2,sr_YU.UTF-8','sr_YU',NULL,NULL),(28,'Svenska','Swedish','sv,svenska,sve,sv_SE,sv_SE.ISO8859-1,sv_SE.ISO8859-15','sv_SE',NULL,NULL),(29,'Türkçe','Turkish','tr,turkish,trk,tr_TR.ISO8859-9,tr_TR.UTF-8','tr_TR',NULL,NULL),(30,'简体中文','Simplified Chinese','zh_CN.EUC,chinese_gb2312','zh_CN',NULL,NULL),(31,'繁體中文','Traditional Chinese','chinese,zh_TW.Big5','zh_TW',NULL,NULL); +/*!40000 ALTER TABLE `cms_language_definitions` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_language_keys` +-- + +DROP TABLE IF EXISTS `cms_language_keys`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_language_keys` ( + `id` int(11) NOT NULL auto_increment, + `module_name` varchar(100) NOT NULL, + `key_string` text, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_language_keys` +-- + +LOCK TABLES `cms_language_keys` WRITE; +/*!40000 ALTER TABLE `cms_language_keys` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_language_keys` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_language_values` +-- + +DROP TABLE IF EXISTS `cms_language_values`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_language_values` ( + `id` int(11) NOT NULL auto_increment, + `language_key_id` int(11) default NULL, + `language_code` varchar(10) default NULL, + `value` longtext, + `modified` tinyint(4) default '0', + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_language_values` +-- + +LOCK TABLES `cms_language_values` WRITE; +/*!40000 ALTER TABLE `cms_language_values` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_language_values` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_module_deps` +-- + +DROP TABLE IF EXISTS `cms_module_deps`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_module_deps` ( + `parent_module` varchar(100) default NULL, + `child_module` varchar(100) default NULL, + `minimum_version` varchar(25) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_module_deps` +-- + +LOCK TABLES `cms_module_deps` WRITE; +/*!40000 ALTER TABLE `cms_module_deps` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_module_deps` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_module_templates` +-- + +DROP TABLE IF EXISTS `cms_module_templates`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_module_templates` ( + `id` int(11) NOT NULL auto_increment, + `module_name` varchar(100) NOT NULL, + `template_type` varchar(100) NOT NULL default '', + `template_name` varchar(150) NOT NULL, + `content` longtext, + `default_template` tinyint(4) default '0', + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `module_and_template` (`module_name`,`template_name`) +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_module_templates` +-- + +LOCK TABLES `cms_module_templates` WRITE; +/*!40000 ALTER TABLE `cms_module_templates` DISABLE KEYS */; +INSERT INTO `cms_module_templates` VALUES (1,'Blog','summary','Default Template','{foreach from=$posts item=entry}\n<h3><a href=\"{$entry->url}\">{$entry->title}</a></h3>\n<small>\n {$entry->post_date} \n {if $entry->author ne null}\n {mod_lang string=by} {$entry->author->full_name()}\n {/if}\n</small>\n\n<div>\n{$entry->get_summary_for_frontend()}\n</div>\n\n{if $entry->has_more() eq true}\n <a href=\"{$entry->url}\">{mod_lang string=hasmore} &gt;&gt;</a>\n{/if}\n\n{/foreach}',1,'2008-12-10 13:18:23','2008-12-10 13:18:23'),(2,'Blog','detail','Default Template','{if $post ne null}\n<h3>{$post->title}</h3>\n<small>\n {$post->post_date} \n {if $post->author ne null}\n {mod_lang string=by} {$post->author->full_name()}\n {/if}\n</small>\n\n<div>\n{$post->content}\n</div>\n\n<hr />\n\n<p>\n{cms_module module=\"comments\" module_name=\"blog\" content_id=$post->id}\n</p>\n\n{else}\n{mod_lang string=postnotfound}\n{/if}',1,'2008-12-10 13:18:23','2008-12-10 13:18:23'),(3,'Blog','rss','Default Template','<?xml version=\"1.0\"?>\n<rss version=\"2.0\">\n <channel>\n <title>{$sitename|escape}</title>\n <link>{root_url}</link>\n {foreach from=$posts item=entry}\n <item>\n <title><![CDATA[{$entry->title}]]></title>\n <link>{$entry->url}</link>\n <guid>{$entry->url}</guid>\n <pubDate>{$entry->post_date}</pubDate>\n <category><![CDATA[]]></category>\n <description><![CDATA[{$entry->get_summary_for_frontend()}]]></description>\n </item>\n {/foreach}\n </channel>\n</rss> \n',1,'2008-12-10 13:18:23','2008-12-10 13:18:23'),(4,'UserAdmin','login','Default Login Form','{* UserAdmin login form *}\n{if !empty($error)}\n<p><strong>{$error}</strong></p>\n{/if}\n{mod_form action=\'login\' inline=\'true\'}\n<p>{tr}Username{/tr}:&nbsp;{mod_textbox name=\'username\' size=\'25\' maxlength=\'25\'}</p>\n<p>{tr}Password{/tr}:&nbsp;{mod_password name=\'password\' size=\'25\' maxlength=\'25\'}</p>\n<p>{tr}OpenID{/tr}:&nbsp;{mod_text name=\'openid\' size=\'15\' maxlength=\'15\'}</p>\n<p>{mod_submit name=\'submit\' value=\'submit\'}</p>\n{/mod_form}',1,'2008-12-14 18:27:51','2008-12-14 18:27:51'),(5,'MenuManager','menu_template','Default Template','{if $count > 0}\n <ul>\n {foreach from=$nodelist item=node}\n {if $node->show}\n <li>\n <a href=\"{$node->url}\">{$node->menutext}</a>\n {menu_children node=$node}\n </li>\n {/if}\n {/foreach}\n </ul>\n{/if}\n',1,'2008-12-14 18:27:57','2008-12-14 18:27:57'); +/*!40000 ALTER TABLE `cms_module_templates` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_modules` +-- + +DROP TABLE IF EXISTS `cms_modules`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_modules` ( + `module_name` varchar(100) default NULL, + `status` varchar(50) default NULL, + `version` varchar(50) default NULL, + `admin_only` tinyint(4) default '0', + `active` tinyint(4) default NULL, + KEY `module_name` (`module_name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_modules` +-- + +LOCK TABLES `cms_modules` WRITE; +/*!40000 ALTER TABLE `cms_modules` DISABLE KEYS */; +INSERT INTO `cms_modules` VALUES ('Blog','installed','0.1',0,1),('UserAdmin','installed','0.1',0,1),('MenuManager','installed','2.0',0,1); +/*!40000 ALTER TABLE `cms_modules` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_multilanguage` +-- + +DROP TABLE IF EXISTS `cms_multilanguage`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_multilanguage` ( + `id` int(11) NOT NULL auto_increment, + `module_name` varchar(100) default NULL, + `content_type` varchar(25) default NULL, + `object_id` int(11) default NULL, + `property_name` varchar(100) default NULL, + `language` varchar(5) default NULL, + `content` longtext, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_multilanguage` +-- + +LOCK TABLES `cms_multilanguage` WRITE; +/*!40000 ALTER TABLE `cms_multilanguage` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_multilanguage` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_permission_defns` +-- + +DROP TABLE IF EXISTS `cms_permission_defns`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_permission_defns` ( + `id` int(11) NOT NULL auto_increment, + `module` varchar(100) default NULL, + `extra_attr` varchar(50) default NULL, + `name` varchar(50) default NULL, + `hierarchical` tinyint(4) default '0', + `link_table` varchar(50) default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_permission_defns` +-- + +LOCK TABLES `cms_permission_defns` WRITE; +/*!40000 ALTER TABLE `cms_permission_defns` DISABLE KEYS */; +INSERT INTO `cms_permission_defns` VALUES (1,'Core','Page','View',1,'content'),(2,'Core','Page','Edit',1,'content'),(3,'Core','Page','Delete',1,'content'),(4,'Core','','Manage Groups',0,NULL),(5,'Core','','Manage Users',0,NULL),(6,'Core','','Manage Layout',0,NULL),(7,'Core','','Manage Modules',0,NULL),(8,'Core','','Manage Files',0,NULL),(9,'Core','','Manage Site Preferences',0,NULL),(10,'Core','','Manage User-defined Tags',0,NULL),(11,'Core','','Manage Global Content Blocks',0,NULL),(12,'Core','','Manage Events',0,NULL),(13,'Core','','Admin Login',0,NULL); +/*!40000 ALTER TABLE `cms_permission_defns` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_permissions` +-- + +DROP TABLE IF EXISTS `cms_permissions`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_permissions` ( + `id` int(11) NOT NULL auto_increment, + `permission_name` varchar(255) default NULL, + `permission_text` varchar(255) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_permissions` +-- + +LOCK TABLES `cms_permissions` WRITE; +/*!40000 ALTER TABLE `cms_permissions` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_permissions` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_serialized_versions` +-- + +DROP TABLE IF EXISTS `cms_serialized_versions`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_serialized_versions` ( + `id` int(11) NOT NULL auto_increment, + `version` int(11) default NULL, + `object_id` int(11) default NULL, + `data` longblob, + `type` varchar(255) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_serialized_versions` +-- + +LOCK TABLES `cms_serialized_versions` WRITE; +/*!40000 ALTER TABLE `cms_serialized_versions` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_serialized_versions` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_siteprefs` +-- + +DROP TABLE IF EXISTS `cms_siteprefs`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_siteprefs` ( + `sitepref_name` varchar(255) NOT NULL, + `sitepref_value` text, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`sitepref_name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_siteprefs` +-- + +LOCK TABLES `cms_siteprefs` WRITE; +/*!40000 ALTER TABLE `cms_siteprefs` DISABLE KEYS */; +INSERT INTO `cms_siteprefs` VALUES ('custom404','<p>Page could not be found.</p>','2006-07-25 21:22:33','2006-07-25 21:22:33'),('custom404template','-1','2006-07-25 21:22:33','2006-07-25 21:22:33'),('enablecustom404','0','2006-07-25 21:22:33','2006-07-25 21:22:33'),('enablesitedownmessage','0','2006-07-25 21:22:33','2006-07-25 21:22:33'),('logintheme','default','2006-07-25 21:22:33','2006-07-25 21:22:33'),('metadata','<meta name=\"Generator\" content=\"CMS Made Simple - Copyright (C) 2004-6 Ted Kulp. All rights reserved.\" />\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n ','2006-07-25 21:22:33','2006-07-25 21:22:33'),('sitedownmessage','<p>Site is currently down for maintenance.</p>','2006-07-25 21:22:33','2006-07-25 21:22:33'),('sitedownmessagetemplate','-1','2006-07-25 21:22:33','2006-07-25 21:22:33'),('useadvancedcss','1','2006-07-25 21:22:33','2006-07-25 21:22:33'),('xmlmodulerepository',NULL,'2006-07-25 21:22:33','2006-07-25 21:22:33'); +/*!40000 ALTER TABLE `cms_siteprefs` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_stylesheet_template_assoc` +-- + +DROP TABLE IF EXISTS `cms_stylesheet_template_assoc`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_stylesheet_template_assoc` ( + `id` int(11) NOT NULL auto_increment, + `stylesheet_id` int(11) default NULL, + `template_id` int(11) default NULL, + `order_num` int(11) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `stylesheet_id` (`stylesheet_id`), + KEY `template_id` (`template_id`), + KEY `stylesheet_id_template_id` (`stylesheet_id`,`template_id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_stylesheet_template_assoc` +-- + +LOCK TABLES `cms_stylesheet_template_assoc` WRITE; +/*!40000 ALTER TABLE `cms_stylesheet_template_assoc` DISABLE KEYS */; +INSERT INTO `cms_stylesheet_template_assoc` VALUES (1,2,1,1,NULL,NULL); +/*!40000 ALTER TABLE `cms_stylesheet_template_assoc` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_stylesheets` +-- + +DROP TABLE IF EXISTS `cms_stylesheets`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_stylesheets` ( + `id` int(11) NOT NULL auto_increment, + `name` varchar(255) default NULL, + `value` longtext, + `active` tinyint(4) default '1', + `media_type` varchar(255) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `name` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_stylesheets` +-- + +LOCK TABLES `cms_stylesheets` WRITE; +/*!40000 ALTER TABLE `cms_stylesheets` DISABLE KEYS */; +INSERT INTO `cms_stylesheets` VALUES (2,'Test','Test',1,'all','2009-01-19 23:34:06','2009-01-19 23:34:06'); +/*!40000 ALTER TABLE `cms_stylesheets` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_tag_objects` +-- + +DROP TABLE IF EXISTS `cms_tag_objects`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_tag_objects` ( + `tag_id` int(11) default NULL, + `name` varchar(255) default NULL, + `type` varchar(25) default NULL, + `object_id` int(11) default NULL, + KEY `tag_object_name` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_tag_objects` +-- + +LOCK TABLES `cms_tag_objects` WRITE; +/*!40000 ALTER TABLE `cms_tag_objects` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_tag_objects` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_tags` +-- + +DROP TABLE IF EXISTS `cms_tags`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_tags` ( + `id` int(11) NOT NULL auto_increment, + `name` varchar(255) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `tag_name` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_tags` +-- + +LOCK TABLES `cms_tags` WRITE; +/*!40000 ALTER TABLE `cms_tags` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_tags` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_templates` +-- + +DROP TABLE IF EXISTS `cms_templates`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_templates` ( + `id` int(11) NOT NULL auto_increment, + `template_name` varchar(255) default NULL, + `template_content` longtext, + `encoding` varchar(25) default NULL, + `active` tinyint(4) default '1', + `default_template` tinyint(4) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`), + KEY `template_name` (`template_name`) +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_templates` +-- + +LOCK TABLES `cms_templates` WRITE; +/*!40000 ALTER TABLE `cms_templates` DISABLE KEYS */; +INSERT INTO `cms_templates` VALUES (1,'Minimal Template','{* Change lang=\"en\" to the language of your site *}\r\n\r\n\r\n\r\n{sitename} - {title}\r\n{* The sitename is changed in Site Admin/Global settings. {title} is the name of each page *}\r\n\r\n{header}\r\n{* This is how all the stylesheets attached to this template are linked to and where metadata is displayed *}\r\n\r\n\r\n\r\n\r\n\r\n {* Start Navigation *}\r\n \r\n {language_selector}\r\n {menu}\r\n \r\n {* End Navigation *}\r\n\r\n {* Start Content *}\r\n \r\n {title}\r\n {content}\r\n \r\n {* End Content *}\r\n\r\n\r\n','',1,1,'2009-01-17 22:31:05','2009-01-17 22:39:19'); +/*!40000 ALTER TABLE `cms_templates` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_user_groups` +-- + +DROP TABLE IF EXISTS `cms_user_groups`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_user_groups` ( + `group_id` int(11) default NULL, + `user_id` int(11) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_user_groups` +-- + +LOCK TABLES `cms_user_groups` WRITE; +/*!40000 ALTER TABLE `cms_user_groups` DISABLE KEYS */; +INSERT INTO `cms_user_groups` VALUES (1,1,'2008-12-09 06:16:17','2008-12-09 06:16:17'); +/*!40000 ALTER TABLE `cms_user_groups` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_userplugins` +-- + +DROP TABLE IF EXISTS `cms_userplugins`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_userplugins` ( + `id` int(11) NOT NULL auto_increment, + `userplugin_name` varchar(255) default NULL, + `code` text, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_userplugins` +-- + +LOCK TABLES `cms_userplugins` WRITE; +/*!40000 ALTER TABLE `cms_userplugins` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_userplugins` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_userprefs` +-- + +DROP TABLE IF EXISTS `cms_userprefs`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_userprefs` ( + `user_id` int(11) default NULL, + `preference` varchar(50) default NULL, + `value` text, + `type` varchar(25) default NULL, + KEY `user_id` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_userprefs` +-- + +LOCK TABLES `cms_userprefs` WRITE; +/*!40000 ALTER TABLE `cms_userprefs` DISABLE KEYS */; +/*!40000 ALTER TABLE `cms_userprefs` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_users` +-- + +DROP TABLE IF EXISTS `cms_users`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_users` ( + `id` int(11) NOT NULL auto_increment, + `username` varchar(25) default NULL, + `password` varchar(40) default NULL, + `first_name` varchar(50) default NULL, + `last_name` varchar(50) default NULL, + `email` varchar(255) default NULL, + `openid` varchar(255) default NULL, + `checksum` varchar(255) default NULL, + `active` tinyint(4) default NULL, + `create_date` datetime default NULL, + `modified_date` datetime default NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_users` +-- + +LOCK TABLES `cms_users` WRITE; +/*!40000 ALTER TABLE `cms_users` DISABLE KEYS */; +INSERT INTO `cms_users` VALUES (1,'admin','21232f297a57a5a743894a0e4a801fc3','Ted','Kulp','[email protected]','http://tedkulp.com/','',1,'2008-12-09 06:16:17','2008-12-09 06:16:17'); +/*!40000 ALTER TABLE `cms_users` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cms_version` +-- + +DROP TABLE IF EXISTS `cms_version`; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +CREATE TABLE `cms_version` ( + `version` int(11) default NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +SET character_set_client = @saved_cs_client; + +-- +-- Dumping data for table `cms_version` +-- + +LOCK TABLES `cms_version` WRITE; +/*!40000 ALTER TABLE `cms_version` DISABLE KEYS */; +INSERT INTO `cms_version` VALUES (1); +/*!40000 ALTER TABLE `cms_version` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2009-02-02 0:53:37 diff --git a/layouts/default.tpl b/layouts/default.tpl deleted file mode 100644 index 5b7bf50..0000000 --- a/layouts/default.tpl +++ /dev/null @@ -1,19 +0,0 @@ -<html> -<head> -<title>{$title}</title> -{javascript file="lib/silk/jquery/jquery.js"} -{javascript file="lib/silk/jquery/jquery.color.js"} -{javascript file="lib/silk/jquery/jquery.silk.js"} -</head> - -<body> - -<div id="messages"> - {php}echo SilkFlash::get_instance()->get('std'){/php} -</div> - -{$content} - -</body> - -</html> \ No newline at end of file diff --git a/lib/cmsms/classes/class.cms_admin_theme.php b/lib/cmsms/classes/class.cms_admin_theme.php deleted file mode 100644 index bb58d5b..0000000 --- a/lib/cmsms/classes/class.cms_admin_theme.php +++ /dev/null @@ -1,1138 +0,0 @@ -<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*- -#CMS - CMS Made Simple -#(c)2004-2008 by Ted Kulp ([email protected]) -#This project's homepage is: http://cmsmadesimple.org -# -#This program is free software; you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation; either version 2 of the License, or -#(at your option) any later version. -# -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -#GNU General Public License for more details. -#You should have received a copy of the GNU General Public License -#along with this program; if not, write to the Free Software -#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -#$Id$ - -/** - * Class to extend in order to create a theme for the admin panel. - * - * @author Ted Kulp - * @since 2.0 - * @version $Revision$ - * @modifiedby $LastChangedBy$ - * @lastmodified $Date$ - * @license GPL - **/ -class CmsAdminTheme extends SilkObject -{ - static private $instance = NULL; - public $breadcrumbs = array(); - public $menuItems; - public $script; - public $headtext = ''; - public $section_count = array(); - public $modules_by_section = array(); - public $url = ''; - public $query = ''; - public $subtitle = ''; - public $theme_template_dir = ''; - public $theme_name = ''; - public $themeName = ''; - public $errors = array(); - public $messages = array(); - private $_notificationitems; - - function __construct($userid, $theme_name = 'default') - { - parent::__construct(); - - //Pull any errors out of the session and load them so they'll display when they get the chance - if (isset($_SESSION['errors'])) - { - foreach ($_SESSION['errors'] as $one_error) - { - $this->errors[] = $one_error; - } - - $_SESSION['errors'] = array(); - } - - //Pull any messages out of the session and load them so they'll display when they get the chance - if (isset($_SESSION['messages'])) - { - foreach ($_SESSION['messages'] as $one_message) - { - $this->messages[] = $one_message; - } - - $_SESSION['messages'] = array(); - } - - $this->theme_name = $theme_name; - - $this->url = $_SERVER['SCRIPT_NAME']; - $this->query = (isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:''); - if ($this->query == '' && isset($_POST['module']) && $_POST['module'] != '') - { - $this->query = 'module='.$_POST['module']; - } - if (strpos( $this->url, '/' ) === false) - { - $this->script = $this->url; - } - else - { - $toam_tmp = explode('/',$this->url); - $toam_tmp2 = array_pop($toam_tmp); - $this->script = $toam_tmp2; - //$this->script = array_pop(@explode('/',$this->url)); - } - - $this->theme_template_dir = dirname(dirname(dirname(__FILE__))) . '/' . CmsConfig::get('admin_dir') . '/themes/' . $this->theme_name . '/templates/'; - } - - static public function get_instance($is_anonymous = false) - { - if (self::$instance == NULL) - { - self::$instance = self::get_theme_for_user($is_anonymous); - } - return self::$instance; - } - - static function get_theme_for_user($is_anonymous = false) - { - $gCms = cmsms(); - - $theme_name = 'default'; - $userid = -1; - - if (!$is_anonymous) - { - $user = CmsLogin::get_current_user(); - $userid = $user->id; - - $theme_name = get_preference($userid, 'admintheme', 'default'); - } - $theme_file_name = "{$theme_name}_theme"; - $theme_object_name = ucfirst(camelize($theme_file_name)); - - if (file_exists(dirname(dirname(dirname(__FILE__))) . DS . "admin/themes/${theme_name}/${theme_file_name}.php")) - { - include(dirname(dirname(dirname(__FILE__))) . DS . "admin/themes/${theme_name}/${theme_file_name}.php"); - $themeObject = new $theme_object_name($userid, $theme_name); - } - else - { - include(dirname(dirname(dirname(__FILE__))) . DS . "admin/themes/default/default_theme.php"); - $themeObject = new CmsAdminTheme($userid); - } - - $themeObject->userid = $userid; - if (!$is_anonymous) - { - $themeObject->set_module_admin_interfaces(); - $themeObject->set_aggrigate_permissions(); - $themeObject->populate_admin_navigation(); - } - - return $themeObject; - } - - static public function start($is_anonymous = false) - { - CmsEventOperations::send_event('Core', 'AdminDisplayStart'); - - @ob_start(); - - $admin_theme = self::get_instance($is_anonymous); - - $smarty = cms_smarty(); - $smarty->assign_by_ref('admin_theme', $admin_theme); - $smarty->assign('adminpaneltitle', lang('adminpaneltitle')); - $smarty->assign('baseurl', CmsConfig::get('root_url') . '/' . CmsConfig::get('admin_dir') . '/'); - } - - static public function end() - { - global $gCms; - // Add in stuff needed WYSIWYG editors - foreach($gCms->modules as $key=>$value) - { - if ($gCms->modules[$key]['installed'] == true && - $gCms->modules[$key]['active'] == true && - $gCms->modules[$key]['object']->is_wysiwyg() - ) - { - $loadit=false; - if ($gCms->modules[$key]['object']->WYSIWYGActive()) - { - $loadit=true; - } - else - { - if (get_preference(get_userid(), 'wysiwyg')==$gCms->modules[$key]['object']->get_name()) - { - $loadit=true; - } - } - if ($loadit) - { - //$bodytext.=$gCms->modules[$key]['object']->WYSIWYGGenerateBody(); - // Add to header - CmsAdminTheme::inject_header_text($gCms->modules[$key]['object']->WYSIWYGGenerateHeader()); - //$formtext.=$gCms->modules[$key]['object']->WYSIWYGPageForm(); - //$formsubmittext.=$gCms->modules[$key]['object']->WYSIWYGPageFormSubmit(); - } - } - } - - $result = @ob_get_clean(); - - $smarty = cms_smarty(); - $smarty->assign('admin_content', $result); - - @ob_start(); - self::get_instance()->display_top_menu(); - $topmenu = @ob_get_clean(); - $smarty->assign('admin_topmenu', $topmenu); - - $smarty->assign('headtext', self::get_instance()->headtext); - $smarty->assign_by_ref('theme_object', self::get_instance()); - - $smarty->display(self::get_instance()->theme_template_dir . 'overall.tpl'); - - //Now that it's all done, send out an event telling everyone - CmsEventOperations::send_event('Core', 'AdminDisplayFinish'); - - if (CmsConfig::get('debug')) - { - echo '<div id="_DebugFooter">'; - echo CmsProfiler::get_instance()->report(); - echo '</div> <!-- end DebugFooter -->'; - } - } - - static public function inject_header_text($text) - { - $instance = self::get_instance(); - $instance->headtext .= $text; - } - - public function ShowHeader($title_name, $extra_lang_param=array(), $link_text = '', $module_help_type = FALSE) - { - return $this->show_header($title_name, $extra_lang_param, $link_text, $module_help_type); - } - - public function show_header($title_name, $extra_lang_param=array(), $link_text = '', $module_help_type = FALSE) - { - $cms = cmsms(); - $config = cms_config(); - $header = '<div class="pageheader">'; - if (FALSE != $module_help_type) - { - $header .= $title_name; - } - else - { - $header .= lang($title_name, $extra_lang_param); - } - if (FALSE == empty($this->breadcrumbs)) - { - $wikiUrl = $config['wiki_url']; - // Include English translation of titles. (Can't find better way to get them) - $dirname = dirname(__FILE__); - foreach ($this->breadcrumbs AS $key => $value) - { - $title = $value['title']; - // If this is a module and the last part of the breadcrumbs - if (FALSE != $module_help_type && TRUE == empty($this->breadcrumbs[$key + 1])) - { - $help_title = $title; - if (FALSE == empty($_GET['module'])) - { - $module_name = $_GET['module']; - } - else - { - $module_name = substr($_REQUEST['mact'], 0, strpos($_REQUEST['mact'], ',')); - } - // Turn ModuleName into _Module_Name - $moduleName = preg_replace('/([A-Z])/', "_$1", $module_name); - $moduleName = preg_replace('/_([A-Z])_/', "$1", $moduleName); - if ($moduleName{0} == '_') - { - $moduleName = substr($moduleName, 1); - } - $wikiUrl .= '/'.$moduleName; - } - else - { - // Remove colon and following (I.E. Turn "Edit Page: Title" into "Edit Page") - $colonLocation = strrchr($title, ':'); - if ($colonLocation !== false) - { - $title = substr($title,0,strpos($title,':')); - } - // Get the key of the title so we can use the en_US version for the URL - $node = CmsAdminTree::find_node_by_title($title); - if ($node) - { - $wikiUrl .= '/'. CmsLanguage::translate($node->english_title, array(), 'core', 'en_US'); - $help_title = $title; - } - } - } - if (FALSE == get_preference($this->userid, 'hide_help_links')) - { - // Clean up URL - $wikiUrl = str_replace(' ', '_', $wikiUrl); - $wikiUrl = str_replace('&amp;', 'and', $wikiUrl); - // Make link to go the translated version of page if lang is not en_US - /* Disabled as suggested by westis - $lang = get_preference($this->cms->variables['user_id'], 'default_cms_language'); - if ($lang != 'en_US') { - $wikiUrl .= '/'.substr($lang, 0, 2); - } - */ - if (FALSE == empty($link_text)) - { - $help_title = $link_text; - } - else - { - $help_title = lang('help_external'); - } - $image_help = $this->DisplayImage('icons/system/info.gif', lang('help'),'','','systemicon'); - $image_help_external = $this->DisplayImage('icons/system/info-external.gif', lang('help'),'','','systemicon'); - if ('both' == $module_help_type) - { - $module_help_link = $config['root_url'].'/'.$config['admin_dir'].'/listmodules.php?action=showmodulehelp&amp;module='.$module_name; - $header .= '<span class="helptext"><a href="'.$module_help_link.'">'.$image_help.'</a> <a href="'.$module_help_link.'">'.lang('help').'</a> | '; - $header .= '<a href="'.$wikiUrl.'" rel="external">'.$image_help_external.'</a> <a href="'.$wikiUrl.'" rel="external">'.lang('wikihelp').'</a> ('.lang('new_window').')</span>'; - } - else - { - $header .= '<span class="helptext"><a href="'.$wikiUrl.'" rel="external">'.$image_help_external.'</a> <a href="'.$wikiUrl.'" rel="external">'.lang('help').'</a> ('.lang('new_window').')</span>'; - } - } - } - $header .= '</div>'; - return $header; - } - - /** - * BackUrl - * "Back" Url - link to the next-to-last item in the breadcrumbs - * for the back button. - */ - public function back_url() - { - $count = count($this->breadcrumbs) - 2; - if ($count > -1) - { - return $this->breadcrumbs[$count]['url']; - } - else - { - return ''; - } - } - - public function BackURL() - { - return $this->back_url(); - } - - /** - * PopulateAdminNavigation - * This method populates a big array containing the Navigation Taxonomy - * for the admin section. This array is then used to create menus and - * section main pages. It uses aggregate permissions to hide sections for which - * the user doesn't have permissions, and highlights the current section so - * menus can show the user where they are. - * - * @param subtitle any info to add to the page title - * - */ - function populate_admin_navigation($subtitle='') - { - //Fill in the initial tree from the xml file - CmsAdminTree::fill_from_file($this); - - $this->subtitle = $subtitle; - - $root_path = CmsConfig::get('root_path'); - $root_url = CmsConfig::get('root_url'); - - //Add in modules and icons - $children = CmsAdminTree::get_instance()->get_root_node()->get_children(); - foreach ($children as &$basenode) - { - //Set icon for this item - $basenode->icon_url = $this->find_icon_url($basenode->name); - - //Set icons on children - $grandchildren = $basenode->get_children(); - foreach ($grandchildren as &$childnode) - { - $childnode->icon_url = $this->find_icon_url($childnode->name); - } - - $first = true; - foreach ($this->menu_list_section_modules($basenode->name) as $module) - { - $newnode = CmsAdminTree::get_instance()->create_node(); - $newnode->name = $module['name']; - $newnode->title = $module['title']; - $newnode->url = $module['url']; - $newnode->description = $module['description']; - $newnode->show_in_menu = true; - $newnode->first_module = $first; - $newnode->module = true; - - $imageSpec = $root_path . '/modules/' . $module['name'] . '/images/icon.gif'; - if (file_exists($imageSpec)) - { - $newnode->icon_url = $root_url . '/modules/' . $module['name'] . '/images/icon.gif'; - } - else - { - if (isset($basenode->icon)) - $newnode->icon_url = $basenode->icon; - } - - $basenode->add_child($newnode); - $first = false; - } - } - - //Now go through and find the selected - $flatlist = CmsAdminTree::get_instance()->get_flat_list(); - foreach ($flatlist as &$onenode) - { - if ($this->script == 'moduleinterface.php') - { - $a = preg_match('/(module|mact)=([^&,]+)/',$this->query,$matches); - if ($a > 0 && $matches[2] == $onenode->name) - { - $onenode->selected = true; - $this->title = $onenode->title; - $onenode->get_parent()->selected = true; - } - } - else if ($onenode->url == $this->script) - { - $onenode->selected = true; - $this->title = $onenode->title; - $onenode->get_parent()->selected = true; - } - } - - // fix subtitle, if any - if ($subtitle != '') - { - $this->title .= ': '.$subtitle; - } - - // generate breadcrumb array - $count = 0; - $flatlist = CmsAdminTree::get_instance()->get_flat_list(); - foreach ($flatlist as &$onenode) - { - if ($onenode->selected) - { - $this->breadcrumbs[] = array('title'=>$onenode->title, 'url'=>$onenode->url); - $count++; - } - } - - if ($count > 0) - { - // and fix up the last breadcrumb... - if ($this->query != '' && strpos($this->breadcrumbs[$count-1]['url'],'?') === false) - { - $this->query = preg_replace('/\&/','&amp;',$this->query); - $this->breadcrumbs[$count-1]['url'] .= '?'.$this->query; - } - if ($this->subtitle != '') - { - $this->breadcrumbs[$count-1]['title'] .= ': '.$this->subtitle; - } - } - } - - /** - * fix_spaces - * This method converts spaces into a non-breaking space HTML entity. - * It's used for making menus that work nicely - * - * @param str string to have its spaces converted - */ - function fix_spaces($str) - { - return preg_replace('/\s+/',"&nbsp;",$str); - } - /** - * unfix_spaces - * This method converts non-breaking space HTML entities into char(20)s. - * - * @param str string to have its spaces converted - */ - function unfix_spaces($str) - { - return preg_replace('/&nbsp;/'," ",$str); - } - - /** - * has_permission - * - * Check if the user has one of the aggregate permissions - * - * @param permission the permission to check. - */ - function has_permission($permission) - { - if (isset($this->perms[$permission]) && $this->perms[$permission]) - { - return true; - } - else - { - return false; - } - } - - /** - * SetModuleAdminInterfaces - * - * This function sets up data structures to place modules in the proper Admin sections - * for display on section pages and menus. - * - */ - function set_module_admin_interfaces() - { - # Are there any modules with an admin interface? - $cmsmodules = cmsms()->modules; - reset($cmsmodules); - while (list($key) = each($cmsmodules)) - { - $value =& $cmsmodules[$key]; - if (isset($cmsmodules[$key]['object']) - && $cmsmodules[$key]['installed'] == true - && $cmsmodules[$key]['active'] == true - && $cmsmodules[$key]['object']->has_admin() - && $cmsmodules[$key]['object']->visible_to_admin_user()) - { - foreach ($cmsmodules[$key]['object']->get_admin_menu_items() as $one_item) - { - $section = $one_item[3]; - if (! isset($this->section_count[$section])) - { - $this->section_count[$section] = 0; - } - $this->modules_by_section[$section][$this->section_count[$section]]['key'] = $key; - $this->modules_by_section[$section][$this->section_count[$section]]['name'] = $key; - $this->modules_by_section[$section][$this->section_count[$section]]['action'] = $one_item[2]; - $this->modules_by_section[$section][$this->section_count[$section]]['title'] = $one_item[0]; - if ($one_item[1] != '') - { - $this->modules_by_section[$section][$this->section_count[$section]]['description'] = $one_item[1]; - } - else - { - $this->modules_by_section[$section][$this->section_count[$section]]['description'] = ""; - } - $this->section_count[$section]++; - } - } - } - } - - /** - * menu_list_section_modules - * This method reformats module information for display in menus. When passed the - * name of the admin section, it returns an array of associations: - * array['module-name']['url'] is the link to that module, and - * array['module-name']['description'] is the language-specific short description of - * the module. - * - * @param section - section to display - */ - function menu_list_section_modules($section) - { - $modList = array(); - if (isset($this->section_count[$section]) && $this->section_count[$section] > 0) - { - # Sort modules by name - $names = array(); - foreach($this->modules_by_section[$section] as $key => $row) - { - $names[$key] = $this->modules_by_section[$section][$key]['name']; - } - array_multisort($names, SORT_ASC, $this->modules_by_section[$section]); - - foreach($this->modules_by_section[$section] as $sectionModule) - { - $modList[$sectionModule['key']]['url'] = "moduleinterface.php?mact={$sectionModule['key']},m1_,{$sectionModule['action']},0"; - $modList[$sectionModule['key']]['description'] = $sectionModule['description']; - $modList[$sectionModule['key']]['name'] = $sectionModule['name']; - $modList[$sectionModule['key']]['title'] = $sectionModule['title']; - } - } - return $modList; - } - - /** - * SetAggregatePermissions - * - * This function gathers disparate permissions to come up with the visibility of - * various admin sections, e.g., if there is any content-related operation for - * which a user has permissions, the aggregate content permission is granted, so - * that menu item is visible. - * - */ - function set_aggrigate_permissions() - { - # Content Permissions - $this->perms['htmlPerms'] = check_permission($this->userid, 'Add Global Content Blocks') | - check_permission($this->userid, 'Modify Global Content Blocks') | - check_permission($this->userid, 'Delete Global Content Blocks'); - - global $gCms; - $gcbops = $gCms->GetGlobalContentOperations(); - - $thisUserBlobs = $gcbops->AuthorBlobs($this->userid); - if (count($thisUserBlobs) > 0) - { - $this->perms['htmlPerms'] = true; - } - - $this->perms['pagePerms'] = ( - check_permission($this->userid, 'Modify Any Page') || - check_permission($this->userid, 'Add Pages') || - check_permission($this->userid, 'Remove Pages') || - check_permission($this->userid, 'Modify Page Structure') - ); - - $thisUserPages = array(); //TODO: Fix me!!! - if (count($thisUserPages) > 0) - { - $this->perms['pagePerms'] = true; - } - $this->perms['contentPerms'] = $this->perms['pagePerms'] | $this->perms['htmlPerms'] | - (isset($this->section_count['content']) && $this->section_count['content'] > 0); - - # layout - - $this->perms['templatePerms'] = check_permission($this->userid, 'Add Templates') | - check_permission($this->userid, 'Modify Templates') | - check_permission($this->userid, 'Remove Templates'); - $this->perms['cssPerms'] = check_permission($this->userid, 'Add Stylesheets') | - check_permission($this->userid, 'Modify Stylesheets') | - check_permission($this->userid, 'Remove Stylesheets'); - $this->perms['cssAssocPerms'] = check_permission($this->userid, 'Add Stylesheet Assoc') | - check_permission($this->userid, 'Modify Stylesheet Assoc') | - check_permission($this->userid, 'Remove Stylesheet Assoc'); - $this->perms['layoutPerms'] = $this->perms['templatePerms'] | - $this->perms['cssPerms'] | $this->perms['cssAssocPerms'] | - (isset($this->section_count['layout']) && $this->section_count['layout'] > 0); - - # file / image - $this->perms['filePerms'] = check_permission($this->userid, 'Modify Files') | - (isset($this->section_count['files']) && $this->section_count['files'] > 0); - - # user/group - $this->perms['userPerms'] = check_permission($this->userid, 'Add Users') | - check_permission($this->userid, 'Modify Users') | - check_permission($this->userid, 'Remove Users'); - $this->perms['groupPerms'] = check_permission($this->userid, 'Add Groups') | - check_permission($this->userid, 'Modify Groups') | - check_permission($this->userid, 'Remove Groups'); - $this->perms['groupPermPerms'] = check_permission($this->userid, 'Modify Permissions'); - $this->perms['groupMemberPerms'] = check_permission($this->userid, 'Modify Group Assignments'); - $this->perms['usersGroupsPerms'] = $this->perms['userPerms'] | - $this->perms['groupPerms'] | - $this->perms['groupPermPerms'] | - $this->perms['groupMemberPerms'] | - (isset($this->section_count['usersgroups']) && - $this->section_count['usersgroups'] > 0); - - # admin - $this->perms['sitePrefPerms'] = check_permission($this->userid, 'Modify Site Preferences') | - (isset($this->section_count['preferences']) && $this->section_count['preferences'] > 0); - $this->perms['adminPerms'] = $this->perms['sitePrefPerms'] | - (isset($this->section_count['admin']) && $this->section_count['admin'] > 0); - $this->perms['siteAdminPerms'] = $this->perms['sitePrefPerms'] | - $this->perms['adminPerms'] | - (isset($this->section_count['admin']) && - $this->section_count['admin'] > 0); - - - # extensions - $this->perms['codeBlockPerms'] = check_permission($this->userid, 'Modify User-defined Tags'); - $this->perms['modulePerms'] = check_permission($this->userid, 'Modify Modules'); - $this->perms['extensionsPerms'] = $this->perms['codeBlockPerms'] | - $this->perms['modulePerms'] | - (isset($this->section_count['extensions']) && $this->section_count['extensions'] > 0); - } - - /** - * has_displayable_children - * This method returns a boolean, based upon whether the section in question - * has displayable children. - * - * @param section - section to test - */ - function has_displayable_children(&$node) - { - $children = $node->get_children(); - foreach ($children as &$child) - { - if ($child->show_in_menu) - return true; - } - return false; - } - - /** - * DoBookmarks - * Method for displaying admin bookmarks (shortcuts) & help links. - * Smarty call in indexcontent.tpl {$admin_bookmarks} - */ - function show_bookmarks() - { - $smarty = cms_smarty(); - $marks = CmsBookmarkOperations::load_bookmarks($this->userid); - $smarty->assign('show_admin_shortcuts',get_preference($this->userid, 'bookmarks')); - $smarty->assign_by_ref('marks', $marks); - $smarty->display(self::get_instance()->theme_template_dir . 'bookmarks.tpl'); - } - /** - * DisplayDashboardCallout - * Outputs warning if the install directory is still there. - * - * @param file file or dir to check for - * @param message to display if it does exist - */ - function DisplayDashboardCallout() - { - $smarty = cms_smarty(); - - $install_file = dirname(dirname(dirname(__FILE__))) . '/install'; - $sitedown_file = TMP_CACHE_LOCATION . '/SITEDOWN'; - - $sitedown_message = lang('sitedownwarning', TMP_CACHE_LOCATION . '/SITEDOWN'); - $smarty->assign('sitedown_message', $sitedown_message); - - if (file_exists($install_file)) - { - $smarty->assign('install_warning', $install_file); - - } - if (file_exists($sitedown_file)) - { - $smarty->assign('sitedownwarning', $sitedown_file); - } - - } - - /** - * DisplayImage will display the themed version of an image (if it exists), - * or the version from the default theme otherwise. - * @param imageName - name of image - * @param alt - alt text - * @param width - * @param height - */ - function display_image($imageName, $alt='', $width='', $height='', $class='') - { - if (! isset($this->imageLink[$imageName])) - { - if (strpos($imageName,'/') !== false) - { - $imagePath = substr($imageName,0,strrpos($imageName,'/')+1); - $imageName = substr($imageName,strrpos($imageName,'/')+1); - } - else - { - $imagePath = ''; - } - - if (file_exists(dirname(CmsConfig::get('root_path') . '/' . CmsConfig::get('admin_dir') . - '/themes/' . $this->themeName . '/images/' . $imagePath . $imageName) . '/'. $imageName)) - { - $this->imageLink[$imageName] = 'themes/' . - $this->themeName . '/images/' . $imagePath . $imageName; - } - else - { - $this->imageLink[$imageName] = 'themes/default/images/' . $imagePath . $imageName; - } - } - - $retStr = '<img src="'.$this->imageLink[$imageName].'"'; - if ($class != '') - { - $retStr .= ' class="'.$class.'"'; - } - if ($width != '') - { - $retStr .= ' width="'.$width.'"'; - } - if ($height != '') - { - $retStr .= ' height="'.$height.'"'; - } - if ($alt != '') - { - $retStr .= ' alt="'.$alt.'" title="'.$alt.'"'; - } - $retStr .= ' />'; - return $retStr; - } - - function DisplayImage($imageName, $alt='', $width='', $height='', $class='') - { - return $this->display_image($imageName, $alt, $width, $height, $class); - } - - /** - * Returns a url to an icon for the given name. If the icon doesn't exist in - * the current theme, it gives the url for the default theme instead. - * - * @param string The name of the icon - * @return string The url to the icon - * @author Ted Kulp - **/ - function find_icon_url($name) - { - $name .= '.gif'; - if (file_exists(CmsConfig::get('root_path') . '/' . CmsConfig::get('admin_dir') . '/themes/' . $this->theme_name . '/images/icons/topfiles/' . $name)) - { - return CmsConfig::get('root_url') . '/' . CmsConfig::get('admin_dir') . '/themes/' . $this->theme_name . '/images/icons/topfiles/' . $name; - } - else - { - return CmsConfig::get('root_url') . '/' . CmsConfig::get('admin_dir') . '/themes/default/images/icons/topfiles/' . $name; - } - } - - /** - * Add error for display next time header is shown. If flash is true, - * this will display after a redirect. - * - * @param string The error message to display - * @param boolean Whether or not the message should persist after a redirect - * @return void - * @author Ted Kulp - **/ - public function add_error($error_string, $flash = false) - { - if ($flash) - { - if (!isset($_SESSION['errors'])) - $_SESSION['errors'] = array(); - $_SESSION['errors'][] = $error_string; - } - else - $this->errors[] = $error_string; - } - - public function has_errors() - { - return count($this->errors) > 0; - } - - /** - * Add message for display next time header is shown. If flash is true, - * this will display after a redirect. - * - * @param string The message to display - * @param boolean Whether or not the message should persist after a redirect - * @return void - * @author Ted Kulp - **/ - public function add_message($message_string, $flash = false) - { - if ($flash) - { - if (!isset($_SESSION['messages'])) - $_SESSION['messages'] = array(); - $_SESSION['messages'][] = $message_string; - } - else - $this->messages[] = $message_string; - } - - public function has_messages() - { - return count($this->messages) > 0; - } - - /** - * ShowError - * Outputs supplied errors with a link to the wiki for troublshooting. - * - * @param errors - array or string of 1 or more errors to be shown - * @param get_var - Name of the _GET variable that contains the - * name of the message lang string - */ - function show_errors($errors, $get_var='') - { - // todo: this should use a template in the admin theme - global $gCms; - $config =& $gCms->GetConfig(); - $wikiUrl = $config['wiki_url']; - - if (FALSE == empty($_REQUEST['module']) || FALSE == empty($_REQUEST['mact'])) - { - if (FALSE == empty($_REQUEST['module'])) - { - $wikiUrl .= '/'.$_REQUEST['module']; - } - else - { - $wikiUrl .= '/'.substr($_REQUEST['mact'], 0, strpos($_REQUEST['mact'], ',')); - } - } - $wikiUrl .= '/Troubleshooting'; - $wikiLink = ' <a href="'.$wikiUrl.'" rel="external">'.lang('troubleshooting').'</a>'; - if (FALSE != is_array($errors)) - { - $output = '<ul class="pageerrorcontainer">'; - foreach ($errors as $oneerror) - { - $output .= '<li>'.$oneerror.'</li>'; - } - $output .= '<li>'.$wikiLink.'</li>'; - $output .= '</ul>'; - } - else - { - $output = '<div class="pageerrorcontainer"'; - if (FALSE == empty($get_var)) - { - if (FALSE == empty($_GET[$get_var])) - { - $errors = cleanValue(lang(cleanValue($_GET[$get_var]))); - } - else - { - $errors = ''; - $output .= ' style="display:none;"'; - } - } - $output .= '><div class="pageoverflow">'; - $output .= $errors.$wikiLink.'</div></div>'; - } - return $output; - } - - function ShowErrors($errors, $get_var = '') - { - return $this->show_errors($errors, $get_var); - } - - /** - * ShowMessage - * Outputs a page status message - * - * @param message - Message to be shown - * @param get_var - Name of the _GET variable that contains the - * name of the message lang string - */ - function show_message($message, $get_var = '') - { - $output = '<div class="pagemcontainer"'; - if (FALSE == empty($get_var)) - { - if (FALSE == empty($_GET[$get_var])) - { - $message = lang(cleanValue($_GET[$get_var])); - } - else - { - $message = ''; - $output .= ' style="display:none;"'; - } - } - $output .= '><p class="pagemessage">'.$message.'</p></div>'; - return $output; - } - - function ShowMessage($message, $get_var = '') - { - return $this->show_message($message, $get_var); - } - - /** - * Display a warning if safe mode is enabled - * - * @return void - * @author Ted Kulp - */ - function safe_mode() - { - $smarty = cms_smarty(); - $safe_mode = ini_get_boolean('safe_mode') && CmsApplication::get_preference('disablesafemodewarning',0) == 0; - $smarty->assign('safe_mode', $safe_mode); - } - - /** - * Displays the list of sections and subitems for the main menu. - * - * @return void - * @author Ted Kulp - */ - function display_all_section_pages() - { - $smarty = cms_smarty(); - #Bookmark - @ob_start(); - self::get_instance()->show_bookmarks(); - $bookmarks = @ob_get_clean(); - $smarty->assign('admin_bookmarks', $bookmarks); - #DisplayDashboardCallout - //self::get_instance()->DisplayDashboardCallout(); - #safe_mode - //self::get_instance()->safe_mode(); - - - - $root_node = CmsAdminTree::get_instance()->get_root_node(); - $smarty->assign('subitems', lang('subitems')); - $smarty->assign_by_ref('root_node', $root_node); - $smarty->display(self::get_instance()->theme_template_dir . 'indexcontent.tpl'); - } - - /** - * Displays the subitems for the given section name. It's used for the - * admin "top*" pages. - * - * @param name The name of the section to display - * @return void - * @author Ted Kulp - **/ - function display_section_pages($section) - { - $children = CmsAdminTree::get_instance()->get_root_node()->get_children(); - $node = null; - foreach ($children as &$basenode) - { - if ($basenode->name == $section) - { - $node =& $basenode; - break; - } - } - - if ($node == null) - { - return; - } - - $smarty = cms_smarty(); - #Bookmark - @ob_start(); - self::get_instance()->show_bookmarks(); - $bookmarks = @ob_get_clean(); - $smarty->assign('admin_bookmarks', $bookmarks); - #end - - $smarty->assign_by_ref('top_node', $node); - $smarty->display(self::get_instance()->theme_template_dir . 'sectiontop.tpl'); - } - - /** - * Displays the html that makes up the admin menu. - * - * @return void - * @author Ted Kulp - **/ - function display_top_menu() - { - $smarty = cms_smarty(); - ###inject current user in top - $current_user = CmsLogin::get_current_user(); - $username = $current_user->name; - $smarty->assign('its_me',$username); - #end - $root_node = CmsAdminTree::get_instance()->get_root_node(); - $smarty->assign('admin_panel_title', lang('admin_panel_title')); - $smarty->assign_by_ref('root_node', $root_node); - $smarty->assign('breadcrumbs', $this->breadcrumbs); - $smarty->display(self::get_instance()->theme_template_dir . 'topmenu.tpl'); - } - - - ############################################################### - /** - * AddToDashboard - */ - function AddNotification($priority,$module,$html) - { - if( !is_array($this->_notificationitems) ) - { - $this->_notificationitems = array(array(),array(),array()); - } - if( $priority < 1 ) $priority = 1; - if( $priority > 3 ) $priority = 3; - - $this->_notificationitems[$priority-1][] = array($module,$html); - } - - function DisplayNotifications($priority=2) - { - if( !is_array($this->_notificationitems) ) return; - - // count the total number of notifications - $count=0; - for( $i = 1; $i <= $priority; $i++ ) - { - $count += count($this->_notificationitems[$i-1]); - } - $no_html_tags = preg_replace('/(<\/?)(\w+)([^>]*>)/e','',lang('notifications_to_handle',$count)); - echo '<div class="full-Notifications clear">'."\n"; - echo '<div class="Notifications-title">' . lang('notifications_to_handle',$count) . '</div>'."\n"; - echo '<div title="'.$no_html_tags.'" id="notifications-display" class="notifications-show" onclick="change(\'notifications-display\', \'notifications-hide\', \'notifications-show\'); change(\'notifications-container\', \'invisible\', \'visible\');"></div>'."\n"; - - echo '<div id="notifications-container" class="invisible">'."\n"; - echo "<ul id=\"Notifications-area\">\n"; - for( $i = 1; $i <= $priority; $i++ ) - { - if( count($this->_notificationitems) < $i ) break; - if( count($this->_notificationitems[$i-1]) == 0 ) continue; - foreach( $this->_notificationitems[$i-1] as $data ) - { - echo '<li class="NotificationsItem NotificationsPriority'.$i.'">'; - echo '<span class="NotificationsItemModuleName">'."\n"; - echo $data[0]."\n"; - echo "</span>\n"; - echo '<span class="NotificationsItemData">'."\n"; - echo $data[1]."\n"; - echo "</span>\n"; - echo '</li>'; - } - } - echo "</ul>"; - echo "</div><!-- notifications-container -->\n"; - echo "</div><!-- full-Notifications -->\n"; - echo "<div class=\"clearb\">&nbsp;</div>\n"; - } - - - - - ############################################################### - /* Functions that we want dont want the standard output from */ - function OutputFooterJavascript() {} -} - -# vim:ts=4 sw=4 noet -?> \ No newline at end of file
stechz/Loading-wheel
4a8c58ddf5ea41e7b8fe6d7551ae231ba7ca7433
Fix for skipping connecting phase.
diff --git a/demo_page/index.html b/demo_page/index.html index 7e9560f..eedc0a0 100644 --- a/demo_page/index.html +++ b/demo_page/index.html @@ -1,224 +1,225 @@ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Spinner Demo</title> </head> <style> html, body { font-family: sans-serif; margin: 0; padding: 1em; } body { background-color: #444444; } #window { background: url('images/window.png') no-repeat scroll top left; border: 1px solid #ababab; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; cursor:pointer; height: 330px; margin: auto; text-align: center; width: 927px; -moz-box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); -webkit-box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); } #window:hover { -moz-box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); -webkit-box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); } #window span { background-color:#666666; -webkit-border-radius: 1em; -moz-border-radius: 1em; border-radius: 1em; color:#FFFFFF; letter-spacing: 0.02em; padding:1em 1.4em; position:relative; text-shadow:0 -1px 0 #333333; top:189px; } #window:hover span { background-color:#555555; } canvas { background: transparent; display:block; left:220px; position:relative; top:27px; } </style> <body> <div id="window"> <canvas id="canvas" width="16" height="16"></canvas> <span>Click the window to activate the demo</span> </div> </body> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> var Spinner = function () { var _max_frames = 36; // number of frames in each spinning animation var _fade_length = 500; // length of fade between connecting and loading spinners, in ms var _ctx; // canvas 2d drawing context, if available var _frame; // frame number in current animation var _connecting; // image of connecting sprite var _loading; // image of loading sprite var _state; // state of the animation // 0 = idle // 1 = connecting // 2 = fading between connecting and loading // 3 = loading var _draw_interval = -1; // interval for drawing var _state_timeout = -1; // timer for changing state var _fade_beginning = 0; // when the fade was started last, in ms var me = this; this._init = function() { _frame = 0; _state = 0; _connecting = new Image(); _loading = new Image(); _connecting.src = 'images/connecting_sprite.png'; _loading.src = 'images/loading_sprite.png'; } this._advance_state = function() { _state = _state + 1; switch(_state) { case 1: // connecting me._clear_draw_interval(); _draw_interval = setInterval(me._draw, 27); me._clear_state_timeout(); - _state_timeout = setTimeout(me._advance_state, 400); + _state_timeout = setTimeout(me._advance_state, 1500); + break; case 2: // fading me._clear_state_timeout(); _state_timeout = setTimeout(me._advance_state, _fade_length); me._clear_draw_interval(); _draw_interval = setInterval(me._draw, 27); // remember when we started fading var d = new Date(); _fade_beginning = d.getTime(); break; case 3: // loading me._clear_state_timeout(); _state_timeout = setTimeout(me._advance_state, 2000); me._clear_draw_interval(); _draw_interval = setInterval(me._draw, 27); break; case 4: // end _state = 0; $("#window span").fadeIn(); break; } } this._clear_draw_interval = function() { if (_draw_interval != -1) { clearInterval(_draw_interval); } } this._clear_state_timeout = function() { if (_state_timeout != -1) { clearTimeout(_state_timeout); } } // return the alpha value to be used on the fade right now this._fade_alpha = function() { if (_fade_length == 0) return 0; var d = new Date(); var current_time = d.getTime(); return Math.min((current_time - _fade_beginning) / _fade_length, 1.0); } this._draw = function() { _frame = (_frame + 1) % _max_frames; _ctx.clearRect(0,0,16,16); switch(_state) { case 0: // idle break; case 1: // connecting _ctx.drawImage(_connecting, _frame * 16, 0, 16, 16, 0, 0, 16, 16); break; case 2: // fading from connecting to loading _ctx.drawImage(_connecting, _frame * 16, 0, 16, 16, 0, 0, 16, 16); _ctx.globalAlpha = me._fade_alpha(); _ctx.drawImage(_loading, _frame * 16, 0, 16, 16, 0, 0, 16, 16); _ctx.globalAlpha = 1.0; break; case 3: // loading _ctx.drawImage(_loading, _frame * 16, 0, 16, 16, 0, 0, 16, 16); break; } } this.start = function() { var canvas = document.getElementById('canvas'); if (canvas.getContext) { _ctx = canvas.getContext('2d'); _state = 0; _frame = 28; me._advance_state(); } } this._init(); } $(function(){ var theSpinner = new Spinner(); $("#window").click(function(){ theSpinner.start(); $("#window span").fadeOut(); }); }); </script> </html>
stechz/Loading-wheel
ea78bf2e15db3ca9f652d9ab29f7e3f7f6ab98ed
Added smooth transition between connecting and loading states.
diff --git a/demo_page/index.html b/demo_page/index.html index eb19d6d..7e9560f 100644 --- a/demo_page/index.html +++ b/demo_page/index.html @@ -1,137 +1,224 @@ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Spinner Demo</title> </head> <style> html, body { font-family: sans-serif; margin: 0; padding: 1em; } body { background-color: #444444; } #window { background: url('images/window.png') no-repeat scroll top left; border: 1px solid #ababab; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; cursor:pointer; height: 330px; margin: auto; text-align: center; width: 927px; -moz-box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); -webkit-box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); } #window:hover { -moz-box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); -webkit-box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); } #window span { background-color:#666666; -webkit-border-radius: 1em; -moz-border-radius: 1em; border-radius: 1em; color:#FFFFFF; letter-spacing: 0.02em; padding:1em 1.4em; position:relative; text-shadow:0 -1px 0 #333333; top:189px; } +#window:hover span { + background-color:#555555; +} + canvas { background: transparent; display:block; left:220px; position:relative; top:27px; } </style> <body> <div id="window"> <canvas id="canvas" width="16" height="16"></canvas> <span>Click the window to activate the demo</span> </div> </body> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> -var frame = 0; -var frame_fast = 0; -var frame_slow = 0; -var max_frames = 36; -var ctx; -var connecting = new Image(); -var loading = new Image(); +var Spinner = function () { + var _max_frames = 36; // number of frames in each spinning animation + var _fade_length = 500; // length of fade between connecting and loading spinners, in ms + + var _ctx; // canvas 2d drawing context, if available + var _frame; // frame number in current animation + var _connecting; // image of connecting sprite + var _loading; // image of loading sprite + var _state; // state of the animation + // 0 = idle + // 1 = connecting + // 2 = fading between connecting and loading + // 3 = loading + var _draw_interval = -1; // interval for drawing + var _state_timeout = -1; // timer for changing state + var _fade_beginning = 0; // when the fade was started last, in ms + + var me = this; + + this._init = function() { + _frame = 0; + _state = 0; + _connecting = new Image(); + _loading = new Image(); + + _connecting.src = 'images/connecting_sprite.png'; + _loading.src = 'images/loading_sprite.png'; + } + + this._advance_state = function() { + _state = _state + 1; + switch(_state) { + case 1: + // connecting + me._clear_draw_interval(); + _draw_interval = setInterval(me._draw, 27); + + me._clear_state_timeout(); + _state_timeout = setTimeout(me._advance_state, 400); + case 2: + // fading + me._clear_state_timeout(); + _state_timeout = setTimeout(me._advance_state, _fade_length); + me._clear_draw_interval(); + _draw_interval = setInterval(me._draw, 27); + + // remember when we started fading + var d = new Date(); + _fade_beginning = d.getTime(); + break; + case 3: + // loading + me._clear_state_timeout(); + _state_timeout = setTimeout(me._advance_state, 2000); + me._clear_draw_interval(); + _draw_interval = setInterval(me._draw, 27); + break; + case 4: + // end + _state = 0; + $("#window span").fadeIn(); + break; + } + } + + this._clear_draw_interval = function() { + if (_draw_interval != -1) { + clearInterval(_draw_interval); + } + } + + this._clear_state_timeout = function() { + if (_state_timeout != -1) { + clearTimeout(_state_timeout); + } + } -var state = 0; -// 0 = idle -// 1 = connecting -// 2 = loading + // return the alpha value to be used on the fade right now + this._fade_alpha = function() { + if (_fade_length == 0) + return 0; + var d = new Date(); + var current_time = d.getTime(); + return Math.min((current_time - _fade_beginning) / _fade_length, 1.0); + } -function draw() { - frame_fast = (frame_fast + 1) % max_frames; - if (frame_fast % 2 == 0) { - frame_slow = (frame_slow + 1) % max_frames; + this._draw = function() { + _frame = (_frame + 1) % _max_frames; + + _ctx.clearRect(0,0,16,16); + + switch(_state) { + case 0: + // idle + break; + case 1: + // connecting + _ctx.drawImage(_connecting, _frame * 16, 0, 16, 16, 0, 0, 16, 16); + break; + case 2: + // fading from connecting to loading + _ctx.drawImage(_connecting, _frame * 16, 0, 16, 16, 0, 0, 16, 16); + _ctx.globalAlpha = me._fade_alpha(); + _ctx.drawImage(_loading, _frame * 16, 0, 16, 16, 0, 0, 16, 16); + _ctx.globalAlpha = 1.0; + break; + case 3: + // loading + _ctx.drawImage(_loading, _frame * 16, 0, 16, 16, 0, 0, 16, 16); + break; + } } - ctx.clearRect(0,0,16,16); - - switch(state) { - case 0: - //idle - break; - case 1: - //connecting - ctx.drawImage(connecting, frame_slow * 16, 0, 16, 16, 0, 0, 16, 16); - break; - case 2: - //loading - ctx.drawImage(loading, frame_fast * 16, 0, 16, 16, 0, 0, 16, 16); + this.start = function() { + var canvas = document.getElementById('canvas'); + if (canvas.getContext) { + _ctx = canvas.getContext('2d'); + _state = 0; + _frame = 28; + me._advance_state(); + } } + + this._init(); } + + + + + $(function(){ - connecting.src = 'images/connecting_sprite.png'; - loading.src = 'images/loading_sprite.png'; + var theSpinner = new Spinner(); - var canvas = document.getElementById('canvas'); - if (canvas.getContext) { - ctx = canvas.getContext('2d'); - setInterval(draw, 27); - } $("#window").click(function(){ - state = (state + 1) % 3; - if (state == 1) { - // if we just switched from idle to connecting, start the animation at the top - frame_slow = 28; - } - if (state == 2) { - // if we just switched from connecting to loading, sync the animations - frame_fast = frame_slow; - } + theSpinner.start(); + $("#window span").fadeOut(); }); }); </script> </html>
stechz/Loading-wheel
4de88b967c1d518f33d37d1a1f3f72d110cb928a
Start the connecting animation on the proper frame.
diff --git a/demo_page/index.html b/demo_page/index.html index 16bfc9a..eb19d6d 100644 --- a/demo_page/index.html +++ b/demo_page/index.html @@ -1,137 +1,137 @@ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Spinner Demo</title> </head> <style> html, body { font-family: sans-serif; margin: 0; padding: 1em; } body { background-color: #444444; } #window { background: url('images/window.png') no-repeat scroll top left; border: 1px solid #ababab; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; cursor:pointer; height: 330px; margin: auto; text-align: center; width: 927px; -moz-box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); -webkit-box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); } #window:hover { -moz-box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); -webkit-box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); box-shadow: 0 0 30px rgba(0, 0, 0, 0.5); } #window span { background-color:#666666; -webkit-border-radius: 1em; -moz-border-radius: 1em; border-radius: 1em; color:#FFFFFF; letter-spacing: 0.02em; padding:1em 1.4em; position:relative; text-shadow:0 -1px 0 #333333; top:189px; } canvas { background: transparent; display:block; left:220px; position:relative; top:27px; } </style> <body> <div id="window"> <canvas id="canvas" width="16" height="16"></canvas> <span>Click the window to activate the demo</span> </div> </body> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> var frame = 0; var frame_fast = 0; var frame_slow = 0; var max_frames = 36; var ctx; var connecting = new Image(); var loading = new Image(); var state = 0; // 0 = idle // 1 = connecting // 2 = loading function draw() { frame_fast = (frame_fast + 1) % max_frames; if (frame_fast % 2 == 0) { frame_slow = (frame_slow + 1) % max_frames; } ctx.clearRect(0,0,16,16); switch(state) { case 0: //idle break; case 1: //connecting ctx.drawImage(connecting, frame_slow * 16, 0, 16, 16, 0, 0, 16, 16); break; case 2: //loading ctx.drawImage(loading, frame_fast * 16, 0, 16, 16, 0, 0, 16, 16); } } -function connect() { - frame_fast = frame_slow; -} - $(function(){ connecting.src = 'images/connecting_sprite.png'; loading.src = 'images/loading_sprite.png'; var canvas = document.getElementById('canvas'); if (canvas.getContext) { ctx = canvas.getContext('2d'); setInterval(draw, 27); } $("#window").click(function(){ state = (state + 1) % 3; + if (state == 1) { + // if we just switched from idle to connecting, start the animation at the top + frame_slow = 28; + } if (state == 2) { // if we just switched from connecting to loading, sync the animations frame_fast = frame_slow; } }); }); </script> </html>
msparks/arduino-ds1302
5650f7d13cfb2c5a28958a62a64c80a07f58a947
Fix incorrect reads from some DS1302 versions.
diff --git a/DS1302.cpp b/DS1302.cpp index 361c55f..24e9baa 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,238 +1,252 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" #include <stdint.h> namespace { enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7, // The RAM register space follows the clock register space. kRamAddress0 = 32 }; enum Command { kClockBurstRead = 0xBF, kClockBurstWrite = 0xBE, kRamBurstRead = 0xFF, kRamBurstWrite = 0xFE }; // Establishes and terminates a three-wire SPI session. class SPISession { public: SPISession(const int ce_pin, const int io_pin, const int sclk_pin) : ce_pin_(ce_pin), io_pin_(io_pin), sclk_pin_(sclk_pin) { digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); delayMicroseconds(4); // tCC } ~SPISession() { digitalWrite(ce_pin_, LOW); delayMicroseconds(4); // tCWH } private: const int ce_pin_; const int io_pin_; const int sclk_pin_; }; // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } // Returns the hour in 24-hour format from the hour register value. uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; + digitalWrite(ce_pin, LOW); pinMode(ce_pin, OUTPUT); + pinMode(io_pin, INPUT); + digitalWrite(sclk_pin, LOW); pinMode(sclk_pin, OUTPUT); } -void DS1302::writeOut(const uint8_t value) { +void DS1302::writeOut(const uint8_t value, bool readAfter) { pinMode(io_pin_, OUTPUT); - // This assumes that shiftOut is 'slow' enough for the DS1302 to read the - // bits. The datasheet specifies that SCLK must be in its high and low states - // for at least 0.25us at 5V or 1us at 2V. Experimentally, a 16MHz Arduino - // seems to spend ~4us high and ~12us low when shifting. - shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); + + for (int i = 0; i < 8; ++i) { + digitalWrite(io_pin_, (value >> i) & 1); + delayMicroseconds(1); + digitalWrite(sclk_pin_, HIGH); + delayMicroseconds(1); + + if (readAfter && i == 7) { + // We're about to read data -- ensure the pin is back in input mode + // before the clock is lowered. + pinMode(io_pin_, INPUT); + } else { + digitalWrite(sclk_pin_, LOW); + delayMicroseconds(1); + } + } } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); // Bits from the DS1302 are output on the falling edge of the clock - // cycle. This method is called after a previous call to writeOut() or - // readIn(), which will have already set the clock low. + // cycle. This is called after readIn (which will leave the clock low) or + // writeOut(..., true) (which will leave it high). for (int i = 0; i < 8; ++i) { - bit = digitalRead(io_pin_); - input_value |= (bit << i); // Bits are read LSB first. - - // See the note in writeOut() about timing. digitalWrite() is slow enough to - // not require extra delays for tCH and tCL. digitalWrite(sclk_pin_, HIGH); + delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); + delayMicroseconds(1); + + bit = digitalRead(io_pin_); + input_value |= (bit << i); // Bits are read LSB first. } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x81 | (reg << 1)); - writeOut(cmd_byte); + writeOut(cmd_byte, true); return readIn(); } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x80 | (reg << 1)); writeOut(cmd_byte); writeOut(value); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { const SPISession s(ce_pin_, io_pin_, sclk_pin_); Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); - writeOut(kClockBurstRead); + writeOut(kClockBurstRead, true); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kClockBurstWrite); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); // All clock registers *and* the WP register have to be written for the time // to be set. writeOut(0); // Write protection register. } void DS1302::writeRam(const uint8_t address, const uint8_t value) { if (address >= kRamSize) { return; } writeRegister(kRamAddress0 + address, value); } uint8_t DS1302::readRam(const uint8_t address) { if (address >= kRamSize) { return 0; } return readRegister(kRamAddress0 + address); } void DS1302::writeRamBulk(const uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kRamBurstWrite); for (int i = 0; i < len; ++i) { writeOut(data[i]); } } void DS1302::readRamBulk(uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); - writeOut(kRamBurstRead); + writeOut(kRamBurstRead, true); for (int i = 0; i < len; ++i) { data[i] = readIn(); } } diff --git a/DS1302.h b/DS1302.h index c7d6cad..d683fcb 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,186 +1,188 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ #include <stdint.h> // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // An interface to the Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. // // Accessing and setting individual components of the time are not supported in // this interface as doing so can lead to errors if the time changes as it is // being read or modified. Instead, using DS1302::time() guarantees safe reads // and writes using the DS1302's burst mode feature. class DS1302 { public: // Size of the DS1302's RAM storage, in bytes. static const int kRamSize = 31; // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Enables or disables write protection on the chip. // // While write protection is enabled, all attempts to write to the chip (e.g., // setting the time) will have no effect. // // The DS1302 datasheet does not define the initial state of write protection, // so this method should be called at least once when initializing a device // for the first time. // // Args: // enable: true to enable write protection. void writeProtect(bool enable); // Sets or clears Clock Halt flag on the chip. // // Enabling the Clock Halt flag disables the DS1302's clock oscillator and // places it into a low-power standby mode. While in this mode, the time does // not progress. The time can still be read from the chip while it is halted, // however. // // The DS1302 datasheet does not define the initial state of the Clock Halt // flag, so this method should be called at least once when initializing a // device for the first time. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Sets the time and date to the instant specified in a given Time object. // // The time will not be set if write protection is enabled on the // chip. Setting the time with this function has no effect on the Clock Halt // flag. // // Args: // t: Time instant. void time(Time t); // Writes a byte to RAM. // // The DS1302 has 31 bytes (kRamSize) of static RAM that can store arbitrary // data as long as the device has power. // // Writes to invalid addresses have no effect. // // Args: // address: RAM address in [0, kRamSize). // value: Byte to write to the RAM address. void writeRam(uint8_t address, uint8_t value); // Reads a byte from RAM. // // Reads of invalid addresses return 0. // // Args: // address: RAM address in [0, kRamSize). // // Returns: // Byte from RAM or 0 if the address is invalid. uint8_t readRam(uint8_t address); // Writes 'len' bytes into RAM from '*data', starting at RAM address 0. // // Args: // data: Input data. // len: Number of bytes of '*data' to read. Must be <= kRamSize. void writeRamBulk(const uint8_t* data, int len); // Reads 'len' bytes from RAM into '*data', starting at RAM address 0. // // Args: // data: Output data. // len: Number of bytes of RAM to read. Must be <= kRamSize. void readRamBulk(uint8_t* data, int len); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(uint8_t reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(uint8_t reg, uint8_t value); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out - void writeOut(uint8_t value); + // readAfter: whether this will be followed by a read; if so, it + // will leave io_pin_ as INPUT. + void writeOut(uint8_t value, bool readAfter = false); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); }; #endif // DS1302_H_
msparks/arduino-ds1302
8f8948fb97f2042640d38caf003693b723289611
Add a few comments.
diff --git a/DS1302.cpp b/DS1302.cpp index 3c978f7..361c55f 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,235 +1,238 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" #include <stdint.h> namespace { enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7, // The RAM register space follows the clock register space. kRamAddress0 = 32 }; enum Command { kClockBurstRead = 0xBF, kClockBurstWrite = 0xBE, kRamBurstRead = 0xFF, kRamBurstWrite = 0xFE }; // Establishes and terminates a three-wire SPI session. class SPISession { public: SPISession(const int ce_pin, const int io_pin, const int sclk_pin) : ce_pin_(ce_pin), io_pin_(io_pin), sclk_pin_(sclk_pin) { digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); delayMicroseconds(4); // tCC } ~SPISession() { digitalWrite(ce_pin_, LOW); delayMicroseconds(4); // tCWH } private: const int ce_pin_; const int io_pin_; const int sclk_pin_; }; // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } +// Returns the hour in 24-hour format from the hour register value. uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); // This assumes that shiftOut is 'slow' enough for the DS1302 to read the // bits. The datasheet specifies that SCLK must be in its high and low states // for at least 0.25us at 5V or 1us at 2V. Experimentally, a 16MHz Arduino // seems to spend ~4us high and ~12us low when shifting. shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); // Bits from the DS1302 are output on the falling edge of the clock // cycle. This method is called after a previous call to writeOut() or // readIn(), which will have already set the clock low. for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); // Bits are read LSB first. // See the note in writeOut() about timing. digitalWrite() is slow enough to // not require extra delays for tCH and tCL. digitalWrite(sclk_pin_, HIGH); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x81 | (reg << 1)); writeOut(cmd_byte); return readIn(); } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x80 | (reg << 1)); writeOut(cmd_byte); writeOut(value); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { const SPISession s(ce_pin_, io_pin_, sclk_pin_); Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); writeOut(kClockBurstRead); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kClockBurstWrite); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); + // All clock registers *and* the WP register have to be written for the time + // to be set. writeOut(0); // Write protection register. } void DS1302::writeRam(const uint8_t address, const uint8_t value) { if (address >= kRamSize) { return; } writeRegister(kRamAddress0 + address, value); } uint8_t DS1302::readRam(const uint8_t address) { if (address >= kRamSize) { return 0; } return readRegister(kRamAddress0 + address); } void DS1302::writeRamBulk(const uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kRamBurstWrite); for (int i = 0; i < len; ++i) { writeOut(data[i]); } } void DS1302::readRamBulk(uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kRamBurstRead); for (int i = 0; i < len; ++i) { data[i] = readIn(); } }
msparks/arduino-ds1302
7ac4e7e069df77094f3143860d64beed15bdb580
Bounds check in terms of kRamSize.
diff --git a/DS1302.cpp b/DS1302.cpp index 42ba2b0..3c978f7 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,239 +1,235 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" #include <stdint.h> namespace { enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7, // The RAM register space follows the clock register space. kRamAddress0 = 32 }; enum Command { kClockBurstRead = 0xBF, kClockBurstWrite = 0xBE, kRamBurstRead = 0xFF, kRamBurstWrite = 0xFE }; // Establishes and terminates a three-wire SPI session. class SPISession { public: SPISession(const int ce_pin, const int io_pin, const int sclk_pin) : ce_pin_(ce_pin), io_pin_(io_pin), sclk_pin_(sclk_pin) { digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); delayMicroseconds(4); // tCC } ~SPISession() { digitalWrite(ce_pin_, LOW); delayMicroseconds(4); // tCWH } private: const int ce_pin_; const int io_pin_; const int sclk_pin_; }; // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } -const int DS1302::kRamSize = 31; - DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); // This assumes that shiftOut is 'slow' enough for the DS1302 to read the // bits. The datasheet specifies that SCLK must be in its high and low states // for at least 0.25us at 5V or 1us at 2V. Experimentally, a 16MHz Arduino // seems to spend ~4us high and ~12us low when shifting. shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); // Bits from the DS1302 are output on the falling edge of the clock // cycle. This method is called after a previous call to writeOut() or // readIn(), which will have already set the clock low. for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); // Bits are read LSB first. // See the note in writeOut() about timing. digitalWrite() is slow enough to // not require extra delays for tCH and tCL. digitalWrite(sclk_pin_, HIGH); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x81 | (reg << 1)); writeOut(cmd_byte); return readIn(); } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x80 | (reg << 1)); writeOut(cmd_byte); writeOut(value); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { const SPISession s(ce_pin_, io_pin_, sclk_pin_); Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); writeOut(kClockBurstRead); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kClockBurstWrite); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. } void DS1302::writeRam(const uint8_t address, const uint8_t value) { - // Only RAM addresses in [0, 30] are valid. - if (address > 30) { + if (address >= kRamSize) { return; } writeRegister(kRamAddress0 + address, value); } uint8_t DS1302::readRam(const uint8_t address) { - // Only RAM addresses in [0, 30] are valid. - if (address > 30) { + if (address >= kRamSize) { return 0; } return readRegister(kRamAddress0 + address); } void DS1302::writeRamBulk(const uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kRamBurstWrite); for (int i = 0; i < len; ++i) { writeOut(data[i]); } } void DS1302::readRamBulk(uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kRamBurstRead); for (int i = 0; i < len; ++i) { data[i] = readIn(); } } diff --git a/DS1302.h b/DS1302.h index 2626732..c7d6cad 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,186 +1,186 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ #include <stdint.h> // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // An interface to the Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. // // Accessing and setting individual components of the time are not supported in // this interface as doing so can lead to errors if the time changes as it is // being read or modified. Instead, using DS1302::time() guarantees safe reads // and writes using the DS1302's burst mode feature. class DS1302 { public: // Size of the DS1302's RAM storage, in bytes. - static const int kRamSize; + static const int kRamSize = 31; // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Enables or disables write protection on the chip. // // While write protection is enabled, all attempts to write to the chip (e.g., // setting the time) will have no effect. // // The DS1302 datasheet does not define the initial state of write protection, // so this method should be called at least once when initializing a device // for the first time. // // Args: // enable: true to enable write protection. void writeProtect(bool enable); // Sets or clears Clock Halt flag on the chip. // // Enabling the Clock Halt flag disables the DS1302's clock oscillator and // places it into a low-power standby mode. While in this mode, the time does // not progress. The time can still be read from the chip while it is halted, // however. // // The DS1302 datasheet does not define the initial state of the Clock Halt // flag, so this method should be called at least once when initializing a // device for the first time. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Sets the time and date to the instant specified in a given Time object. // // The time will not be set if write protection is enabled on the // chip. Setting the time with this function has no effect on the Clock Halt // flag. // // Args: // t: Time instant. void time(Time t); // Writes a byte to RAM. // // The DS1302 has 31 bytes (kRamSize) of static RAM that can store arbitrary // data as long as the device has power. // // Writes to invalid addresses have no effect. // // Args: - // address: RAM address in [0, 30]. + // address: RAM address in [0, kRamSize). // value: Byte to write to the RAM address. void writeRam(uint8_t address, uint8_t value); // Reads a byte from RAM. // // Reads of invalid addresses return 0. // // Args: - // address: RAM address in [0, 30]. + // address: RAM address in [0, kRamSize). // // Returns: // Byte from RAM or 0 if the address is invalid. uint8_t readRam(uint8_t address); // Writes 'len' bytes into RAM from '*data', starting at RAM address 0. // // Args: // data: Input data. // len: Number of bytes of '*data' to read. Must be <= kRamSize. void writeRamBulk(const uint8_t* data, int len); // Reads 'len' bytes from RAM into '*data', starting at RAM address 0. // // Args: // data: Output data. // len: Number of bytes of RAM to read. Must be <= kRamSize. void readRamBulk(uint8_t* data, int len); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(uint8_t reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(uint8_t reg, uint8_t value); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); }; #endif // DS1302_H_
msparks/arduino-ds1302
57f9566be2d294c95ba8418098167ef15d338fdf
Use Register value for RAM offset.
diff --git a/DS1302.cpp b/DS1302.cpp index 651f347..42ba2b0 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,239 +1,239 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" #include <stdint.h> namespace { -// The RAM register space follows the clock register space. -const uint8_t kRamRegisterOffset = 32; - enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, - kWriteProtectReg = 7 + kWriteProtectReg = 7, + + // The RAM register space follows the clock register space. + kRamAddress0 = 32 }; enum Command { kClockBurstRead = 0xBF, kClockBurstWrite = 0xBE, kRamBurstRead = 0xFF, kRamBurstWrite = 0xFE }; // Establishes and terminates a three-wire SPI session. class SPISession { public: SPISession(const int ce_pin, const int io_pin, const int sclk_pin) : ce_pin_(ce_pin), io_pin_(io_pin), sclk_pin_(sclk_pin) { digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); delayMicroseconds(4); // tCC } ~SPISession() { digitalWrite(ce_pin_, LOW); delayMicroseconds(4); // tCWH } private: const int ce_pin_; const int io_pin_; const int sclk_pin_; }; // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } const int DS1302::kRamSize = 31; DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); // This assumes that shiftOut is 'slow' enough for the DS1302 to read the // bits. The datasheet specifies that SCLK must be in its high and low states // for at least 0.25us at 5V or 1us at 2V. Experimentally, a 16MHz Arduino // seems to spend ~4us high and ~12us low when shifting. shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); // Bits from the DS1302 are output on the falling edge of the clock // cycle. This method is called after a previous call to writeOut() or // readIn(), which will have already set the clock low. for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); // Bits are read LSB first. // See the note in writeOut() about timing. digitalWrite() is slow enough to // not require extra delays for tCH and tCL. digitalWrite(sclk_pin_, HIGH); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x81 | (reg << 1)); writeOut(cmd_byte); return readIn(); } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x80 | (reg << 1)); writeOut(cmd_byte); writeOut(value); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { const SPISession s(ce_pin_, io_pin_, sclk_pin_); Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); writeOut(kClockBurstRead); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kClockBurstWrite); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. } void DS1302::writeRam(const uint8_t address, const uint8_t value) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return; } - writeRegister(kRamRegisterOffset + address, value); + writeRegister(kRamAddress0 + address, value); } uint8_t DS1302::readRam(const uint8_t address) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return 0; } - return readRegister(kRamRegisterOffset + address); + return readRegister(kRamAddress0 + address); } void DS1302::writeRamBulk(const uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kRamBurstWrite); for (int i = 0; i < len; ++i) { writeOut(data[i]); } } void DS1302::readRamBulk(uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kRamBurstRead); for (int i = 0; i < len; ++i) { data[i] = readIn(); } }
msparks/arduino-ds1302
fe85203b8db0979a05dbc60dd8a56dc113d8a54f
Add notes about timing.
diff --git a/DS1302.cpp b/DS1302.cpp index f690df4..651f347 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,230 +1,239 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" #include <stdint.h> namespace { // The RAM register space follows the clock register space. const uint8_t kRamRegisterOffset = 32; enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; enum Command { kClockBurstRead = 0xBF, kClockBurstWrite = 0xBE, kRamBurstRead = 0xFF, kRamBurstWrite = 0xFE }; // Establishes and terminates a three-wire SPI session. class SPISession { public: SPISession(const int ce_pin, const int io_pin, const int sclk_pin) : ce_pin_(ce_pin), io_pin_(io_pin), sclk_pin_(sclk_pin) { digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); delayMicroseconds(4); // tCC } ~SPISession() { digitalWrite(ce_pin_, LOW); + delayMicroseconds(4); // tCWH } private: const int ce_pin_; const int io_pin_; const int sclk_pin_; }; // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } const int DS1302::kRamSize = 31; DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); + // This assumes that shiftOut is 'slow' enough for the DS1302 to read the + // bits. The datasheet specifies that SCLK must be in its high and low states + // for at least 0.25us at 5V or 1us at 2V. Experimentally, a 16MHz Arduino + // seems to spend ~4us high and ~12us low when shifting. shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); + // Bits from the DS1302 are output on the falling edge of the clock + // cycle. This method is called after a previous call to writeOut() or + // readIn(), which will have already set the clock low. for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); - input_value |= (bit << i); + input_value |= (bit << i); // Bits are read LSB first. + // See the note in writeOut() about timing. digitalWrite() is slow enough to + // not require extra delays for tCH and tCL. digitalWrite(sclk_pin_, HIGH); - delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x81 | (reg << 1)); writeOut(cmd_byte); return readIn(); } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { const SPISession s(ce_pin_, io_pin_, sclk_pin_); const uint8_t cmd_byte = (0x80 | (reg << 1)); writeOut(cmd_byte); writeOut(value); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { const SPISession s(ce_pin_, io_pin_, sclk_pin_); Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); writeOut(kClockBurstRead); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kClockBurstWrite); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. } void DS1302::writeRam(const uint8_t address, const uint8_t value) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return; } writeRegister(kRamRegisterOffset + address, value); } uint8_t DS1302::readRam(const uint8_t address) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return 0; } return readRegister(kRamRegisterOffset + address); } void DS1302::writeRamBulk(const uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kRamBurstWrite); for (int i = 0; i < len; ++i) { writeOut(data[i]); } } void DS1302::readRamBulk(uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } const SPISession s(ce_pin_, io_pin_, sclk_pin_); writeOut(kRamBurstRead); for (int i = 0; i < len; ++i) { data[i] = readIn(); } }
msparks/arduino-ds1302
e5e3f4bd5e102e56ab83b87c9066930c51105b12
Add SPISession helper class.
diff --git a/DS1302.cpp b/DS1302.cpp index 85f6a5f..f690df4 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,235 +1,230 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" #include <stdint.h> namespace { // The RAM register space follows the clock register space. const uint8_t kRamRegisterOffset = 32; enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; enum Command { kClockBurstRead = 0xBF, kClockBurstWrite = 0xBE, kRamBurstRead = 0xFF, kRamBurstWrite = 0xFE }; +// Establishes and terminates a three-wire SPI session. +class SPISession { + public: + SPISession(const int ce_pin, const int io_pin, const int sclk_pin) + : ce_pin_(ce_pin), io_pin_(io_pin), sclk_pin_(sclk_pin) { + digitalWrite(sclk_pin_, LOW); + digitalWrite(ce_pin_, HIGH); + delayMicroseconds(4); // tCC + } + ~SPISession() { + digitalWrite(ce_pin_, LOW); + } + + private: + const int ce_pin_; + const int io_pin_; + const int sclk_pin_; +}; + // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } const int DS1302::kRamSize = 31; DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { - const uint8_t cmd_byte = (0x81 | (reg << 1)); - - digitalWrite(sclk_pin_, LOW); - digitalWrite(ce_pin_, HIGH); + const SPISession s(ce_pin_, io_pin_, sclk_pin_); + const uint8_t cmd_byte = (0x81 | (reg << 1)); writeOut(cmd_byte); - const uint8_t reg_value = readIn(); - - digitalWrite(ce_pin_, LOW); - - return reg_value; + return readIn(); } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { - const uint8_t cmd_byte = (0x80 | (reg << 1)); - - digitalWrite(sclk_pin_, LOW); - digitalWrite(ce_pin_, HIGH); + const SPISession s(ce_pin_, io_pin_, sclk_pin_); + const uint8_t cmd_byte = (0x80 | (reg << 1)); writeOut(cmd_byte); writeOut(value); - - digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { - Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); + const SPISession s(ce_pin_, io_pin_, sclk_pin_); - digitalWrite(sclk_pin_, LOW); - digitalWrite(ce_pin_, HIGH); + Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); writeOut(kClockBurstRead); - t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); - - digitalWrite(ce_pin_, LOW); - return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; - digitalWrite(sclk_pin_, LOW); - digitalWrite(ce_pin_, HIGH); - writeOut(kClockBurstWrite); + const SPISession s(ce_pin_, io_pin_, sclk_pin_); + writeOut(kClockBurstWrite); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. - - digitalWrite(ce_pin_, LOW); } void DS1302::writeRam(const uint8_t address, const uint8_t value) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return; } writeRegister(kRamRegisterOffset + address, value); } uint8_t DS1302::readRam(const uint8_t address) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return 0; } return readRegister(kRamRegisterOffset + address); } void DS1302::writeRamBulk(const uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } - digitalWrite(sclk_pin_, LOW); - digitalWrite(ce_pin_, HIGH); - writeOut(kRamBurstWrite); + const SPISession s(ce_pin_, io_pin_, sclk_pin_); + writeOut(kRamBurstWrite); for (int i = 0; i < len; ++i) { writeOut(data[i]); } - - digitalWrite(ce_pin_, LOW); } void DS1302::readRamBulk(uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } - digitalWrite(sclk_pin_, LOW); - digitalWrite(ce_pin_, HIGH); - writeOut(kRamBurstRead); + const SPISession s(ce_pin_, io_pin_, sclk_pin_); + writeOut(kRamBurstRead); for (int i = 0; i < len; ++i) { data[i] = readIn(); } - - digitalWrite(ce_pin_, LOW); }
msparks/arduino-ds1302
b6b3d03e5ad04200b5d06a2f7928ca0c06f26f2c
Clean up command bytes.
diff --git a/DS1302.cpp b/DS1302.cpp index 04127a7..85f6a5f 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,232 +1,235 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" #include <stdint.h> namespace { // The RAM register space follows the clock register space. const uint8_t kRamRegisterOffset = 32; enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; +enum Command { + kClockBurstRead = 0xBF, + kClockBurstWrite = 0xBE, + kRamBurstRead = 0xFF, + kRamBurstWrite = 0xFE +}; + // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } const int DS1302::kRamSize = 31; DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { - uint8_t cmd_byte = 129; // 1000 0001 - uint8_t reg_value; - cmd_byte |= (reg << 1); + const uint8_t cmd_byte = (0x81 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); - reg_value = readIn(); + const uint8_t reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { - uint8_t cmd_byte = (128 | (reg << 1)); + const uint8_t cmd_byte = (0x80 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); - const uint8_t cmd_byte = 0xBF; // Clock burst read. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); - writeOut(cmd_byte); + writeOut(kClockBurstRead); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); digitalWrite(ce_pin_, LOW); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; - const uint8_t cmd_byte = 0xBE; // Clock burst write. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); - writeOut(cmd_byte); + writeOut(kClockBurstWrite); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. digitalWrite(ce_pin_, LOW); } void DS1302::writeRam(const uint8_t address, const uint8_t value) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return; } writeRegister(kRamRegisterOffset + address, value); } uint8_t DS1302::readRam(const uint8_t address) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return 0; } return readRegister(kRamRegisterOffset + address); } void DS1302::writeRamBulk(const uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); - writeOut(0xFE); // RAM write in burst mode. + writeOut(kRamBurstWrite); for (int i = 0; i < len; ++i) { writeOut(data[i]); } digitalWrite(ce_pin_, LOW); } void DS1302::readRamBulk(uint8_t* const data, int len) { if (len <= 0) { return; } if (len > kRamSize) { len = kRamSize; } digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); - writeOut(0xFF); // RAM read in burst mode. + writeOut(kRamBurstRead); for (int i = 0; i < len; ++i) { data[i] = readIn(); } digitalWrite(ce_pin_, LOW); }
msparks/arduino-ds1302
13ba179f1fec8b17622f2d2a7e1994a9eb16524e
Implement burst RAM read and write.
diff --git a/DS1302.cpp b/DS1302.cpp index d384c16..04127a7 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,192 +1,232 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" #include <stdint.h> namespace { // The RAM register space follows the clock register space. const uint8_t kRamRegisterOffset = 32; enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } +const int DS1302::kRamSize = 31; + DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); const uint8_t cmd_byte = 0xBF; // Clock burst read. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); digitalWrite(ce_pin_, LOW); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const uint8_t cmd_byte = 0xBE; // Clock burst write. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. digitalWrite(ce_pin_, LOW); } void DS1302::writeRam(const uint8_t address, const uint8_t value) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return; } writeRegister(kRamRegisterOffset + address, value); } uint8_t DS1302::readRam(const uint8_t address) { // Only RAM addresses in [0, 30] are valid. if (address > 30) { return 0; } return readRegister(kRamRegisterOffset + address); } + +void DS1302::writeRamBulk(const uint8_t* const data, int len) { + if (len <= 0) { + return; + } + if (len > kRamSize) { + len = kRamSize; + } + + digitalWrite(sclk_pin_, LOW); + digitalWrite(ce_pin_, HIGH); + writeOut(0xFE); // RAM write in burst mode. + + for (int i = 0; i < len; ++i) { + writeOut(data[i]); + } + + digitalWrite(ce_pin_, LOW); +} + +void DS1302::readRamBulk(uint8_t* const data, int len) { + if (len <= 0) { + return; + } + if (len > kRamSize) { + len = kRamSize; + } + + digitalWrite(sclk_pin_, LOW); + digitalWrite(ce_pin_, HIGH); + writeOut(0xFF); // RAM read in burst mode. + + for (int i = 0; i < len; ++i) { + data[i] = readIn(); + } + + digitalWrite(ce_pin_, LOW); +} diff --git a/DS1302.h b/DS1302.h index 533d4b1..2626732 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,169 +1,186 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ #include <stdint.h> // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // An interface to the Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. // // Accessing and setting individual components of the time are not supported in // this interface as doing so can lead to errors if the time changes as it is // being read or modified. Instead, using DS1302::time() guarantees safe reads // and writes using the DS1302's burst mode feature. class DS1302 { public: + // Size of the DS1302's RAM storage, in bytes. + static const int kRamSize; + // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Enables or disables write protection on the chip. // // While write protection is enabled, all attempts to write to the chip (e.g., // setting the time) will have no effect. // // The DS1302 datasheet does not define the initial state of write protection, // so this method should be called at least once when initializing a device // for the first time. // // Args: // enable: true to enable write protection. void writeProtect(bool enable); // Sets or clears Clock Halt flag on the chip. // // Enabling the Clock Halt flag disables the DS1302's clock oscillator and // places it into a low-power standby mode. While in this mode, the time does // not progress. The time can still be read from the chip while it is halted, // however. // // The DS1302 datasheet does not define the initial state of the Clock Halt // flag, so this method should be called at least once when initializing a // device for the first time. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Sets the time and date to the instant specified in a given Time object. // // The time will not be set if write protection is enabled on the // chip. Setting the time with this function has no effect on the Clock Halt // flag. // // Args: // t: Time instant. void time(Time t); // Writes a byte to RAM. // - // The DS1302 has 31 bytes of static RAM that can store arbitrary data as long - // as the device has power. + // The DS1302 has 31 bytes (kRamSize) of static RAM that can store arbitrary + // data as long as the device has power. // // Writes to invalid addresses have no effect. // // Args: // address: RAM address in [0, 30]. // value: Byte to write to the RAM address. void writeRam(uint8_t address, uint8_t value); // Reads a byte from RAM. // // Reads of invalid addresses return 0. // // Args: // address: RAM address in [0, 30]. // // Returns: // Byte from RAM or 0 if the address is invalid. uint8_t readRam(uint8_t address); + // Writes 'len' bytes into RAM from '*data', starting at RAM address 0. + // + // Args: + // data: Input data. + // len: Number of bytes of '*data' to read. Must be <= kRamSize. + void writeRamBulk(const uint8_t* data, int len); + + // Reads 'len' bytes from RAM into '*data', starting at RAM address 0. + // + // Args: + // data: Output data. + // len: Number of bytes of RAM to read. Must be <= kRamSize. + void readRamBulk(uint8_t* data, int len); + // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(uint8_t reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(uint8_t reg, uint8_t value); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); }; #endif // DS1302_H_ diff --git a/examples/ram/ram.ino b/examples/ram/ram.ino index a4dc1a8..83e5c91 100644 --- a/examples/ram/ram.ino +++ b/examples/ram/ram.ino @@ -1,46 +1,50 @@ +#include <stdio.h> #include <DS1302.h> namespace { // Set the appropriate digital I/O pin connections. These are the pin // assignments for the Arduino as well for as the DS1302 chip. See the DS1302 // datasheet: // // http://datasheets.maximintegrated.com/en/ds/DS1302.pdf const int kCePin = 5; // Chip Enable const int kIoPin = 6; // Input/Output const int kSclkPin = 7; // Serial Clock DS1302 rtc(kCePin, kIoPin, kSclkPin); } // namespace void setup() { Serial.begin(9600); rtc.writeProtect(false); - // Clear all RAM bytes. - for (int i = 0; i < 31; ++i) { + // Clear all RAM bytes, using the byte interface. + for (int i = 0; i < DS1302::kRamSize; ++i) { rtc.writeRam(i, 0x00); } - // Write a string to the RAM. + // Write a string using the bulk interface. static const char kHelloWorld[] = "hello world"; - for (int i = 0; i < sizeof(kHelloWorld) - 1; ++i) { - rtc.writeRam(i, kHelloWorld[i]); - } + rtc.writeRamBulk((uint8_t*)kHelloWorld, sizeof(kHelloWorld) - 1); } void loop() { - // Read all of the RAM. - for (int i = 0; i < 31; ++i) { - const char c = static_cast<char>(rtc.readRam(i)); - Serial.print("RAM index "); - Serial.print(i); - Serial.print(": "); - Serial.println(c); + char buf[32]; + + // Print the RAM byte values as hex using the byte interface. + for (int i = 0; i < DS1302::kRamSize; ++i) { + snprintf(buf, sizeof(buf), "[%02X]", rtc.readRam(i)); + Serial.print(buf); } + Serial.println(); + + // Print the RAM byte values as ASCII using the bulk interface. + uint8_t ram[DS1302::kRamSize]; + rtc.readRamBulk(ram, DS1302::kRamSize); + Serial.println((const char*)ram); delay(3000); }
msparks/arduino-ds1302
5909e099211ae99333162880f76f850ef92eea65
Add RAM byte interface.
diff --git a/DS1302.cpp b/DS1302.cpp index dc6dd04..d384c16 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,171 +1,192 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" #include <stdint.h> namespace { +// The RAM register space follows the clock register space. +const uint8_t kRamRegisterOffset = 32; + enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); const uint8_t cmd_byte = 0xBF; // Clock burst read. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); digitalWrite(ce_pin_, LOW); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const uint8_t cmd_byte = 0xBE; // Clock burst write. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. digitalWrite(ce_pin_, LOW); } + +void DS1302::writeRam(const uint8_t address, const uint8_t value) { + // Only RAM addresses in [0, 30] are valid. + if (address > 30) { + return; + } + + writeRegister(kRamRegisterOffset + address, value); +} + +uint8_t DS1302::readRam(const uint8_t address) { + // Only RAM addresses in [0, 30] are valid. + if (address > 30) { + return 0; + } + + return readRegister(kRamRegisterOffset + address); +} diff --git a/DS1302.h b/DS1302.h index c7644b4..533d4b1 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,146 +1,169 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ #include <stdint.h> // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // An interface to the Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. // // Accessing and setting individual components of the time are not supported in // this interface as doing so can lead to errors if the time changes as it is // being read or modified. Instead, using DS1302::time() guarantees safe reads // and writes using the DS1302's burst mode feature. class DS1302 { public: // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Enables or disables write protection on the chip. // // While write protection is enabled, all attempts to write to the chip (e.g., // setting the time) will have no effect. // // The DS1302 datasheet does not define the initial state of write protection, // so this method should be called at least once when initializing a device // for the first time. // // Args: // enable: true to enable write protection. void writeProtect(bool enable); - // Set or clear Clock Halt flag on the chip. + // Sets or clears Clock Halt flag on the chip. // // Enabling the Clock Halt flag disables the DS1302's clock oscillator and // places it into a low-power standby mode. While in this mode, the time does // not progress. The time can still be read from the chip while it is halted, // however. // // The DS1302 datasheet does not define the initial state of the Clock Halt // flag, so this method should be called at least once when initializing a // device for the first time. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Sets the time and date to the instant specified in a given Time object. // // The time will not be set if write protection is enabled on the // chip. Setting the time with this function has no effect on the Clock Halt // flag. // // Args: // t: Time instant. void time(Time t); + // Writes a byte to RAM. + // + // The DS1302 has 31 bytes of static RAM that can store arbitrary data as long + // as the device has power. + // + // Writes to invalid addresses have no effect. + // + // Args: + // address: RAM address in [0, 30]. + // value: Byte to write to the RAM address. + void writeRam(uint8_t address, uint8_t value); + + // Reads a byte from RAM. + // + // Reads of invalid addresses return 0. + // + // Args: + // address: RAM address in [0, 30]. + // + // Returns: + // Byte from RAM or 0 if the address is invalid. + uint8_t readRam(uint8_t address); + // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(uint8_t reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(uint8_t reg, uint8_t value); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); }; #endif // DS1302_H_ diff --git a/examples/ram/ram.ino b/examples/ram/ram.ino new file mode 100644 index 0000000..a4dc1a8 --- /dev/null +++ b/examples/ram/ram.ino @@ -0,0 +1,46 @@ +#include <DS1302.h> + +namespace { + +// Set the appropriate digital I/O pin connections. These are the pin +// assignments for the Arduino as well for as the DS1302 chip. See the DS1302 +// datasheet: +// +// http://datasheets.maximintegrated.com/en/ds/DS1302.pdf +const int kCePin = 5; // Chip Enable +const int kIoPin = 6; // Input/Output +const int kSclkPin = 7; // Serial Clock + +DS1302 rtc(kCePin, kIoPin, kSclkPin); + +} // namespace + +void setup() { + Serial.begin(9600); + + rtc.writeProtect(false); + + // Clear all RAM bytes. + for (int i = 0; i < 31; ++i) { + rtc.writeRam(i, 0x00); + } + + // Write a string to the RAM. + static const char kHelloWorld[] = "hello world"; + for (int i = 0; i < sizeof(kHelloWorld) - 1; ++i) { + rtc.writeRam(i, kHelloWorld[i]); + } +} + +void loop() { + // Read all of the RAM. + for (int i = 0; i < 31; ++i) { + const char c = static_cast<char>(rtc.readRam(i)); + Serial.print("RAM index "); + Serial.print(i); + Serial.print(": "); + Serial.println(c); + } + + delay(3000); +}
msparks/arduino-ds1302
b84e5d22dea782a6691c4edbe12ac4b7aa4a4da8
Add missing stdint.h includes.
diff --git a/DS1302.cpp b/DS1302.cpp index c15cd44..dc6dd04 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,169 +1,171 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" +#include <stdint.h> + namespace { enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::readRegister(const uint8_t reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); const uint8_t cmd_byte = 0xBF; // Clock burst read. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); digitalWrite(ce_pin_, LOW); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const uint8_t cmd_byte = 0xBE; // Clock burst write. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. digitalWrite(ce_pin_, LOW); } diff --git a/DS1302.h b/DS1302.h index 3e71fff..c7644b4 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,144 +1,146 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ +#include <stdint.h> + // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // An interface to the Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. // // Accessing and setting individual components of the time are not supported in // this interface as doing so can lead to errors if the time changes as it is // being read or modified. Instead, using DS1302::time() guarantees safe reads // and writes using the DS1302's burst mode feature. class DS1302 { public: // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Enables or disables write protection on the chip. // // While write protection is enabled, all attempts to write to the chip (e.g., // setting the time) will have no effect. // // The DS1302 datasheet does not define the initial state of write protection, // so this method should be called at least once when initializing a device // for the first time. // // Args: // enable: true to enable write protection. void writeProtect(bool enable); // Set or clear Clock Halt flag on the chip. // // Enabling the Clock Halt flag disables the DS1302's clock oscillator and // places it into a low-power standby mode. While in this mode, the time does // not progress. The time can still be read from the chip while it is halted, // however. // // The DS1302 datasheet does not define the initial state of the Clock Halt // flag, so this method should be called at least once when initializing a // device for the first time. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Sets the time and date to the instant specified in a given Time object. // // The time will not be set if write protection is enabled on the // chip. Setting the time with this function has no effect on the Clock Halt // flag. // // Args: // t: Time instant. void time(Time t); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(uint8_t reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(uint8_t reg, uint8_t value); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); }; #endif // DS1302_H_
msparks/arduino-ds1302
50f1478718cc0bdb2e7cf9ef94c091ebd19391e8
Remove public clock register definitions.
diff --git a/DS1302.cpp b/DS1302.cpp index 49b6342..c15cd44 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,158 +1,169 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" namespace { +enum Register { + kSecondReg = 0, + kMinuteReg = 1, + kHourReg = 2, + kDateReg = 3, + kMonthReg = 4, + kDayReg = 5, + kYearReg = 6, + kWriteProtectReg = 7 +}; + // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } -uint8_t DS1302::readRegister(const Register reg) { +uint8_t DS1302::readRegister(const uint8_t reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } -void DS1302::writeRegister(const Register reg, const uint8_t value) { +void DS1302::writeRegister(const uint8_t reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); const uint8_t cmd_byte = 0xBF; // Clock burst read. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); digitalWrite(ce_pin_, LOW); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const uint8_t cmd_byte = 0xBE; // Clock burst write. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. digitalWrite(ce_pin_, LOW); } diff --git a/DS1302.h b/DS1302.h index 3ecfdef..3e71fff 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,155 +1,144 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // An interface to the Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. // // Accessing and setting individual components of the time are not supported in // this interface as doing so can lead to errors if the time changes as it is // being read or modified. Instead, using DS1302::time() guarantees safe reads // and writes using the DS1302's burst mode feature. class DS1302 { public: - enum Register { - kSecondReg = 0, - kMinuteReg = 1, - kHourReg = 2, - kDateReg = 3, - kMonthReg = 4, - kDayReg = 5, - kYearReg = 6, - kWriteProtectReg = 7 - }; - // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); - // Reads register byte value. - // - // Args: - // reg: register number - // - // Returns: - // register value - uint8_t readRegister(Register reg); - - // Writes byte into register. - // - // Args: - // reg: register number - // value: byte to write - void writeRegister(Register reg, uint8_t value); - // Enables or disables write protection on the chip. // // While write protection is enabled, all attempts to write to the chip (e.g., // setting the time) will have no effect. // // The DS1302 datasheet does not define the initial state of write protection, // so this method should be called at least once when initializing a device // for the first time. // // Args: // enable: true to enable write protection. void writeProtect(bool enable); // Set or clear Clock Halt flag on the chip. // // Enabling the Clock Halt flag disables the DS1302's clock oscillator and // places it into a low-power standby mode. While in this mode, the time does // not progress. The time can still be read from the chip while it is halted, // however. // // The DS1302 datasheet does not define the initial state of the Clock Halt // flag, so this method should be called at least once when initializing a // device for the first time. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Sets the time and date to the instant specified in a given Time object. // // The time will not be set if write protection is enabled on the // chip. Setting the time with this function has no effect on the Clock Halt // flag. // // Args: // t: Time instant. void time(Time t); + // Reads register byte value. + // + // Args: + // reg: register number + // + // Returns: + // register value + uint8_t readRegister(uint8_t reg); + + // Writes byte into register. + // + // Args: + // reg: register number + // value: byte to write + void writeRegister(uint8_t reg, uint8_t value); + private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); }; #endif // DS1302_H_
msparks/arduino-ds1302
03aa861865cd4306d17f42018beaa8655ffd2c4b
Remove dead code.
diff --git a/DS1302.cpp b/DS1302.cpp index 5a2e8d5..49b6342 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,177 +1,158 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" namespace { // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } -void DS1302::registerDecToBcd(const Register reg, uint8_t value, - const uint8_t high_bit) { - const uint8_t mask = (1 << (high_bit + 1)) - 1; - uint8_t regv = readRegister(reg); - - // Convert value to bcd in place. - value = decToBcd(value); - - // Replace high bits of register if needed. - value &= mask; - value |= (regv &= ~mask); - - writeRegister(reg, value); -} - -void DS1302::registerDecToBcd(const Register reg, const uint8_t value) { - registerDecToBcd(reg, value, 7); -} - uint8_t DS1302::readRegister(const Register reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } void DS1302::writeRegister(const Register reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } Time DS1302::time() { Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); const uint8_t cmd_byte = 0xBF; // Clock burst read. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); digitalWrite(ce_pin_, LOW); return t; } void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const uint8_t cmd_byte = 0xBE; // Clock burst write. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. digitalWrite(ce_pin_, LOW); } diff --git a/DS1302.h b/DS1302.h index eb21d32..3ecfdef 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,164 +1,155 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // An interface to the Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. // // Accessing and setting individual components of the time are not supported in // this interface as doing so can lead to errors if the time changes as it is // being read or modified. Instead, using DS1302::time() guarantees safe reads // and writes using the DS1302's burst mode feature. class DS1302 { public: enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(Register reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(Register reg, uint8_t value); // Enables or disables write protection on the chip. // // While write protection is enabled, all attempts to write to the chip (e.g., // setting the time) will have no effect. // // The DS1302 datasheet does not define the initial state of write protection, // so this method should be called at least once when initializing a device // for the first time. // // Args: // enable: true to enable write protection. void writeProtect(bool enable); // Set or clear Clock Halt flag on the chip. // // Enabling the Clock Halt flag disables the DS1302's clock oscillator and // places it into a low-power standby mode. While in this mode, the time does // not progress. The time can still be read from the chip while it is halted, // however. // // The DS1302 datasheet does not define the initial state of the Clock Halt // flag, so this method should be called at least once when initializing a // device for the first time. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Sets the time and date to the instant specified in a given Time object. // // The time will not be set if write protection is enabled on the // chip. Setting the time with this function has no effect on the Clock Halt // flag. // // Args: // t: Time instant. void time(Time t); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); - - // Sets a register with binary-coded decimal converted from a given value. - // - // Args: - // reg: register number - // value: decimal value to convert to BCD - // high_bit: highest bit in the register allowed to contain BCD value - void registerDecToBcd(Register reg, uint8_t value, uint8_t high_bit); - void registerDecToBcd(Register reg, uint8_t value); }; #endif // DS1302_H_
msparks/arduino-ds1302
995772e9ed303270cab9f02e2d8f5ba7da5e13fa
Add comments about write protection and halt flag.
diff --git a/DS1302.h b/DS1302.h index 9c1cdb1..eb21d32 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,144 +1,164 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // An interface to the Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. // // Accessing and setting individual components of the time are not supported in // this interface as doing so can lead to errors if the time changes as it is // being read or modified. Instead, using DS1302::time() guarantees safe reads // and writes using the DS1302's burst mode feature. class DS1302 { public: enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(Register reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(Register reg, uint8_t value); - // Enables or disables write protection on chip. + // Enables or disables write protection on the chip. + // + // While write protection is enabled, all attempts to write to the chip (e.g., + // setting the time) will have no effect. + // + // The DS1302 datasheet does not define the initial state of write protection, + // so this method should be called at least once when initializing a device + // for the first time. // // Args: - // enable: true to enable, false to disable. + // enable: true to enable write protection. void writeProtect(bool enable); - // Set or clear clock halt flag. + // Set or clear Clock Halt flag on the chip. + // + // Enabling the Clock Halt flag disables the DS1302's clock oscillator and + // places it into a low-power standby mode. While in this mode, the time does + // not progress. The time can still be read from the chip while it is halted, + // however. + // + // The DS1302 datasheet does not define the initial state of the Clock Halt + // flag, so this method should be called at least once when initializing a + // device for the first time. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Sets the time and date to the instant specified in a given Time object. // + // The time will not be set if write protection is enabled on the + // chip. Setting the time with this function has no effect on the Clock Halt + // flag. + // // Args: - // t: Time object to use + // t: Time instant. void time(Time t); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); // Sets a register with binary-coded decimal converted from a given value. // // Args: // reg: register number // value: decimal value to convert to BCD // high_bit: highest bit in the register allowed to contain BCD value void registerDecToBcd(Register reg, uint8_t value, uint8_t high_bit); void registerDecToBcd(Register reg, uint8_t value); }; #endif // DS1302_H_