Compare commits

...

109 Commits

Author SHA1 Message Date
c915fcfdff Release 3.0.0 2017-09-20 15:21:55 +01:00
02966c3b93 Sets cron daemon timeout to 5s across the plugin
Adds hook to override cron request arguments
2017-09-20 14:59:48 +01:00
84dc48daec Allow passing cron timeouts
[MAILPOET-1114]
2017-09-20 14:59:48 +01:00
12225004f4 Apply hook on cron timeout
[MAILPOET-1114]
2017-09-20 14:59:48 +01:00
320dfa2ec5 Extracts duplicate code into reusable methods
Updates unit test
2017-09-20 14:59:48 +01:00
b5f3016085 Removes URL from user agent
(https://mailpoet.slack.com/archives/C02MTKAJL/p1505488541000029?thread_ts=1505488163.000795&cid=C02MTKAJL)
2017-09-20 14:59:48 +01:00
cd53e369d0 Allows accessing full URL from within custom cron hook 2017-09-20 14:59:48 +01:00
6fc11af774 Returns error message instead of empty body 2017-09-20 14:59:48 +01:00
03d0de74e4 Merge pull request #1108 from mailpoet/send_twice_tooltip
Show a tooltip about sending an email twice only when the Send button is disabled [MAILPOET-1098]
2017-09-19 20:38:10 -04:00
28c75c5b96 Adds a thousand separator 2017-09-19 09:55:38 -04:00
6f255854f2 Merge pull request #1112 from mailpoet/copy_update
Update free MSS plan size to 2000 subscribers [MAILPOET-1112]
2017-09-19 12:46:36 +03:00
91c5f9c43e Clarify Premium plugin benefits 2017-09-19 12:41:25 +03:00
62acd6404a Update free MSS plan size to 2k subscribers, update plugin description 2017-09-19 12:15:46 +03:00
adc1461771 Don't show send tooltip for paused newsletters [MAILPOET-1098] 2017-09-19 08:51:16 +03:00
66cc0964ce Merge pull request #1106 from mailpoet/fix-tests
Fixing MP API test
2017-09-18 18:23:20 -04:00
10d77720ad Merge pull request #1107 from mailpoet/hooks_unit_test_update
Updates hooks unit test [MAILPOET-1110]
2017-09-18 17:39:50 +02:00
d831b2df55 Explicitly sets up hooks instead of assuming they are already set up 2017-09-18 10:43:17 -04:00
16ff630e88 Show a tooltip about sending an email twice only when the Send button is dsiabled [MAILPOET-1098] 2017-09-18 17:42:24 +03:00
d35763662e Fixing MP API test 2017-09-18 12:00:43 +00:00
10be411b12 Prepare release v3.0.0 2017-09-18 11:35:59 +01:00
6ecce192f7 Merge pull request #1105 from mailpoet/wp_sync_multisite
Fix WP sync throwing 'Table "users" doesn't exist' errors on multisite subsites [MAILPOET-1107]
2017-09-18 11:48:30 +03:00
ee07e60fe9 Adds new survey 2017-09-18 09:13:06 +01:00
a35d7a1154 Fix WP sync throwing 'Table users doesn't exist' errors on multisite subsites [MAILPOET-1107] 2017-09-18 10:55:49 +03:00
ebba8dbfd6 Merge pull request #1103 from mailpoet/twig_version_conflict_detection_improvement
Updates Twig version conflict detection logic [MAILPOET-1068]
2017-09-18 10:42:51 +03:00
44c637c06b Merge pull request #1101 from mailpoet/premium_key_in_beacon
Add Premium key to Help Scout beacon [MAILPOET-1090]
2017-09-17 12:08:52 -04:00
d54ba734bf Adds a min-max range of supported Twig versions 2017-09-17 11:25:35 -04:00
b45fc22306 Updates coding style and cleans up JS script inclusion part 2017-09-16 11:34:21 -04:00
994935d4ae Adds check for minimum Twig version loaded by external plugins 2017-09-16 11:33:40 -04:00
ceb5ce850c Removes deprecated Twig_ExtensionInterface::getName()
(https://github.com/twigphp/Twig/blob/2.x/CHANGELOG#L207)
Removes deprecated Twig_Extension_GlobalsInterface
(https://github.com/twigphp/Twig/blob/2.x/CHANGELOG#L259)
2017-09-16 11:30:40 -04:00
97b5ed945d Merge pull request #1100 from mailpoet/update-send-copy
Update send copy [MAILPOET-1101]
2017-09-14 20:02:28 +02:00
873b322245 Translate
[MAILPOET-1101]
2017-09-14 18:52:33 +01:00
12ad9e41e7 Translate a string
[MAILPOET-1101]
2017-09-14 18:40:04 +01:00
96b418e455 Our free plan will be for 1,000 subscribers and not 250
[MAILPOET-1101]
2017-09-14 17:35:15 +01:00
8ea7861f77 Merge pull request #1102 from mailpoet/welcome-tab-update
Update welcome tab [MAILPOET-1099]
2017-09-14 19:34:01 +03:00
821976c881 Make text random
[MAILPOET-1099]
2017-09-14 17:19:55 +01:00
6f1443e43d Update welcome tab
[MAILPOET-1099]
2017-09-14 15:35:07 +01:00
09fcaecdfc Add Premium key to Help Scout beacon [MAILPOET-1090] 2017-09-14 16:24:15 +03:00
efd72ca9f6 Merge pull request #1099 from mailpoet/update-readme
Update readme.txt for launch v3
2017-09-14 15:38:36 +03:00
550b5e9aed More readme.txt updates
[MAILPOET-1105]
2017-09-14 13:37:10 +01:00
4b7ae5fcff Fix typo
[MAILPOET-1105]
2017-09-14 13:28:44 +01:00
fa85e12127 Update premium section in readme.txt
[MAILPOET-1105]
2017-09-14 13:27:07 +01:00
1cce50902b Update Send with... other copy
[MAILPOET-1101]
2017-09-14 11:39:20 +01:00
2048fa5cf9 Update Send with... mailpoet copy
[MAILPOET-1101]
2017-09-14 11:31:43 +01:00
f438c8fd31 Update readme.txt for launch v3
[MAILPOET-1105]
2017-09-14 10:15:00 +01:00
0bfa832dad Merge pull request #1098 from mailpoet/subscribers-fix
Subscribers fix [MAILPOET-1102]
2017-09-13 18:17:56 +03:00
483dfbe1ec Fix removal of WP segment subscribers without wp_user_id [MAILPOET-1102] 2017-09-13 16:46:50 +03:00
561fee491d Merge pull request #1097 from mailpoet/makepot_views_fix
Fix makepot adding extra slashes to escaped characters in views [MAILPOET-1093]
2017-09-13 14:54:25 +02:00
97d157192a Remove orphaned links
[MAILPOET-1102]
2017-09-13 13:30:23 +01:00
6b14a8a057 Remove data from usermeta
[MAILPOET-1102]
2017-09-13 13:18:39 +01:00
d27b187f5e Fix QA problems
[MAILPOET-1102]
2017-09-13 13:15:50 +01:00
02d49ba2ca DELETE subscribers in WP list which are not WP users
[MAILPOET-1102]
2017-09-13 13:07:01 +01:00
f3571a5855 Add another testing scenario
[MAILPOET-1102]
2017-09-13 08:54:54 +01:00
3d5f0df213 Don't delete subscribers with wp_user_id = 0 [MAILPOET-1102] 2017-09-13 10:15:09 +03:00
595a201fe7 Stop deleting subscribers
[MAILPOET-1102]
2017-09-12 17:53:12 +01:00
c3db7d8148 Release 3.0.0-rc.2.0.3 2017-09-12 15:41:06 +03:00
4a2187ff32 Merge pull request #1096 from mailpoet/translation_strings_update
Removes escape character in translations [MAILPOET-1093]
2017-09-12 14:24:38 +03:00
279c36a30d Merge pull request #1094 from mailpoet/initializer_update
Updates plugin initialization logic [MAILPOET-1097]
2017-09-12 12:34:27 +03:00
fd65117a5d Fix makepot adding extra slashes to escaped characters in views [MAILPOET-1093] 2017-09-12 11:17:04 +03:00
9305beace3 Removes escape character in translations 2017-09-11 19:27:03 -04:00
ba86cbfb18 Updates unit test 2017-09-11 11:40:14 -04:00
2ac7d1d4ab Breaks plugin initialization into 3 stages: preInit, init and postInit 2017-09-11 11:33:03 -04:00
e9c55260c8 Merge pull request #1092 from mailpoet/db_version_settings_logic_update
Uses plugin's settings to store DB version [MAILPOET-1095]
2017-09-11 18:15:17 +03:00
99b6a287f8 Highlight a container block when hovering over its tools [MAILPOET-1088] 2017-09-11 15:32:45 +01:00
d645f0cad4 Merge pull request #1087 from mailpoet/eslint-un
Eslint un [MAILPOET-1073]
2017-09-11 16:16:51 +02:00
b0343254c0 Renames db version setting value 2017-09-11 10:05:09 -04:00
cc368f015b Remove redundant argument
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
4e508855fc Fix eslint no-unused-expressions in tests
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
72c0a6f165 Fix eslint no-undef in tests
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
f266508654 Fix eslint no-undef in ES6
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
1893d82b2d Fix eslint no-unused-expressions in ES6
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
bb1dd6a2ec Fix eslint import/no-unresolved in ES6
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
7097ea5d9b Fix eslint no-unreachable in ES6
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
b4092e0641 Fix eslint no-unneeded-ternary in ES5
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
2c068c7bb6 Fix eslint no-unreachable in ES5
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
a1a4fcb978 Fix eslint no-unused-expressions in ES5
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
f77620d649 Fix eslint no-undef in ES5
[MAILPOET-1085]
2017-09-11 15:03:30 +01:00
9e932c9078 Merge pull request #1085 from mailpoet/improve-user-sync
Improve user sync [MAILPOET-1073]
2017-09-11 14:56:41 +03:00
de47dbe41b Removes arrow functions that are not supported in IE 2017-09-11 10:25:43 +01:00
6d36d67a60 Delete orphaned subscribers instead of updating their id
[MAILPOET-1073]
2017-09-11 10:09:32 +01:00
607bf51b37 Merge two test cases for one class
[MAILPOET-1073]
2017-09-11 09:28:39 +01:00
f38ed0272c Merge pull request #1093 from mailpoet/cron_helper_improvement
Cron helper improvement [MAILPOET-1096]
2017-09-11 11:23:01 +03:00
eef969439b Code comment
[MAILPOET-1073]
2017-09-11 09:22:40 +01:00
272f552f3c Clean data befre and after test run
[MAILPOET-1073]
2017-09-11 09:22:18 +01:00
dff9c1012b Moves widget initialization back to widgets_init hook
Removes priority from plugin initialization
2017-09-10 19:49:05 -04:00
52470360a1 Returns ping response body instead of boolean 2017-09-10 18:49:15 -04:00
6c62459ed4 Adds filter to override default cron request URL 2017-09-10 18:36:22 -04:00
98482cebf9 Uses plugin's settings to store DB version 2017-09-10 16:31:36 -04:00
509880119e Merge pull request #1090 from mailpoet/eslint-indent
Eslint indent [MAILPOET-1029]
2017-09-07 20:13:20 -04:00
195ccb5eed Fix indent rule in tests
[MAILPOET-1029]
2017-09-07 16:05:45 +01:00
122af1c943 Fix react/jsx-indent rule in ES6
[MAILPOET-1029]
2017-09-07 15:59:38 +01:00
169940058b Fix react/jsx-indent-props rule in ES6
[MAILPOET-1029]
2017-09-07 15:52:46 +01:00
478e60d60e Fix indent rule in ES5
[MAILPOET-1029]
2017-09-07 15:51:25 +01:00
9fc0ac8c4f Merge pull request #1089 from mailpoet/color_picker
Change color on click, add history to color picker [MAILPOET-1087]
2017-09-07 17:08:09 +03:00
e86b780479 Fix build`
[MAILPOET-1073]
2017-09-07 14:44:55 +01:00
42f08bdc65 Fix handling of empty color and transparent color selected from palette [MAILPOET-1087] 2017-09-07 15:48:14 +03:00
c2789cdac3 Don't load all ids to memory, PHP could crash
[MAILPOET-1073]
2017-09-07 13:42:18 +01:00
8a362f49f8 Add test for users synchronisation
[MAILPOET-1073]
2017-09-07 13:42:18 +01:00
784a80d1a5 Use ->prefix instead of wp_
[MAILPOET-1073]
2017-09-07 13:42:18 +01:00
922d2b4b5f Fix migration
[MAILPOET-1073]
2017-09-07 13:42:18 +01:00
91e8461cac Clean the code
[MAILPOET-1073]
2017-09-07 13:42:18 +01:00
8757598a2d Add index
[MAILPOET-1073]
2017-09-07 13:42:18 +01:00
524aabea1d Split users sync into multiple queries
[MAILPOET-1073]
2017-09-07 13:42:18 +01:00
513181ff47 Change color on click, add history to color picker [MAILPOET-1087] 2017-09-07 13:17:57 +03:00
6bc288ed54 Merge pull request #1088 from mailpoet/depreciated_twig_notice_fix
Fixed Twig's deprecated notice [MAILPOET-1092]
2017-09-07 12:48:11 +03:00
77f3a875dd Does not set global is_rtl variable 2017-09-06 20:56:52 -04:00
6584250d1a Adds is_rtl() function to Twig 2017-09-06 20:55:44 -04:00
e42db162aa Merge pull request #1086 from mailpoet/translation_fixes
Fix translations based on translator feedback on TX [MAILPOET-1091]
2017-09-06 16:30:13 +03:00
2762096167 Switch strtoupper to mb_strtoupper based on feedback 2017-09-06 16:14:52 +03:00
b2ec3e5f7b Fix translations based on translator feedback on TX [MAILPOET-1091] 2017-09-06 13:45:42 +03:00
139 changed files with 2530 additions and 1948 deletions

View File

@ -11,7 +11,6 @@
"import/no-amd": 0,
"space-before-function-paren": 0,
"prefer-arrow-callback": 0,
"no-undef": 0,
"key-spacing": 0,
"radix": 0,
"no-alert": 0,
@ -34,16 +33,13 @@
"no-empty": 0,
"no-useless-escape": 0,
"wrap-iife": 0,
"no-unused-expressions": 0,
"block-spacing": 0,
"computed-property-spacing": 0,
"no-plusplus": 0,
"array-bracket-spacing": 0,
"no-unreachable": 0,
"default-case": 0,
"no-lonely-if": 0,
"space-before-blocks": 0,
"no-unneeded-ternary": 0,
"no-mixed-operators": 0,
"eqeqeq": 0,
"space-in-parens": 0,
@ -74,7 +70,6 @@
"keyword-spacing": 0,
"eol-last": 0,
"dot-notation": 0,
"indent": 0,
"prefer-template": 0,
"func-names": 0
}

View File

@ -10,6 +10,9 @@
"jsx": true
}
},
"settings": {
"import/resolver": "webpack"
},
"rules": {
"comma-dangle": ["error", "always-multiline"],
"import/no-amd": 0,
@ -18,12 +21,10 @@
"react/jsx-max-props-per-line": 0,
"react/prop-types": 0,
"react/jsx-first-prop-new-line": 0,
"react/jsx-indent-props": 0,
"react/no-is-mounted": 0,
"react/jsx-no-target-blank": 0,
"react/no-render-return-value": 0,
"react/jsx-boolean-value": 0,
"react/jsx-indent": 0,
"react/jsx-no-bind": 0,
"react/no-array-index-key": 0,
"react/self-closing-comp": 0,
@ -45,8 +46,6 @@
"default-case": 0,
"array-callback-return": 0,
"consistent-return": 0,
"no-unreachable": 0,
"import/no-unresolved": 0,
"import/extensions": 0,
"import/no-extraneous-dependencies": 0,
"camelcase": 0,
@ -65,7 +64,6 @@
"no-else-return": 0,
"max-len": 0,
"no-useless-concat": 0,
"no-unused-expressions": 0,
"no-sequences": 0,
"no-extra-boolean-cast": 0,
"dot-notation": 0,
@ -79,7 +77,6 @@
"space-infix-ops": 0,
"no-irregular-whitespace": 0,
"padded-blocks": 0,
"no-underscore-dangle": 0,
"no-undef": 0
"no-underscore-dangle": 0
}
}

View File

@ -9,9 +9,7 @@
},
"rules": {
"import/no-amd": 0,
"no-undef": 0,
"one-var": 0,
"indent": 0,
"no-whitespace-before-property": 0,
"global-require": 0,
"keyword-spacing": 0,
@ -21,7 +19,6 @@
"max-len": 0,
"space-unary-ops": 0,
"no-unused-vars": 0,
"no-unused-expressions": 0,
"no-underscore-dangle": 0,
"no-shadow": 0,
"padded-blocks": 0,

View File

@ -23,8 +23,10 @@ $block-text-line-height = $text-line-height
border: 1px solid $transparent-color
&:hover > .mailpoet_block_highlight
&.mailpoet_highlight > .mailpoet_block_highlight
border: 1px dashed $block-hover-highlight-color
&.mailpoet_highlight > .mailpoet_block_highlight
border: 1px dashed $block-hover-highlight-color !important
.mailpoet_content
position: relative

View File

@ -33,3 +33,6 @@ Custom styles for MailPoet pages.
p.top-space-triple
margin-top: 3em
p.mailpoet-top-text
margin-right: 0

View File

@ -62,6 +62,15 @@
margin-bottom: 2em
margin-top: 2em
.sending-free-plan-button
background: #FF5301
border-color: #e64c03
text-shadow: 0 -1px 1px #e64c03
box-shadow: 0 1px 0 #e64c03
margin: 10px 0
strong
text-transform: uppercase
.mailpoet_success_item::before
content ' '

View File

@ -1,6 +1,6 @@
define('admin', [
'jquery'
],
'jquery'
],
function(jQuery) {
jQuery(function($) {
// dom ready

View File

@ -16,59 +16,59 @@ define('ajax', ['mailpoet', 'jquery', 'underscore'], function(mp, jQuery, _) {
var MailPoet = mp;
MailPoet.Ajax = {
version: 0.5,
options: {},
defaults: {
url: null,
api_version: null,
endpoint: null,
action: null,
token: null,
data: {}
},
post: function(options) {
return this.request('post', options);
},
init: function(options) {
// merge options
this.options = jQuery.extend({}, this.defaults, options);
version: 0.5,
options: {},
defaults: {
url: null,
api_version: null,
endpoint: null,
action: null,
token: null,
data: {}
},
post: function(options) {
return this.request('post', options);
},
init: function(options) {
// merge options
this.options = jQuery.extend({}, this.defaults, options);
// set default url
if(this.options.url === null) {
this.options.url = ajaxurl;
}
// set default url
if(this.options.url === null) {
this.options.url = window.ajaxurl;
}
// set default token
if(this.options.token === null) {
this.options.token = window.mailpoet_token;
}
},
getParams: function() {
return {
action: 'mailpoet',
api_version: this.options.api_version,
token: this.options.token,
endpoint: this.options.endpoint,
method: this.options.action,
data: this.options.data || {}
};
},
request: function(method, options) {
// set default token
if(this.options.token === null) {
this.options.token = window.mailpoet_token;
}
},
getParams: function() {
return {
action: 'mailpoet',
api_version: this.options.api_version,
token: this.options.token,
endpoint: this.options.endpoint,
method: this.options.action,
data: this.options.data || {}
};
},
request: function(method, options) {
// set options
this.init(options);
this.init(options);
// set request params
var params = this.getParams();
var params = this.getParams();
// remove null values from the data object
if (_.isObject(params.data)) {
params.data = _.pick(params.data, function(value) {
return (value !== null);
});
}
if (_.isObject(params.data)) {
params.data = _.pick(params.data, function(value) {
return (value !== null);
});
}
// ajax request
var deferred = jQuery.post(
var deferred = jQuery.post(
this.options.url,
params,
null,
@ -78,9 +78,9 @@ define('ajax', ['mailpoet', 'jquery', 'underscore'], function(mp, jQuery, _) {
}, _.partial(requestFailed, MailPoet.I18n.t('ajaxFailedErrorMessage')));
// clear options
this.options = {};
this.options = {};
return deferred;
}
return deferred;
}
};
});

View File

@ -43,15 +43,6 @@ function trackCachedEvents() {
});
}
function initializeMixpanelWhenLoaded() {
if (typeof window.mixpanel === 'object') {
exportMixpanel(MailPoet);
trackCachedEvents();
} else {
setTimeout(initializeMixpanelWhenLoaded, 100);
}
}
function cacheEvent(forced, name, data) {
eventsCache.push({
name: name,
@ -65,6 +56,15 @@ define(
function(mp, _) {
var MailPoet = mp;
function initializeMixpanelWhenLoaded() {
if (typeof window.mixpanel === 'object') {
exportMixpanel(MailPoet);
trackCachedEvents();
} else {
setTimeout(initializeMixpanelWhenLoaded, 100);
}
}
MailPoet.trackEvent = _.partial(cacheEvent, false);
MailPoet.forceTrackEvent = _.partial(cacheEvent, true);

View File

@ -8,162 +8,162 @@ define('date',
jQuery,
Moment
) {
'use strict';
'use strict';
var MailPoet = mp;
var MailPoet = mp;
MailPoet.Date = {
version: 0.1,
options: {},
defaults: {
offset: 0,
format: 'F, d Y H:i:s'
},
init: function (opts) {
var options = opts || {};
MailPoet.Date = {
version: 0.1,
options: {},
defaults: {
offset: 0,
format: 'F, d Y H:i:s'
},
init: function (opts) {
var options = opts || {};
// set UTC offset
if (
if (
options.offset === undefined
&& window.mailpoet_date_offset !== undefined
) {
options.offset = window.mailpoet_date_offset;
}
options.offset = window.mailpoet_date_offset;
}
// set date format
if (
if (
options.format === undefined
&& window.mailpoet_date_format !== undefined
) {
options.format = window.mailpoet_date_format;
}
// merge options
this.options = jQuery.extend({}, this.defaults, options);
return this;
},
format: function(date, opts) {
var options = opts || {};
this.init(options);
var momentDate = Moment(date, this.convertFormat(options.parseFormat));
if (options.offset === 0) momentDate = momentDate.utc();
return momentDate.format(this.convertFormat(this.options.format));
},
toDate: function(date, opts) {
var options = opts || {};
this.init(options);
return Moment(date, this.convertFormat(options.parseFormat)).toDate();
},
short: function(date) {
return this.format(date, {
format: 'F, j Y'
});
},
full: function(date) {
return this.format(date, {
format: 'F, j Y H:i:s'
});
},
time: function(date) {
return this.format(date, {
format: 'H:i:s'
});
},
convertFormat: function(format) {
var format_mappings = {
date: {
d: 'DD',
D: 'ddd',
j: 'D',
l: 'dddd',
N: 'E',
S: 'o',
w: 'e',
z: 'DDD',
W: 'W',
F: 'MMMM',
m: 'MM',
M: 'MMM',
n: 'M',
t: '', // no equivalent
L: '', // no equivalent
o: 'YYYY',
Y: 'YYYY',
y: 'YY',
a: 'a',
A: 'A',
B: '', // no equivalent
g: 'h',
G: 'H',
h: 'hh',
H: 'HH',
i: 'mm',
s: 'ss',
u: 'SSS',
e: 'zz', // deprecated since version 1.6.0 of moment.js
I: '', // no equivalent
O: '', // no equivalent
P: '', // no equivalent
T: '', // no equivalent
Z: '', // no equivalent
c: '', // no equivalent
r: '', // no equivalent
U: 'X'
},
strftime: {
a: 'ddd',
A: 'dddd',
b: 'MMM',
B: 'MMMM',
d: 'DD',
e: 'D',
F: 'YYYY-MM-DD',
H: 'HH',
I: 'hh',
j: 'DDDD',
k: 'H',
l: 'h',
m: 'MM',
M: 'mm',
p: 'A',
S: 'ss',
u: 'E',
w: 'd',
W: 'WW',
y: 'YY',
Y: 'YYYY',
z: 'ZZ',
Z: 'z'
options.format = window.mailpoet_date_format;
}
};
// merge options
this.options = jQuery.extend({}, this.defaults, options);
if (!format || format.length <= 0) return format;
return this;
},
format: function(date, opts) {
var options = opts || {};
this.init(options);
var replacements = format_mappings['date'];
var momentDate = Moment(date, this.convertFormat(options.parseFormat));
if (options.offset === 0) momentDate = momentDate.utc();
return momentDate.format(this.convertFormat(this.options.format));
},
toDate: function(date, opts) {
var options = opts || {};
this.init(options);
var convertedFormat = [];
var escapeToken = false;
return Moment(date, this.convertFormat(options.parseFormat)).toDate();
},
short: function(date) {
return this.format(date, {
format: 'F, j Y'
});
},
full: function(date) {
return this.format(date, {
format: 'F, j Y H:i:s'
});
},
time: function(date) {
return this.format(date, {
format: 'H:i:s'
});
},
convertFormat: function(format) {
var format_mappings = {
date: {
d: 'DD',
D: 'ddd',
j: 'D',
l: 'dddd',
N: 'E',
S: 'o',
w: 'e',
z: 'DDD',
W: 'W',
F: 'MMMM',
m: 'MM',
M: 'MMM',
n: 'M',
t: '', // no equivalent
L: '', // no equivalent
o: 'YYYY',
Y: 'YYYY',
y: 'YY',
a: 'a',
A: 'A',
B: '', // no equivalent
g: 'h',
G: 'H',
h: 'hh',
H: 'HH',
i: 'mm',
s: 'ss',
u: 'SSS',
e: 'zz', // deprecated since version 1.6.0 of moment.js
I: '', // no equivalent
O: '', // no equivalent
P: '', // no equivalent
T: '', // no equivalent
Z: '', // no equivalent
c: '', // no equivalent
r: '', // no equivalent
U: 'X'
},
strftime: {
a: 'ddd',
A: 'dddd',
b: 'MMM',
B: 'MMMM',
d: 'DD',
e: 'D',
F: 'YYYY-MM-DD',
H: 'HH',
I: 'hh',
j: 'DDDD',
k: 'H',
l: 'h',
m: 'MM',
M: 'mm',
p: 'A',
S: 'ss',
u: 'E',
w: 'd',
W: 'WW',
y: 'YY',
Y: 'YYYY',
z: 'ZZ',
Z: 'z'
}
};
for(var index = 0, token = ''; format.charAt(index); index += 1){
token = format.charAt(index);
if (escapeToken === true) {
convertedFormat.push('['+token+']');
escapeToken = false;
} else {
if (token === '\\') {
// Slash escapes the next symbol to be treated as literal
escapeToken = true;
continue;
} else if (replacements[token] !== undefined) {
convertedFormat.push(replacements[token]);
} else {
if (!format || format.length <= 0) return format;
var replacements = format_mappings['date'];
var convertedFormat = [];
var escapeToken = false;
for(var index = 0, token = ''; format.charAt(index); index += 1){
token = format.charAt(index);
if (escapeToken === true) {
convertedFormat.push('['+token+']');
escapeToken = false;
} else {
if (token === '\\') {
// Slash escapes the next symbol to be treated as literal
escapeToken = true;
continue;
} else if (replacements[token] !== undefined) {
convertedFormat.push(replacements[token]);
} else {
convertedFormat.push('['+token+']');
}
}
}
}
return convertedFormat.join('');
}
};
});
return convertedFormat.join('');
}
};
});

View File

@ -212,7 +212,6 @@ define([
year={ this.state.year }
placeholder={ this.props.field.year_placeholder }
/>);
break;
case 'MM':
return (<FormFieldDateMonth
@ -224,7 +223,6 @@ define([
monthNames={ monthNames }
placeholder={ this.props.field.month_placeholder }
/>);
break;
case 'DD':
return (<FormFieldDateDay
@ -235,7 +233,6 @@ define([
day={ this.state.day }
placeholder={ this.props.field.day_placeholder }
/>);
break;
}
});

View File

@ -7,6 +7,7 @@ define([
'form/fields/checkbox.jsx',
'form/fields/selection.jsx',
'form/fields/date.jsx',
'jquery',
],
(
React,
@ -16,7 +17,8 @@ define([
FormFieldRadio,
FormFieldCheckbox,
FormFieldSelection,
FormFieldDate
FormFieldDate,
jQuery
) => {
const FormField = React.createClass({
renderField: function (data, inline = false) {

View File

@ -116,6 +116,7 @@ define([
}
},
handleChange: function (e) {
let value;
if(this.props.onValueChange !== undefined) {
if(this.props.field.multiple) {
value = jQuery('#'+this.refs.select.id).val();

View File

@ -5,13 +5,15 @@ define(
'classnames',
'react-router',
'form/fields/field.jsx',
'jquery',
],
(
React,
MailPoet,
classNames,
Router,
FormField
FormField,
jQuery
) => {
const Form = React.createClass({

View File

@ -91,7 +91,7 @@ var Observable = (function() {
function getHandlers(klass) {
var proto = klass.prototype,
namespace = proto.namespace;
return Object.keys(proto).grep(/^on/).inject($H(), function(handlers, name) {
return Object.keys(proto).grep(/^on/).inject(window.$H(), function(handlers, name) {
if(name === 'onDomLoaded') return handlers;
handlers.set(getEventName(name, namespace), getWrapper(proto[name], klass));
return handlers;
@ -105,7 +105,7 @@ var Observable = (function() {
}
function onDomLoad(selector, klass) {
$$(selector).each(function(element) {
window.$$(selector).each(function(element) {
new klass(element).onDomLoaded();
});
}
@ -114,7 +114,13 @@ var Observable = (function() {
if(!this.handlers) this.handlers = {};
if(this.handlers[selector]) return;
var klass = this;
if(this.prototype.onDomLoaded) document.loaded ? onDomLoad(selector, klass) : document.observe('dom:loaded', onDomLoad.curry(selector, klass));
if(this.prototype.onDomLoaded) {
if(document.loaded) {
onDomLoad(selector, klass);
} else {
document.observe('dom:loaded', onDomLoad.curry(selector, klass));
}
}
this.handlers[selector] = getHandlers(klass).each(function(handler) {
document.delegate(selector, handler.key, handler.value);
});
@ -130,12 +136,12 @@ var Observable = (function() {
})();
// override droppables
Object.extend(Droppables, {
deactivate: Droppables.deactivate.wrap(function(proceed, drop, draggable) {
Object.extend(window.Droppables, {
deactivate: window.Droppables.deactivate.wrap(function(proceed, drop, draggable) {
if(drop.onLeave) drop.onLeave(draggable, drop.element);
return proceed(drop);
}),
activate: Droppables.activate.wrap(function(proceed, drop, draggable) {
activate: window.Droppables.activate.wrap(function(proceed, drop, draggable) {
if(drop.onEnter) drop.onEnter(draggable, drop.element);
return proceed(drop);
}),
@ -143,14 +149,14 @@ Object.extend(Droppables, {
if(!this.drops.length) return;
var drop, affected = [];
this.drops.each(function(drop) {
if(Droppables.isAffected(point, element, drop)) affected.push(drop);
if(window.Droppables.isAffected(point, element, drop)) affected.push(drop);
});
if(affected.length > 0) drop = Droppables.findDeepestChild(affected);
if(affected.length > 0) drop = window.Droppables.findDeepestChild(affected);
if(this.last_active && this.last_active !== drop) this.deactivate(this.last_active, element);
if(drop) {
Position.within(drop.element, point[0], point[1]);
if(drop.onHover) drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
if(drop !== this.last_active) Droppables.activate(drop, element);
window.Position.within(drop.element, point[0], point[1]);
if(drop.onHover) drop.onHover(element, drop.element, window.Position.overlap(drop.overlap, drop.element));
if(drop !== this.last_active) window.Droppables.activate(drop, element);
}
},
displayArea: function(draggable) {
@ -199,36 +205,36 @@ var WysijaHistory = {
// check if the field is unique
if(parseInt(clone.readAttribute('wysija_unique'), 10) === 1) {
// check if the field is already in the queue
$(WysijaHistory.container).select('[wysija_name="' + clone.readAttribute('wysija_name') + '"]').invoke('remove');
window.$(WysijaHistory.container).select('[wysija_name="' + clone.readAttribute('wysija_name') + '"]').invoke('remove');
}
// check history size
if($(WysijaHistory.container).select('> div').length >= WysijaHistory.size) {
if(window.$(WysijaHistory.container).select('> div').length >= WysijaHistory.size) {
// remove oldest element (last in the list)
$(WysijaHistory.container).select('> div').last().remove();
window.$(WysijaHistory.container).select('> div').last().remove();
}
// store block in history
$(WysijaHistory.container).insert({
window.$(WysijaHistory.container).insert({
top: clone
});
},
dequeue: function() {
// pop last block off the history
var block = $(WysijaHistory.container).select('div').first();
var block = window.$(WysijaHistory.container).select('div').first();
if(block !== undefined) {
// insert block back into the editor
$(WysijaForm.options.body).insert({
window.$(WysijaForm.options.body).insert({
top: block
});
}
},
clear: function() {
$(WysijaHistory.container).innerHTML = '';
window.$(WysijaHistory.container).innerHTML = '';
},
remove: function(field) {
$(WysijaHistory.container).select('[wysija_name="' + field + '"]').invoke('remove');
window.$(WysijaHistory.container).select('[wysija_name="' + field + '"]').invoke('remove');
}
};
@ -272,17 +278,17 @@ var WysijaForm = {
},
loading: function(is_loading) {
if(is_loading) {
$(WysijaForm.options.editor).addClassName('loading');
$(WysijaForm.options.toolbar).addClassName('loading');
window.$(WysijaForm.options.editor).addClassName('loading');
window.$(WysijaForm.options.toolbar).addClassName('loading');
} else {
$(WysijaForm.options.editor).removeClassName('loading');
$(WysijaForm.options.toolbar).removeClassName('loading');
window.$(WysijaForm.options.editor).removeClassName('loading');
window.$(WysijaForm.options.toolbar).removeClassName('loading');
}
},
loadStatic: function(blocks) {
$A(blocks).each(function(block) {
window.$A(blocks).each(function(block) {
// create block
WysijaForm.Block.create(block, $('block_placeholder'));
WysijaForm.Block.create(block, window.$('block_placeholder'));
});
},
load: function(data) {
@ -290,13 +296,13 @@ var WysijaForm = {
// load body
if(data.body !== undefined) {
$A(data.body).each(function(block) {
window.$A(data.body).each(function(block) {
// create block
WysijaForm.Block.create(block, $('block_placeholder'));
WysijaForm.Block.create(block, window.$('block_placeholder'));
});
// load settings
var settings_elements = $('mailpoet_form_settings').getElements();
var settings_elements = window.$('mailpoet_form_settings').getElements();
settings_elements.each(function(setting) {
// skip lists
if(setting.name === 'segments') {
@ -305,7 +311,7 @@ var WysijaForm = {
// if the input value is equal to the one stored in the settings
if(setting.value === data.settings[setting.name]) {
// check selected value
$(setting).checked = true;
window.$(setting).checked = true;
}
} else if(data.settings[setting.name] !== undefined) {
if(typeof data.settings[setting.name] === 'string') {
@ -320,10 +326,10 @@ var WysijaForm = {
save: function() {
var position = 1,
data = {
name: $F('mailpoet_form_name'),
settings: $('mailpoet_form_settings').serialize(true),
name: window.$F('mailpoet_form_name'),
settings: window.$('mailpoet_form_settings').serialize(true),
body: [],
styles: (MailPoet.CodeEditor !== undefined) ? MailPoet.CodeEditor.getValue() : null
styles: (window.MailPoet.CodeEditor !== undefined) ? window.MailPoet.CodeEditor.getValue() : null
};
// body
WysijaForm.getBlocks().each(function(b) {
@ -395,11 +401,11 @@ var WysijaForm = {
return data;
},
toggleWidgets: function() {
$$('a[wysija_unique="1"]').invoke('removeClassName', 'disabled');
window.$$('a[wysija_unique="1"]').invoke('removeClassName', 'disabled');
// loop through each unique field already inserted in the editor and disable its toolbar equivalent
$$('#' + WysijaForm.options.editor + ' [wysija_unique="1"]').map(function(element) {
var field = $$('#' + WysijaForm.options.toolbar + ' [wysija_id="' + element.readAttribute('wysija_id') + '"]');
window.$$('#' + WysijaForm.options.editor + ' [wysija_unique="1"]').map(function(element) {
var field = window.$$('#' + WysijaForm.options.toolbar + ' [wysija_id="' + element.readAttribute('wysija_id') + '"]');
if(field.length > 0) {
field.first().addClassName('disabled');
}
@ -408,18 +414,18 @@ var WysijaForm = {
var hasSegmentSelection = WysijaForm.hasSegmentSelection();
if(hasSegmentSelection) {
$('mailpoet_form_segments').writeAttribute('required', false).disable();
$('mailpoet_settings_segment_selection').hide();
window.$('mailpoet_form_segments').writeAttribute('required', false).disable();
window.$('mailpoet_settings_segment_selection').hide();
} else {
$('mailpoet_form_segments').writeAttribute('required', true).enable();
$('mailpoet_settings_segment_selection').show();
window.$('mailpoet_form_segments').writeAttribute('required', true).enable();
window.$('mailpoet_settings_segment_selection').show();
}
},
hasSegmentSelection: function() {
return ($$('#' + WysijaForm.options.editor + ' [wysija_id="segments"]').length > 0);
return (window.$$('#' + WysijaForm.options.editor + ' [wysija_id="segments"]').length > 0);
},
isSegmentSelectionValid: function() {
var segment_selection = $$('#' + WysijaForm.options.editor + ' [wysija_id="segments"]')[0];
var segment_selection = window.$$('#' + WysijaForm.options.editor + ' [wysija_id="segments"]')[0];
if(segment_selection !== undefined) {
var block = WysijaForm.get(segment_selection).block.getData();
return (
@ -447,7 +453,7 @@ var WysijaForm = {
if(target !== undefined) {
// get placeholders (previous placeholder matches the placeholder linked to the next block)
var block_placeholder = $(target.element.readAttribute('wysija_placeholder')),
var block_placeholder = window.$(target.element.readAttribute('wysija_placeholder')),
previous_placeholder = target.element.previous('.block_placeholder');
if(block_placeholder !== null) {
@ -469,18 +475,18 @@ var WysijaForm = {
WysijaForm.scroll = document.viewport.getScrollOffsets();
},
hideSettings: function() {
$(WysijaForm.options.container).select('.wysija_settings').invoke('hide');
window.$(WysijaForm.options.container).select('.wysija_settings').invoke('hide');
},
setSettingsPosition: function() {
// get viewport offsets and dimensions
var viewportHeight = document.viewport.getHeight(),
blockPadding = 5;
$(WysijaForm.options.container).select('.wysija_settings').each(function(element) {
window.$(WysijaForm.options.container).select('.wysija_settings').each(function(element) {
// get parent dimensions and position
var parentDim = element.up('.mailpoet_form_block').getDimensions(),
parentPos = element.up('.mailpoet_form_block').cumulativeOffset(),
is_visible = (parentPos.top <= (WysijaForm.scroll.top + viewportHeight)) ? true : false,
is_visible = (parentPos.top <= (WysijaForm.scroll.top + viewportHeight)),
buttonMargin = 5,
relativeTop = buttonMargin;
@ -494,22 +500,22 @@ var WysijaForm = {
relativeTop = parseInt((parentDim.height / 2) - (element.getHeight() / 2), 10);
}
// set position for button
$(element).setStyle({
window.$(element).setStyle({
left: parseInt((parentDim.width / 2) - (element.getWidth() / 2)) + 'px',
top: relativeTop + 'px'
});
});
},
initToolbarPosition: function() {
if(WysijaForm.toolbar.top === null) WysijaForm.toolbar.top = parseInt($(WysijaForm.options.container).positionedOffset().top);
if(WysijaForm.toolbar.top === null) WysijaForm.toolbar.top = parseInt(window.$(WysijaForm.options.container).positionedOffset().top);
if(WysijaForm.toolbar.y === null) WysijaForm.toolbar.y = parseInt(WysijaForm.toolbar.top);
if(isRtl) {
if(window.isRtl) {
if(WysijaForm.toolbar.left === null) WysijaForm.toolbar.left = 0;
} else {
if(WysijaForm.toolbar.left === null) WysijaForm.toolbar.left = parseInt($(WysijaForm.options.container).positionedOffset().left);
if(WysijaForm.toolbar.left === null) WysijaForm.toolbar.left = parseInt(window.$(WysijaForm.options.container).positionedOffset().left);
}
if(WysijaForm.toolbar.x === null) WysijaForm.toolbar.x = parseInt(WysijaForm.toolbar.left + $(WysijaForm.options.container).getDimensions().width + 15);
if(WysijaForm.toolbar.x === null) WysijaForm.toolbar.x = parseInt(WysijaForm.toolbar.left + window.$(WysijaForm.options.container).getDimensions().width + 15);
},
setToolbarPosition: function() {
@ -520,13 +526,13 @@ var WysijaForm = {
visibility: 'visible'
};
if(isRtl) {
if(window.isRtl) {
position.right = WysijaForm.toolbar.x + 'px';
} else {
position.left = WysijaForm.toolbar.x + 'px';
}
$(WysijaForm.options.toolbar).setStyle(position);
window.$(WysijaForm.options.toolbar).setStyle(position);
},
updateToolbarPosition: function() {
// init toolbar position (updates scroll and toolbar y)
@ -538,31 +544,31 @@ var WysijaForm = {
if(WysijaForm.scroll.top >= (WysijaForm.toolbar.top - 20)) {
WysijaForm.toolbar.y = parseInt(20 + WysijaForm.scroll.top);
// start effect
WysijaForm.toolbar.effect = new Effect.Move(WysijaForm.options.toolbar, {
WysijaForm.toolbar.effect = new window.Effect.Move(WysijaForm.options.toolbar, {
x: WysijaForm.toolbar.x,
y: WysijaForm.toolbar.y,
mode: 'absolute',
duration: 0.2
});
} else {
$(WysijaForm.options.toolbar).setStyle({
window.$(WysijaForm.options.toolbar).setStyle({
left: WysijaForm.toolbar.x + 'px',
top: WysijaForm.toolbar.top + 'px'
});
}
},
blockDropOptions: {
accept: $w('mailpoet_form_field'), // acceptable items (classes array)
accept: window.$w('mailpoet_form_field'), // acceptable items (classes array)
onEnter: function(draggable, droppable) {
$(droppable).addClassName('hover');
window.$(droppable).addClassName('hover');
},
onLeave: function(draggable, droppable) {
$(droppable).removeClassName('hover');
window.$(droppable).removeClassName('hover');
},
onDrop: function(draggable, droppable) {
// custom data for images
droppable.fire('wjfe:item:drop', WysijaForm.getFieldData(draggable));
$(droppable).removeClassName('hover');
window.$(droppable).removeClassName('hover');
}
},
hideControls: function() {
@ -573,7 +579,7 @@ var WysijaForm = {
}
},
hideTools: function() {
$$('.wysija_tools').invoke('hide');
window.$$('.wysija_tools').invoke('hide');
WysijaForm.locks.showingTools = false;
},
instances: {},
@ -588,11 +594,11 @@ var WysijaForm = {
return instance;
},
makeDroppable: function() {
Droppables.add('block_placeholder', WysijaForm.blockDropOptions);
window.Droppables.add('block_placeholder', WysijaForm.blockDropOptions);
},
makeSortable: function() {
var body = $(WysijaForm.options.body);
Sortable.create(body, {
var body = window.$(WysijaForm.options.body);
window.Sortable.create(body, {
tag: 'div',
only: 'mailpoet_form_block',
scroll: window,
@ -600,15 +606,15 @@ var WysijaForm = {
constraint: 'vertical'
});
Draggables.removeObserver(body);
Draggables.addObserver({
window.Draggables.removeObserver(body);
window.Draggables.addObserver({
element: body,
onStart: WysijaForm.startBlockPositions,
onEnd: WysijaForm.setBlockPositions
});
},
hideBlockControls: function() {
$$('.wysija_controls').invoke('hide');
window.$$('.wysija_controls').invoke('hide');
this.getBlockElements().invoke('removeClassName', 'hover');
},
getBlocks: function() {
@ -617,7 +623,7 @@ var WysijaForm = {
});
},
getBlockElements: function() {
return $(WysijaForm.options.container).select('.mailpoet_form_block');
return window.$(WysijaForm.options.container).select('.mailpoet_form_block');
},
startBlockPositions: function(event, target) {
if(target.element.hasClassName('mailpoet_form_block')) {
@ -665,14 +671,14 @@ var WysijaForm = {
}
};
WysijaForm.DraggableItem = Class.create({
WysijaForm.DraggableItem = window.Class.create({
initialize: function(element) {
this.elementType = $(element).readAttribute('wysija_type');
this.element = $(element).down() || $(element);
this.elementType = window.$(element).readAttribute('wysija_type');
this.element = window.$(element).down() || window.$(element);
this.clone = this.cloneElement();
this.insert();
},
STYLES: new Template('position: absolute; top: #{top}px; left: #{left}px;'),
STYLES: new window.Template('position: absolute; top: #{top}px; left: #{left}px;'),
cloneElement: function() {
var clone = this.element.clone(),
offset = this.element.cumulativeOffset(),
@ -695,27 +701,27 @@ WysijaForm.DraggableItem = Class.create({
return this.element.up('ul');
},
insert: function() {
$$('body')[0].insert(this.clone);
window.$$('body')[0].insert(this.clone);
},
onMousedown: function(event) {
var draggable = new Draggable(this.clone, {
var draggable = new window.Draggable(this.clone, {
scroll: window,
onStart: function() {
Droppables.displayArea(draggable);
window.Droppables.displayArea(draggable);
},
onEnd: function(drag) {
drag.destroy();
drag.element.remove();
Droppables.hideArea();
window.Droppables.hideArea();
},
starteffect: function(element) {
new Effect.Opacity(element, {
new window.Effect.Opacity(element, {
duration: 0.2,
from: element.getOpacity(),
to: 0.7
});
},
endeffect: Prototype.emptyFunction
endeffect: window.Prototype.emptyFunction
});
draggable.initDrag(event);
draggable.startDrag(event);
@ -725,12 +731,12 @@ WysijaForm.DraggableItem = Class.create({
Object.extend(WysijaForm.DraggableItem, Observable).observe('a[class="mailpoet_form_field"]');
WysijaForm.Block = Class.create({
WysijaForm.Block = window.Class.create({
/* Invoked on load */
initialize: function(element) {
info('block -> init');
this.element = $(element);
this.element = window.$(element);
this.block = new WysijaForm.Widget(this.element);
// enable block placeholder
@ -763,14 +769,14 @@ WysijaForm.Block = Class.create({
makeBlockDroppable: function() {
if(this.isBlockDroppableEnabled() === false) {
var block_placeholder = this.getBlockDroppable();
Droppables.add(block_placeholder.identify(), WysijaForm.blockDropOptions);
window.Droppables.add(block_placeholder.identify(), WysijaForm.blockDropOptions);
block_placeholder.addClassName('enabled');
}
},
removeBlockDroppable: function() {
if(this.isBlockDroppableEnabled()) {
var block_placeholder = this.getBlockDroppable();
Droppables.remove(block_placeholder.identify());
window.Droppables.remove(block_placeholder.identify());
block_placeholder.removeClassName('enabled');
}
},
@ -786,7 +792,7 @@ WysijaForm.Block = Class.create({
createBlockDroppable: function() {
info('block -> createBlockDroppable');
this.element.insert({
before: '<div class=\"block_placeholder\">' + $('block_placeholder').innerHTML + '</div>'
before: '<div class=\"block_placeholder\">' + window.$('block_placeholder').innerHTML + '</div>'
});
return this.element.previous('.block_placeholder');
},
@ -851,7 +857,7 @@ WysijaForm.Block = Class.create({
if(this.settingsButton !== null) {
this.settingsButton.observe('click', function(event) {
// TODO: refactor
var block = $(event.target).up('.mailpoet_form_block') || null;
var block = window.$(event.target).up('.mailpoet_form_block') || null;
if(block !== null) {
var field = WysijaForm.getFieldData(block);
this.editSettings();
@ -867,7 +873,7 @@ WysijaForm.Block = Class.create({
// save block in history
WysijaHistory.enqueue(this.element);
Effect.Fade(this.element.identify(), {
window.Effect.Fade(this.element.identify(), {
duration: 0.2,
afterFinish: function(effect) {
// remove placeholder
@ -899,20 +905,20 @@ WysijaForm.Block = Class.create({
/* Invoked on item dropped */
WysijaForm.Block.create = function(createBlock, target) {
var block = createBlock;
if($('form_template_' + block.type) === null) {
if(window.$('form_template_' + block.type) === null) {
return false;
}
var body = $(WysijaForm.options.body),
block_template = Handlebars.compile($('form_template_block').innerHTML),
template = Handlebars.compile($('form_template_' + block.type).innerHTML),
var body = window.$(WysijaForm.options.body),
block_template = window.Handlebars.compile(window.$('form_template_block').innerHTML),
template = window.Handlebars.compile(window.$('form_template_' + block.type).innerHTML),
output = '';
if(block.type === 'segment') {
if(block.params.values === undefined) {
var settings_segments = jQuery('#mailpoet_form_segments').val();
var settings_segments = window.jQuery('#mailpoet_form_segments').val();
if(settings_segments !== null && settings_segments.length > 0){
block.params.values = mailpoet_segments.filter(function(segment) {
block.params.values = window.mailpoet_segments.filter(function(segment) {
return (settings_segments.indexOf(segment.id) !== -1);
});
}
@ -967,10 +973,10 @@ document.observe('wjfe:item:drop', function(event) {
});
/* Form Widget */
WysijaForm.Widget = Class.create(WysijaForm.Block, {
WysijaForm.Widget = window.Class.create(WysijaForm.Block, {
initialize: function(element) {
info('widget -> init');
this.element = $(element);
this.element = window.$(element);
return this;
},
setup: function() {
@ -989,7 +995,7 @@ WysijaForm.Widget = Class.create(WysijaForm.Block, {
},
setData: function(data) {
var current_data = this.getData(),
params = $H(current_data.params).merge(data.params).toObject();
params = window.$H(current_data.params).merge(data.params).toObject();
// update type if it changed
if(data.type !== undefined && data.type !== current_data.type) {
@ -1018,9 +1024,9 @@ WysijaForm.Widget = Class.create(WysijaForm.Block, {
this.setData(data);
var options = this.getData();
// redraw block
var block_template = Handlebars.compile($('form_template_block').innerHTML),
template = Handlebars.compile($('form_template_' + options.type).innerHTML),
data = $H(options).merge({
var block_template = window.Handlebars.compile(window.$('form_template_block').innerHTML),
template = window.Handlebars.compile(window.$('form_template_' + options.type).innerHTML),
data = window.$H(options).merge({
template: template(options)
}).toObject();
this.element.replace(block_template(data));
@ -1028,12 +1034,12 @@ WysijaForm.Widget = Class.create(WysijaForm.Block, {
WysijaForm.init();
},
editSettings: function() {
MailPoet.Modal.popup({
title: MailPoet.I18n.t('editFieldSettings'),
template: jQuery('#form_template_field_settings').html(),
window.MailPoet.Modal.popup({
title: window.MailPoet.I18n.t('editFieldSettings'),
template: window.jQuery('#form_template_field_settings').html(),
data: this.getData(),
onSuccess: function() {
var data = jQuery('#form_field_settings').serializeObject();
var data = window.jQuery('#form_field_settings').serializeObject();
this.redraw(data);
}.bind(this)
});

View File

@ -2,7 +2,7 @@ import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, useRouterHistory } from 'react-router';
import { createHashHistory } from 'history';
import FormList from 'forms/list.jsx';
import FormList from './list.jsx';
const history = useRouterHistory(createHashHistory)({ queryKey: false });

View File

@ -1,7 +1,8 @@
import React from 'react';
import Listing from 'listing/listing.jsx';
import classNames from 'classnames';
import MailPoet from 'mailpoet';
import jQuery from 'jquery';
import Listing from '../listing/listing.jsx';
const columns = [
{
@ -128,7 +129,7 @@ const FormList = React.createClass({
endpoint: 'forms',
action: 'create',
}).done((response) => {
window.location = mailpoet_form_edit_url + response.data.id;
window.location = window.mailpoet_form_edit_url + response.data.id;
}).fail((response) => {
if (response.errors.length > 0) {
MailPoet.Notice.error(
@ -145,7 +146,7 @@ const FormList = React.createClass({
'has-row-actions'
);
let segments = mailpoet_segments.filter((segment) => {
let segments = window.mailpoet_segments.filter((segment) => {
return (jQuery.inArray(segment.id, form.segments) !== -1);
}).map((segment) => {
return segment.name;
@ -190,7 +191,7 @@ const FormList = React.createClass({
</h1>
<Listing
limit={ mailpoet_listing_per_page }
limit={ window.mailpoet_listing_per_page }
location={ this.props.location }
params={ this.props.params }
messages={ messages }

View File

@ -1,31 +1,31 @@
define('handlebars_helpers', ['handlebars'], function(Handlebars) {
// Handlebars helpers
Handlebars.registerHelper('concat', function() {
var size = (arguments.length - 1),
output = '';
for(var i = 0; i < size; i++) {
output += arguments[i];
}
return output;
var size = (arguments.length - 1),
output = '';
for(var i = 0; i < size; i++) {
output += arguments[i];
}
return output;
});
Handlebars.registerHelper('number_format', function(value, block) {
return Number(value).toLocaleString();
return Number(value).toLocaleString();
});
Handlebars.registerHelper('date_format', function(timestamp, block) {
if(window.moment) {
if(timestamp === undefined || isNaN(timestamp) || timestamp <= 0) {
return;
}
if(timestamp === undefined || isNaN(timestamp) || timestamp <= 0) {
return;
}
// set date format
var f = block.hash.format || 'MMM Do, YYYY';
var f = block.hash.format || 'MMM Do, YYYY';
// check if we passed a timestamp
if(parseInt(timestamp, 10) == timestamp) {
return moment.unix(timestamp).format(f);
} else {
return moment.utc(timestamp).format(f);
}
if(parseInt(timestamp, 10) == timestamp) {
return window.moment.unix(timestamp).format(f);
} else {
return window.moment.utc(timestamp).format(f);
}
} else {
return timestamp;
}
@ -37,81 +37,81 @@ define('handlebars_helpers', ['handlebars'], function(Handlebars) {
});
Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
switch (operator) {
case '==':
return (v1 == v2) ? options.fn(this) : options.inverse(this);
case '===':
return (v1 === v2) ? options.fn(this) : options.inverse(this);
case '!=':
return (v1 != v2) ? options.fn(this) : options.inverse(this);
case '!==':
return (v1 !== v2) ? options.fn(this) : options.inverse(this);
case '<':
return (v1 < v2) ? options.fn(this) : options.inverse(this);
case '<=':
return (v1 <= v2) ? options.fn(this) : options.inverse(this);
case '>':
return (v1 > v2) ? options.fn(this) : options.inverse(this);
case '>=':
return (v1 >= v2) ? options.fn(this) : options.inverse(this);
case '&&':
return (v1 && v2) ? options.fn(this) : options.inverse(this);
case '||':
return (v1 || v2) ? options.fn(this) : options.inverse(this);
case 'in':
var values = v2.split(',');
return (v2.indexOf(v1) !== -1) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
switch (operator) {
case '==':
return (v1 == v2) ? options.fn(this) : options.inverse(this);
case '===':
return (v1 === v2) ? options.fn(this) : options.inverse(this);
case '!=':
return (v1 != v2) ? options.fn(this) : options.inverse(this);
case '!==':
return (v1 !== v2) ? options.fn(this) : options.inverse(this);
case '<':
return (v1 < v2) ? options.fn(this) : options.inverse(this);
case '<=':
return (v1 <= v2) ? options.fn(this) : options.inverse(this);
case '>':
return (v1 > v2) ? options.fn(this) : options.inverse(this);
case '>=':
return (v1 >= v2) ? options.fn(this) : options.inverse(this);
case '&&':
return (v1 && v2) ? options.fn(this) : options.inverse(this);
case '||':
return (v1 || v2) ? options.fn(this) : options.inverse(this);
case 'in':
var values = v2.split(',');
return (v2.indexOf(v1) !== -1) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});
Handlebars.registerHelper('nl2br', function(value, block) {
return value.gsub('\n', '<br />');
return value.gsub('\n', '<br />');
});
Handlebars.registerHelper('json_encode', function(value, block) {
return JSON.stringify(value);
return JSON.stringify(value);
});
Handlebars.registerHelper('json_decode', function(value, block) {
return JSON.parse(value);
return JSON.parse(value);
});
Handlebars.registerHelper('url', function(value, block) {
var url = window.location.protocol + '//' + window.location.host + window.location.pathname;
var url = window.location.protocol + '//' + window.location.host + window.location.pathname;
return url + value;
return url + value;
});
Handlebars.registerHelper('emailFromMailto', function(value) {
var mailtoMatchingRegex = /^mailto\:/i;
if (typeof value === 'string' && value.match(mailtoMatchingRegex)) {
return value.replace(mailtoMatchingRegex, '');
} else {
return value;
}
var mailtoMatchingRegex = /^mailto\:/i;
if (typeof value === 'string' && value.match(mailtoMatchingRegex)) {
return value.replace(mailtoMatchingRegex, '');
} else {
return value;
}
});
Handlebars.registerHelper('lookup', function(obj, field, options) {
return obj && obj[field];
return obj && obj[field];
});
Handlebars.registerHelper('rsa_key', function(value, block) {
// extract all lines into an array
if(value === undefined) return '';
if(value === undefined) return '';
var lines = value.trim().split('\n');
var lines = value.trim().split('\n');
// remove header & footer
lines.shift();
lines.pop();
lines.shift();
lines.pop();
// return concatenated lines
return lines.join('');
return lines.join('');
});
Handlebars.registerHelper('trim', function(value, block) {
if(value === null || value === undefined) return '';
return value.trim();
if(value === null || value === undefined) return '';
return value.trim();
});
/**
@ -125,20 +125,20 @@ define('handlebars_helpers', ['handlebars'], function(Handlebars) {
* @return {String} The truncated string.
*/
Handlebars.registerHelper('ellipsis', function (str, limit, append) {
var strAppend = append;
if (strAppend === undefined) {
strAppend = '';
}
var sanitized = str.replace(/(<([^>]+)>)/g, '');
if (sanitized.length > limit) {
return sanitized.substr(0, limit - strAppend.length) + strAppend;
} else {
return sanitized;
}
var strAppend = append;
if (strAppend === undefined) {
strAppend = '';
}
var sanitized = str.replace(/(<([^>]+)>)/g, '');
if (sanitized.length > limit) {
return sanitized.substr(0, limit - strAppend.length) + strAppend;
} else {
return sanitized;
}
});
Handlebars.registerHelper('getNumber', function (string) {
return parseInt(string, 10);
return parseInt(string, 10);
});
Handlebars.registerHelper('fontWithFallback', function(font) {

View File

@ -34,15 +34,15 @@ function Tooltip(props) {
data-for={tooltipId}
>
</span>
<ReactTooltip
globalEventOff="click"
multiline={true}
id={tooltipId}
efect="solid"
place={props.place}
<ReactTooltip
globalEventOff="click"
multiline={true}
id={tooltipId}
efect="solid"
place={props.place}
>
{tooltip}
</ReactTooltip>
{tooltip}
</ReactTooltip>
</span>
);
}

View File

@ -4,22 +4,22 @@ define('i18n',
], function(
mp
) {
'use strict';
'use strict';
var MailPoet = mp;
var MailPoet = mp;
var translations = {};
var translations = {};
MailPoet.I18n = {
add: function(key, value) {
translations[key] = value;
},
t: function(key) {
return translations[key] || 'TRANSLATION "%$1s" NOT FOUND'.replace('%$1s', key);
},
all: function() {
return translations;
}
};
MailPoet.I18n = {
add: function(key, value) {
translations[key] = value;
},
t: function(key) {
return translations[key] || 'TRANSLATION "%$1s" NOT FOUND'.replace('%$1s', key);
},
all: function() {
return translations;
}
};
});
});

View File

@ -112,7 +112,7 @@ define([
defaultValue={MailPoet.I18n.t('apply')}
className="button action" />
{ this.state.extra }
{ this.state.extra }
</div>
);
},

View File

@ -56,14 +56,14 @@ define([
key={ `filter-${i}` }
name={ filter }
>
{ filters[filter].map((option, j) => {
return (
<option
value={ option.value }
key={ 'filter-option-' + j }
{ filters[filter].map((option, j) => {
return (
<option
value={ option.value }
key={ 'filter-option-' + j }
>{ option.label }</option>
);
}) }
);
}) }
</select>
);
});

View File

@ -15,22 +15,22 @@ define(['react', 'classnames'], (React, classNames) => {
);
return (
<li key={index}>
{(index > 0) ? ' |' : ''}
<a
href="javascript:;"
className={classes}
onClick={this.handleSelect.bind(this, group.name)} >
{group.label} <span className="count">({ group.count.toLocaleString() })</span>
</a>
</li>
<li key={index}>
{(index > 0) ? ' |' : ''}
<a
href="javascript:;"
className={classes}
onClick={this.handleSelect.bind(this, group.name)} >
{group.label} <span className="count">({ group.count.toLocaleString() })</span>
</a>
</li>
);
});
return (
<ul className="subsubsub">
{ groups }
</ul>
<ul className="subsubsub">
{ groups }
</ul>
);
},
});

View File

@ -24,7 +24,7 @@ define([
<form name="search" onSubmit={this.handleSearch}>
<p className="search-box">
<label htmlFor="search_input" className="screen-reader-text">
{MailPoet.I18n.t('searchLabel')}
{MailPoet.I18n.t('searchLabel')}
</label>
<input
type="search"

View File

@ -112,9 +112,8 @@ define('modal', ['mailpoet', 'jquery'],
if(this.renderer === 'html') {
return function() { return template; };
} else {
return Handlebars.compile(template);
return window.Handlebars.compile(template);
}
return false;
},
init: function(options) {
if(this.initialized === true) {
@ -182,24 +181,24 @@ define('modal', ['mailpoet', 'jquery'],
initOverlay: function(toggle) {
if(jQuery('#mailpoet_modal_overlay').length === 0) {
// insert overlay into the DOM
jQuery('body').append(this.templates.overlay);
jQuery('body').append(this.templates.overlay);
// insert loading indicator into overlay
jQuery('#mailpoet_modal_overlay').append(this.templates.loading);
}
return this;
},
toggleOverlay: function(toggle) {
if(toggle === true) {
jQuery('#mailpoet_modal_overlay')
jQuery('#mailpoet_modal_overlay').append(this.templates.loading);
}
return this;
},
toggleOverlay: function(toggle) {
if(toggle === true) {
jQuery('#mailpoet_modal_overlay')
.removeClass('mailpoet_overlay_hidden');
} else {
jQuery('#mailpoet_modal_overlay')
} else {
jQuery('#mailpoet_modal_overlay')
.addClass('mailpoet_overlay_hidden');
}
}
return this;
},
setupEvents: function() {
return this;
},
setupEvents: function() {
// close popup when user clicks on close button
jQuery('#mailpoet_modal_close').on('click', this.cancel.bind(this));
@ -250,39 +249,39 @@ define('modal', ['mailpoet', 'jquery'],
loadTemplate: function() {
if(this.subpanels.length > 0) {
// hide panel
jQuery('.mailpoet_'+this.options.type+'_wrapper').hide();
jQuery('.mailpoet_'+this.options.type+'_wrapper').hide();
// add sub panel wrapper
jQuery('#mailpoet_'+this.options.type)
jQuery('#mailpoet_'+this.options.type)
.append(this.templates['subpanel']);
// add sub panel content
jQuery('.mailpoet_'+this.options.type+'_body').last()
jQuery('.mailpoet_'+this.options.type+'_body').last()
.html(this.subpanels[(this.subpanels.length - 1)].element);
// focus on sub panel
if(this.options.focus) {
this.focus();
}
} else if (this.options.element) {
jQuery('.mailpoet_'+this.options.type+'_body').empty();
jQuery('.mailpoet_'+this.options.type+'_body')
if(this.options.focus) {
this.focus();
}
} else if (this.options.element) {
jQuery('.mailpoet_'+this.options.type+'_body').empty();
jQuery('.mailpoet_'+this.options.type+'_body')
.append(this.options.element);
} else {
jQuery('.mailpoet_'+this.options.type+'_body')
} else {
jQuery('.mailpoet_'+this.options.type+'_body')
.html(
this.options.body_template(
this.options.data
)
);
}
}
return this;
},
loadUrl: function() {
if(this.options.method === 'get') {
return this;
},
loadUrl: function() {
if(this.options.method === 'get') {
// make ajax request
jQuery.getJSON(this.options.url,
jQuery.getJSON(this.options.url,
function(data) {
this.options.data = jQuery.extend({}, this.options.data, data);
// load template using fetched data
@ -291,9 +290,9 @@ define('modal', ['mailpoet', 'jquery'],
this.showModal();
}.bind(this)
);
} else if(this.options.method === 'post') {
} else if(this.options.method === 'post') {
// make ajax request
jQuery.post(this.options.url, JSON.stringify(this.options.params),
jQuery.post(this.options.url, JSON.stringify(this.options.params),
function(data) {
this.options.data = jQuery.extend({}, this.options.data, data);
// load template using fetched data
@ -303,342 +302,342 @@ define('modal', ['mailpoet', 'jquery'],
}.bind(this),
'json'
);
}
}
return this;
},
setDimensions: function() {
switch(this.options.type) {
case 'popup':
return this;
},
setDimensions: function() {
switch(this.options.type) {
case 'popup':
// set popup dimensions
jQuery('#mailpoet_popup').css({
width: this.options.width,
height: this.options.height
});
jQuery('#mailpoet_popup').css({
width: this.options.width,
height: this.options.height
});
// set popup wrapper height
jQuery('#mailpoet_popup_wrapper').css({
height: this.options.height
});
jQuery('#mailpoet_popup_wrapper').css({
height: this.options.height
});
break;
case 'panel':
case 'panel':
// set dimensions
if(this.options.position === 'right') {
jQuery('#mailpoet_panel').css({
width: this.options.width,
right: 0,
marginRight: '-' + this.options.width,
left: 'auto'
});
} else if(this.options.position === 'left') {
jQuery('#mailpoet_panel').css({
width: this.options.width,
left: 0,
marginLeft: '-' + this.options.width,
right: 'auto'
});
}
jQuery('#mailpoet_panel').css({ minHeight: 'auto' });
if(this.options.position === 'right') {
jQuery('#mailpoet_panel').css({
width: this.options.width,
right: 0,
marginRight: '-' + this.options.width,
left: 'auto'
});
} else if(this.options.position === 'left') {
jQuery('#mailpoet_panel').css({
width: this.options.width,
left: 0,
marginLeft: '-' + this.options.width,
right: 'auto'
});
}
jQuery('#mailpoet_panel').css({ minHeight: 'auto' });
break;
}
}
return this;
},
setPosition: function() {
switch(this.options.type) {
case 'popup':
var screenWidth = jQuery(window).width(),
return this;
},
setPosition: function() {
switch(this.options.type) {
case 'popup':
var screenWidth = jQuery(window).width(),
screenHeight = jQuery(window).height(),
modalWidth = jQuery('.mailpoet_'+ this.options.type +'_wrapper').width(),
modalHeight = jQuery('.mailpoet_'+ this.options.type +'_wrapper').height();
var top = Math.max(48, parseInt((screenHeight / 2) - (modalHeight / 2))),
var top = Math.max(48, parseInt((screenHeight / 2) - (modalHeight / 2))),
left = Math.max(0, parseInt((screenWidth / 2) - (modalWidth / 2)));
// set position of popup depending on screen dimensions.
jQuery('#mailpoet_popup').css({
top: top,
left: left
});
jQuery('#mailpoet_popup').css({
top: top,
left: left
});
break;
case 'panel':
setTimeout(function() {
case 'panel':
setTimeout(function() {
// set position of popup depending on screen dimensions.
if(this.options.position === 'right') {
jQuery('#mailpoet_panel').css({
marginRight: 0
});
} else if(this.options.position === 'left') {
jQuery('#mailpoet_panel').css({
marginLeft: 0
});
}
}.bind(this), 0);
if(this.options.position === 'right') {
jQuery('#mailpoet_panel').css({
marginRight: 0
});
} else if(this.options.position === 'left') {
jQuery('#mailpoet_panel').css({
marginLeft: 0
});
}
}.bind(this), 0);
break;
}
}
return this;
},
showModal: function() {
return this;
},
showModal: function() {
// set modal dimensions
this.setDimensions();
this.setDimensions();
// remember the previously focused element
this.prevFocus = jQuery(':focus');
this.prevFocus = jQuery(':focus');
// add a flag on the body so that we can prevent scrolling
jQuery('body').addClass('mailpoet_modal_opened');
jQuery('body').addClass('mailpoet_modal_opened');
// show popup
jQuery('#mailpoet_'+this.options.type).show();
jQuery('#mailpoet_'+this.options.type).show();
// display overlay
this.showOverlay();
this.showOverlay();
// set modal position
this.setPosition();
this.setPosition();
// add class on highlighted elements
if(this.options.highlight !== null) {
if(this.options.highlight.length > 0) {
this.highlightOn(this.options.highlight);
}
if(this.options.highlight !== null) {
if(this.options.highlight.length > 0) {
this.highlightOn(this.options.highlight);
}
}
if(this.options.focus) {
this.focus();
}
// set popup as opened
this.opened = true;
// trigger init event if specified
if(this.options.onInit !== null) {
this.options.onInit(this);
}
return this;
},
focus: function() {
if(this.options.type == 'popup') {
jQuery('#mailpoet_'+this.options.type).focus();
} else {
// panel and subpanel
jQuery('#mailpoet_'+this.options.type+' .mailpoet_panel_wrapper')
.filter(':visible').focus();
}
return this;
},
highlightOn: function(element) {
jQuery(element).addClass('mailpoet_modal_highlight');
return this;
},
highlightOff: function() {
jQuery('.mailpoet_modal_highlight')
.removeClass('mailpoet_modal_highlight');
return this;
},
hideModal: function(callback) {
// set modal as closed
this.opened = false;
// hide modal
jQuery('#mailpoet_'+this.options.type).hide();
// remove class on highlighted elements
this.highlightOff();
// remove class from body to let it be scrollable
jQuery('body').removeClass('mailpoet_modal_opened');
return this;
},
showOverlay: function(force) {
jQuery('#mailpoet_modal_overlay').show();
return this;
},
hideOverlay: function() {
jQuery('#mailpoet_modal_overlay').hide();
return this;
},
popup: function(opts) {
// get options
var options = opts || {};
// set modal type
options.type = 'popup';
// set overlay state
options.overlay = options.overlay || true;
// initialize modal
this.init(options);
// open modal
this.open();
return this;
},
panel: function(opts) {
// get options
var options = opts || {};
// reset subpanels
this.subpanels = [];
// set modal type
options.type = 'panel';
// set overlay state
options.overlay = options.overlay || false;
// set highlighted element
options.highlight = options.highlight || null;
// set modal dimensions
options.width = options.width || '40%';
options.height = options.height || 'auto';
// initialize modal
this.init(options);
// open modal
this.open();
return this;
},
subpanel: function(options) {
if(this.opened === false) {
// if no panel is already opened, let's create one instead
this.panel(options);
} else {
// if a panel is already opened, add a sub panel to it
this.subpanels.push(options);
this.loadTemplate();
}
return this;
},
loading: function(toggle) {
// make sure the overlay is initialized and that it's visible
this.initOverlay(true);
if(toggle === true) {
this.showLoading();
} else {
this.hideLoading();
}
return this;
},
showLoading: function() {
jQuery('#mailpoet_loading').show();
// add loading class to overlay
jQuery('#mailpoet_modal_overlay')
.addClass('mailpoet_overlay_loading');
return this;
},
hideLoading: function() {
jQuery('#mailpoet_loading').hide();
// remove loading class from overlay
jQuery('#mailpoet_modal_overlay')
.removeClass('mailpoet_overlay_loading');
return this;
},
open: function() {
// load template if specified
if(this.options.template !== null) {
// check if a url was specified to get extra data
if(this.options.url !== null) {
this.loadUrl();
} else {
// load template
this.loadTemplate();
// show modal window
this.showModal();
}
} else {
this.cancel();
}
return this;
},
success: function() {
if(this.subpanels.length > 0) {
if(this.subpanels[(this.subpanels.length - 1)].onSuccess !== undefined) {
this.subpanels[(this.subpanels.length - 1)].onSuccess(this.subpanels[(this.subpanels.length - 1)].data);
}
} else {
if(this.options.onSuccess !== null) {
this.options.onSuccess(this.options.data);
}
}
this.close();
return this;
},
cancel: function() {
if(this.subpanels.length > 0) {
if(this.subpanels[(this.subpanels.length - 1)].onCancel !== undefined) {
this.subpanels[(this.subpanels.length - 1)].onCancel(this.subpanels[(this.subpanels.length - 1)].data);
}
} else {
if(this.options.onCancel !== null) {
this.options.onCancel(this.options.data);
}
}
this.close();
return this;
},
destroy: function() {
this.hideOverlay();
// remove extra modal
if(jQuery('#mailpoet_'+this.options.type).length > 0) {
jQuery('#mailpoet_'+this.options.type).remove();
}
this.initialized = false;
return this;
},
close: function() {
if(this.isLocked() === true) { return this; }
if(this.subpanels.length > 0) {
// close subpanel
jQuery('.mailpoet_'+this.options.type+'_wrapper').last().remove();
// show previous panel
jQuery('.mailpoet_'+this.options.type+'_wrapper').last().show();
// remove last subpanels
this.subpanels.pop();
// focus on previous panel
if(this.options.focus) {
this.focus();
}
// set popup as opened
this.opened = true;
// trigger init event if specified
if(this.options.onInit !== null) {
this.options.onInit(this);
}
return this;
},
focus: function() {
if(this.options.type == 'popup') {
jQuery('#mailpoet_'+this.options.type).focus();
} else {
// panel and subpanel
jQuery('#mailpoet_'+this.options.type+' .mailpoet_panel_wrapper')
.filter(':visible').focus();
}
return this;
},
highlightOn: function(element) {
jQuery(element).addClass('mailpoet_modal_highlight');
return this;
},
highlightOff: function() {
jQuery('.mailpoet_modal_highlight')
.removeClass('mailpoet_modal_highlight');
return this;
},
hideModal: function(callback) {
// set modal as closed
this.opened = false;
// hide modal
jQuery('#mailpoet_'+this.options.type).hide();
// remove class on highlighted elements
this.highlightOff();
// remove class from body to let it be scrollable
jQuery('body').removeClass('mailpoet_modal_opened');
return this;
},
showOverlay: function(force) {
jQuery('#mailpoet_modal_overlay').show();
return this;
},
hideOverlay: function() {
jQuery('#mailpoet_modal_overlay').hide();
return this;
},
popup: function(opts) {
// get options
var options = opts || {};
// set modal type
options.type = 'popup';
// set overlay state
options.overlay = options.overlay || true;
// initialize modal
this.init(options);
// open modal
this.open();
return this;
},
panel: function(opts) {
// get options
var options = opts || {};
// reset subpanels
this.subpanels = [];
// set modal type
options.type = 'panel';
// set overlay state
options.overlay = options.overlay || false;
// set highlighted element
options.highlight = options.highlight || null;
// set modal dimensions
options.width = options.width || '40%';
options.height = options.height || 'auto';
// initialize modal
this.init(options);
// open modal
this.open();
return this;
},
subpanel: function(options) {
if(this.opened === false) {
// if no panel is already opened, let's create one instead
this.panel(options);
} else {
// if a panel is already opened, add a sub panel to it
this.subpanels.push(options);
this.loadTemplate();
}
return this;
},
loading: function(toggle) {
// make sure the overlay is initialized and that it's visible
this.initOverlay(true);
if(toggle === true) {
this.showLoading();
} else {
this.hideLoading();
}
return this;
},
showLoading: function() {
jQuery('#mailpoet_loading').show();
// add loading class to overlay
jQuery('#mailpoet_modal_overlay')
.addClass('mailpoet_overlay_loading');
return this;
},
hideLoading: function() {
jQuery('#mailpoet_loading').hide();
// remove loading class from overlay
jQuery('#mailpoet_modal_overlay')
.removeClass('mailpoet_overlay_loading');
return this;
},
open: function() {
// load template if specified
if(this.options.template !== null) {
// check if a url was specified to get extra data
if(this.options.url !== null) {
this.loadUrl();
} else {
// load template
this.loadTemplate();
// show modal window
this.showModal();
}
} else {
this.cancel();
}
return this;
},
success: function() {
if(this.subpanels.length > 0) {
if(this.subpanels[(this.subpanels.length - 1)].onSuccess !== undefined) {
this.subpanels[(this.subpanels.length - 1)].onSuccess(this.subpanels[(this.subpanels.length - 1)].data);
}
} else {
if(this.options.onSuccess !== null) {
this.options.onSuccess(this.options.data);
}
}
this.close();
return this;
},
cancel: function() {
if(this.subpanels.length > 0) {
if(this.subpanels[(this.subpanels.length - 1)].onCancel !== undefined) {
this.subpanels[(this.subpanels.length - 1)].onCancel(this.subpanels[(this.subpanels.length - 1)].data);
}
} else {
if(this.options.onCancel !== null) {
this.options.onCancel(this.options.data);
}
}
this.close();
return this;
},
destroy: function() {
this.hideOverlay();
// remove extra modal
if(jQuery('#mailpoet_'+this.options.type).length > 0) {
jQuery('#mailpoet_'+this.options.type).remove();
}
this.initialized = false;
return this;
},
close: function() {
if(this.isLocked() === true) { return this; }
if(this.subpanels.length > 0) {
// close subpanel
jQuery('.mailpoet_'+this.options.type+'_wrapper').last().remove();
// show previous panel
jQuery('.mailpoet_'+this.options.type+'_wrapper').last().show();
// remove last subpanels
this.subpanels.pop();
// focus on previous panel
if(this.options.focus) {
this.focus();
}
return this;
}
// remove event handlers
this.removeEvents();
// hide modal window
this.hideModal();
// destroy modal element
this.destroy();
// restore the previously focused element
if(this.prevFocus !== undefined){
this.prevFocus.focus();
}
// reset options
this.options = {
onSuccess: null,
onCancel: null
};
return this;
}
// remove event handlers
this.removeEvents();
// hide modal window
this.hideModal();
// destroy modal element
this.destroy();
// restore the previously focused element
if(this.prevFocus !== undefined){
this.prevFocus.focus();
}
// reset options
this.options = {
onSuccess: null,
onCancel: null
};
return this;
}
};
}
);

View File

@ -26,7 +26,7 @@ define('mp2migrator', ['mailpoet', 'jquery'], function(mp, jQuery) {
displayLogs: function () {
jQuery.ajax({
url: mailpoet_mp2_migrator.log_file_url,
url: window.mailpoet_mp2_migrator.log_file_url,
cache: false
}).done(function (result) {
jQuery('#logger').html('');
@ -53,7 +53,7 @@ define('mp2migrator', ['mailpoet', 'jquery'], function(mp, jQuery) {
updateProgressbar: function () {
jQuery.ajax({
url: mailpoet_mp2_migrator.progress_url,
url: window.mailpoet_mp2_migrator.progress_url,
cache: false,
dataType: 'json'
}).always(function (result) {

View File

@ -1,12 +1,12 @@
define([
'backbone',
'backbone.marionette',
'backbone.radio',
'jquery',
'underscore',
'handlebars',
'handlebars_helpers'
], function(Backbone, Marionette, BackboneRadio, jQuery, _, Handlebars) {
'backbone',
'backbone.marionette',
'backbone.radio',
'jquery',
'underscore',
'handlebars',
'handlebars_helpers'
], function(Backbone, Marionette, BackboneRadio, jQuery, _, Handlebars) {
var Radio = BackboneRadio;
var AppView = Marionette.View.extend({

View File

@ -5,8 +5,8 @@
* For more check: http://marionettejs.com/docs/marionette.behaviors.html#behaviorslookup
*/
define([
'backbone.marionette'
], function(BackboneMarionette) {
'backbone.marionette'
], function(BackboneMarionette) {
var Marionette = BackboneMarionette;
var BehaviorsLookup = {};
Marionette.Behaviors.behaviorsLookup = function() {

View File

@ -4,24 +4,44 @@
* Adds a color picker integration with the view
*/
define([
'backbone.marionette',
'newsletter_editor/behaviors/BehaviorsLookup',
'mailpoet',
'spectrum'
], function(Marionette, BehaviorsLookup, MailPoet, Spectrum) {
'backbone.marionette',
'newsletter_editor/behaviors/BehaviorsLookup',
'mailpoet',
'spectrum'
], function(Marionette, BehaviorsLookup, MailPoet, Spectrum) {
var BL = BehaviorsLookup;
BL.ColorPickerBehavior = Marionette.Behavior.extend({
onRender: function() {
this.view.$('.mailpoet_color').spectrum({
clickoutFiresChange: true,
showInput: true,
showInitial: true,
preferredFormat: 'hex6',
allowEmpty: true,
chooseText: MailPoet.I18n.t('selectColor'),
cancelText: MailPoet.I18n.t('cancelColorSelection')
});
var that = this,
preferredFormat = 'hex6';
this.view.$('.mailpoet_color').each(function () {
var $input = that.view.$(this);
var updateColorInput = function(color) {
if(color && color.getAlpha() > 0) {
$input.val(color.toString(preferredFormat));
} else {
$input.val('');
}
$input.trigger('change');
};
$input.spectrum({
clickoutFiresChange: true,
showInput: true,
showInitial: true,
showPalette: true,
showSelectionPalette: true,
palette: [],
localStorageKey: 'newsletter_editor.spectrum.palette',
preferredFormat: preferredFormat,
allowEmpty: true,
chooseText: MailPoet.I18n.t('selectColor'),
cancelText: MailPoet.I18n.t('cancelColorSelection'),
change: updateColorInput,
move: updateColorInput,
hide: updateColorInput
});
});
}
});
});

View File

@ -1,3 +1,4 @@
/**
* ContainerDropZoneBehavior
*
@ -6,12 +7,12 @@
* accept droppables
*/
define([
'backbone.marionette',
'underscore',
'jquery',
'newsletter_editor/behaviors/BehaviorsLookup',
'interact'
], function(Marionette, _, jQuery, BL, interact) {
'backbone.marionette',
'underscore',
'jquery',
'newsletter_editor/behaviors/BehaviorsLookup',
'interact'
], function(Marionette, _, jQuery, BL, interact) {
var BehaviorsLookup = BL;
BehaviorsLookup.ContainerDropZoneBehavior = Marionette.Behavior.extend({
@ -21,7 +22,7 @@ define([
onRender: function() {
var dragAndDropDisabled = _.isObject(this.view.options.renderOptions) && this.view.options.renderOptions.disableDragAndDrop === true;
if (!dragAndDropDisabled) {
this.addDropZone();
this.addDropZone();
}
},
addDropZone: function(_event) {
@ -195,8 +196,9 @@ define([
if (view.model.get('orientation') === 'horizontal' && droppableModel.get('type') !== 'container') {
// Regular blocks always need to be inserted into columns - vertical containers
tempCollection = new (EditorApplication.getBlockTypeModel('container'))({
orientation: 'vertical'
tempCollection = new (window.EditorApplication.getBlockTypeModel('container'))({
orientation: 'vertical'
});
tempCollection.get('blocks').add(droppableModel);
viewCollection.add(tempCollection, {at: index});
@ -210,27 +212,27 @@ define([
// and inserting dropModel into that
var tempModel = viewCollection.at(dropPosition.index);
tempCollection = new (EditorApplication.getBlockTypeModel('container'))({
orientation: (view.model.get('orientation') === 'vertical') ? 'horizontal' : 'vertical'
tempCollection = new (window.EditorApplication.getBlockTypeModel('container'))({
orientation: (view.model.get('orientation') === 'vertical') ? 'horizontal' : 'vertical'
});
viewCollection.remove(tempModel);
if (tempCollection.get('orientation') === 'horizontal') {
if (dropPosition.position === 'before') {
tempCollection2 = new (EditorApplication.getBlockTypeModel('container'))({
tempCollection2 = new (window.EditorApplication.getBlockTypeModel('container'))({
orientation: 'vertical'
});
tempCollection2.get('blocks').add(droppableModel);
tempCollection.get('blocks').add(tempCollection2);
}
tempCollection2 = new (EditorApplication.getBlockTypeModel('container'))({
tempCollection2 = new (window.EditorApplication.getBlockTypeModel('container'))({
orientation: 'vertical'
});
tempCollection2.get('blocks').add(tempModel);
tempCollection.get('blocks').add(tempCollection2);
if (dropPosition.position === 'after') {
tempCollection2 = new (EditorApplication.getBlockTypeModel('container'))({
tempCollection2 = new (window.EditorApplication.getBlockTypeModel('container'))({
orientation: 'vertical'
});
tempCollection2.get('blocks').add(droppableModel);
@ -291,7 +293,7 @@ define([
insertionType, index, position, indexAndPosition;
unsafe = !!is_unsafe;
var unsafe = !!is_unsafe;
if (this.getCollection().length === 0) {
return {
@ -377,14 +379,14 @@ define([
if (eventOffset <= closeOffset + elementDimension / 2) {
// First half of the element
return {
index: index,
position: 'before'
index: index,
position: 'before'
};
} else {
// Second half of the element
return {
index: index,
position: 'after'
index: index,
position: 'after'
};
}
},

View File

@ -5,12 +5,12 @@
* Part of the drag&drop behavior.
*/
define([
'backbone.marionette',
'underscore',
'jquery',
'newsletter_editor/behaviors/BehaviorsLookup',
'interact'
], function(Marionette, _, jQuery, BehaviorsLookup, interact) {
'backbone.marionette',
'underscore',
'jquery',
'newsletter_editor/behaviors/BehaviorsLookup',
'interact'
], function(Marionette, _, jQuery, BehaviorsLookup, interact) {
var BL = BehaviorsLookup;
BL.DraggableBehavior = Marionette.Behavior.extend({
@ -33,13 +33,13 @@ define([
},
onRender: function() {
var that = this,
interactable;
interactable;
// Give instances more control over whether Draggable should be applied
if (!this.options.testAttachToInstance(this.view.model, this.view)) return;
interactable = interact(this.$el.get(0), {
ignoreFrom: this.options.ignoreSelector
ignoreFrom: this.options.ignoreSelector
}).draggable({
// allow dragging of multple elements at the same time
max: Infinity,
@ -54,7 +54,7 @@ define([
// Use substitution instead of a clone
var tempClone = (_.isFunction(that.options.onDragSubstituteBy)) ? that.options.onDragSubstituteBy(that) : undefined,
// Or use a clone
clone = tempClone ? tempClone : event.target.cloneNode(true),
clone = tempClone || event.target.cloneNode(true),
$original = jQuery(event.target),
$clone = jQuery(clone),

View File

@ -0,0 +1,26 @@
/**
* Highlight Container Behavior
*
* Highlights a container block when hovering over its tools
*/
define([
'backbone.marionette',
'newsletter_editor/behaviors/BehaviorsLookup'
], function(Marionette, BehaviorsLookup) {
var BL = BehaviorsLookup;
BL.HighlightContainerBehavior = Marionette.Behavior.extend({
events: {
'mouseenter @ui.tools': 'enableHighlight',
'mouseleave @ui.tools': 'disableHighlight'
},
enableHighlight: function() {
this.$el.addClass('mailpoet_highlight');
},
disableHighlight: function() {
if (!this.view._isBeingEdited) {
this.$el.removeClass('mailpoet_highlight');
}
}
});
});

View File

@ -4,9 +4,9 @@
* Highlights a block that is being edited
*/
define([
'backbone.marionette',
'newsletter_editor/behaviors/BehaviorsLookup'
], function(Marionette, BehaviorsLookup) {
'backbone.marionette',
'newsletter_editor/behaviors/BehaviorsLookup'
], function(Marionette, BehaviorsLookup) {
var BL = BehaviorsLookup;
BL.HighlightEditingBehavior = Marionette.Behavior.extend({
@ -15,9 +15,11 @@ define([
stopEditing: 'disableHighlight'
},
enableHighlight: function() {
this.view._isBeingEdited = true;
this.$el.addClass('mailpoet_highlight');
},
disableHighlight: function() {
this.view._isBeingEdited = false;
this.$el.removeClass('mailpoet_highlight');
}
});

View File

@ -4,10 +4,10 @@
* Allows resizing elements within a block
*/
define([
'backbone.marionette',
'newsletter_editor/behaviors/BehaviorsLookup',
'interact'
], function(Marionette, BehaviorsLookup, interact) {
'backbone.marionette',
'newsletter_editor/behaviors/BehaviorsLookup',
'interact'
], function(Marionette, BehaviorsLookup, interact) {
var BL = BehaviorsLookup;
BL.ResizableBehavior = Marionette.Behavior.extend({
@ -31,7 +31,7 @@ define([
},
attachResize: function() {
var domElement = (this.options.elementSelector === null) ? this.view.$el.get(0) : this.view.$(this.options.elementSelector).get(0),
that = this;
that = this;
interact(domElement).resizable({
//axis: 'y',
edges: {

View File

@ -4,10 +4,10 @@
* Opens up settings of a BlockView if contents are clicked upon
*/
define([
'backbone.marionette',
'jquery',
'newsletter_editor/behaviors/BehaviorsLookup'
], function(Marionette, jQuery, BehaviorsLookup) {
'backbone.marionette',
'jquery',
'newsletter_editor/behaviors/BehaviorsLookup'
], function(Marionette, jQuery, BehaviorsLookup) {
var BL = BehaviorsLookup;
BL.ShowSettingsBehavior = Marionette.Behavior.extend({

View File

@ -4,10 +4,10 @@
* Allows sorting elements within a collection
*/
define([
'backbone.marionette',
'underscore',
'newsletter_editor/behaviors/BehaviorsLookup'
], function(Marionette, _, BehaviorsLookup) {
'backbone.marionette',
'underscore',
'newsletter_editor/behaviors/BehaviorsLookup'
], function(Marionette, _, BehaviorsLookup) {
var BL = BehaviorsLookup;
BL.SortableBehavior = Marionette.Behavior.extend({

View File

@ -4,10 +4,10 @@
* Adds TinyMCE text editing capabilities to a view
*/
define([
'backbone.marionette',
'underscore',
'newsletter_editor/behaviors/BehaviorsLookup'
], function(Marionette, _, BehaviorsLookup) {
'backbone.marionette',
'underscore',
'newsletter_editor/behaviors/BehaviorsLookup'
], function(Marionette, _, BehaviorsLookup) {
var BL = BehaviorsLookup;
BL.TextEditorBehavior = Marionette.Behavior.extend({
@ -65,7 +65,7 @@ define([
editor.focus();
if (that._isActivationClick) {
editor.selection.setRng(
tinymce.dom.RangeUtils.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc())
window.tinymce.dom.RangeUtils.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc())
);
that._isActivationClick = false;
}
@ -73,7 +73,7 @@ define([
editor.on('focus', function(e) {
that.view.triggerMethod('text:editor:focus');
that._isActivationClick = true;
that._isActivationClick = true;
});
editor.on('blur', function(e) {

View File

@ -7,31 +7,31 @@
* block settings view.
*/
define([
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'newsletter_editor/blocks/button',
'newsletter_editor/blocks/divider',
'newsletter_editor/components/communication',
'mailpoet',
'backbone.supermodel',
'underscore',
'jquery'
], function(
App,
BaseBlock,
ButtonBlock,
DividerBlock,
CommunicationComponent,
MailPoet,
SuperModel,
_,
jQuery
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'newsletter_editor/blocks/button',
'newsletter_editor/blocks/divider',
'newsletter_editor/components/communication',
'mailpoet',
'backbone.supermodel',
'underscore',
'jquery'
], function(
App,
BaseBlock,
ButtonBlock,
DividerBlock,
CommunicationComponent,
MailPoet,
SuperModel,
_,
jQuery
) {
'use strict';
var Module = {},
base = BaseBlock;
base = BaseBlock;
Module.ALCSupervisor = SuperModel.extend({
initialize: function() {
@ -61,7 +61,7 @@ define([
_.zip(models, renderedBlocks),
function(args) {
var model = args[0],
contents = args[1];
contents = args[1];
model.trigger('refreshPosts', contents);
}
);
@ -135,7 +135,7 @@ define([
}
App.getChannel().on('replaceAllButtonStyles', replaceButtonStylesHandler.bind(this));
},
getTemplate: function() { return templates.automatedLatestContentBlock; },
getTemplate: function() { return window.templates.automatedLatestContentBlock; },
regions: {
toolsRegion: '.mailpoet_tools',
postsRegion: '.mailpoet_automated_latest_content_block_posts'
@ -168,7 +168,7 @@ define([
// Sidebar view container
Module.AutomatedLatestContentBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.automatedLatestContentBlockSettings; },
getTemplate: function() { return window.templates.automatedLatestContentBlockSettings; },
events: function() {
return {
'click .mailpoet_automated_latest_content_hide_display_options': 'toggleDisplayOptions',
@ -350,7 +350,7 @@ define([
},
_updateContentTypes: function(postTypes) {
var select = this.$('.mailpoet_automated_latest_content_content_type'),
selectedValue = this.model.get('contentType');
selectedValue = this.model.get('contentType');
select.find('option').remove();
_.each(postTypes, function(type) {
@ -364,7 +364,7 @@ define([
});
Module.AutomatedLatestContentWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.automatedLatestContentInsertion; },
getTemplate: function() { return window.templates.automatedLatestContentInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -5,19 +5,19 @@
* BlockToolsView, BlockSettingsView and BlockWidgetView are optional.
*/
define([
'newsletter_editor/App',
'backbone.marionette',
'backbone.supermodel',
'underscore',
'jquery',
'mailpoet',
'modal'
], function(App, Marionette, SuperModel, _, jQuery, MailPoet, Modal) {
'newsletter_editor/App',
'backbone.marionette',
'backbone.supermodel',
'underscore',
'jquery',
'mailpoet',
'modal'
], function(App, Marionette, SuperModel, _, jQuery, MailPoet, Modal) {
'use strict';
var Module = {},
AugmentedView = Marionette.View.extend({});
AugmentedView = Marionette.View.extend({});
Module.BlockModel = SuperModel.extend({
stale: [], // Attributes to be removed upon saving
@ -178,7 +178,7 @@ define([
});
Module.BlockToolsView = AugmentedView.extend({
getTemplate: function() { return templates.genericBlockTools; },
getTemplate: function() { return window.templates.genericBlockTools; },
events: {
'click .mailpoet_edit_block': 'changeSettings',
'click .mailpoet_delete_block_activate': 'showDeletionConfirmation',
@ -275,7 +275,7 @@ define([
this.model.set(field, jQuery(event.target).val() + suffix);
},
changeBoolField: function(field, event) {
this.model.set(field, (jQuery(event.target).val() === 'true') ? true : false);
this.model.set(field, (jQuery(event.target).val() === 'true'));
},
changeBoolCheckboxField: function(field, event) {
this.model.set(field, (!!jQuery(event.target).prop('checked')));

View File

@ -2,17 +2,17 @@
* Button content block
*/
define([
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'mailpoet',
'underscore',
'jquery'
], function(App, BaseBlock, MailPoet, _, jQuery) {
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'mailpoet',
'underscore',
'jquery'
], function(App, BaseBlock, MailPoet, _, jQuery) {
'use strict';
var Module = {},
base = BaseBlock;
base = BaseBlock;
Module.ButtonBlockModel = base.BlockModel.extend({
defaults: function() {
@ -42,7 +42,7 @@ define([
Module.ButtonBlockView = base.BlockView.extend({
className: 'mailpoet_block mailpoet_button_block mailpoet_droppable_block',
getTemplate: function() { return templates.buttonBlock; },
getTemplate: function() { return window.templates.buttonBlock; },
onDragSubstituteBy: function() { return Module.ButtonWidgetView; },
behaviors: _.extend({}, base.BlockView.prototype.behaviors, {
ShowSettingsBehavior: {}
@ -65,7 +65,7 @@ define([
});
Module.ButtonBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.buttonBlockSettings; },
getTemplate: function() { return window.templates.buttonBlockSettings; },
events: function() {
return {
'input .mailpoet_field_button_text': _.partial(this.changeField, 'text'),
@ -121,7 +121,7 @@ define([
});
Module.ButtonWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.buttonInsertion; },
getTemplate: function() { return window.templates.buttonInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -4,19 +4,19 @@
* as other containers.
*/
define([
'backbone',
'backbone.marionette',
'underscore',
'jquery',
'newsletter_editor/App',
'newsletter_editor/blocks/base'
], function(Backbone, Marionette, _, jQuery, App, BaseBlock) {
'backbone',
'backbone.marionette',
'underscore',
'jquery',
'newsletter_editor/App',
'newsletter_editor/blocks/base'
], function(Backbone, Marionette, _, jQuery, App, BaseBlock) {
'use strict';
var Module = {},
base = BaseBlock,
BlockCollection;
base = BaseBlock,
BlockCollection;
BlockCollection = Backbone.Collection.extend({
model: base.BlockModel,
@ -103,7 +103,7 @@ define([
}
}),
className: 'mailpoet_block mailpoet_container_block mailpoet_droppable_block mailpoet_droppable_layout_block',
getTemplate: function() { return templates.containerBlock; },
getTemplate: function() { return window.templates.containerBlock; },
events: _.extend({}, base.BlockView.prototype.events, {
'click .mailpoet_newsletter_layer_selector': 'toggleEditingLayer'
}),
@ -138,7 +138,8 @@ define([
// for root and column containers.
return view.renderOptions.depth === 1;
}
}
},
HighlightContainerBehavior: {}
}),
onDragSubstituteBy: function() {
// For two and three column layouts display their respective widgets,
@ -217,7 +218,7 @@ define([
});
Module.ContainerBlockEmptyView = Marionette.View.extend({
getTemplate: function() { return templates.containerEmpty; },
getTemplate: function() { return window.templates.containerEmpty; },
initialize: function(options) {
this.renderOptions = _.defaults(options.renderOptions || {}, {});
},
@ -234,7 +235,7 @@ define([
});
Module.ContainerBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.containerBlockSettings; },
getTemplate: function() { return window.templates.containerBlockSettings; },
events: function() {
return {
'change .mailpoet_field_container_background_color': _.partial(this.changeColorField, 'styles.block.backgroundColor'),
@ -266,7 +267,7 @@ define([
});
Module.ContainerBlockColumnSettingsView = Marionette.View.extend({
getTemplate: function() { return templates.containerBlockColumnSettings; },
getTemplate: function() { return window.templates.containerBlockColumnSettings; },
initialize: function(options) {
this.columnNumber = (options.columnIndex || 0) + 1;
},
@ -280,7 +281,7 @@ define([
Module.OneColumnContainerWidgetView = base.WidgetView.extend({
className: base.WidgetView.prototype.className + ' mailpoet_droppable_layout_block',
getTemplate: function() { return templates.oneColumnLayoutInsertion; },
getTemplate: function() { return window.templates.oneColumnLayoutInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,
@ -298,7 +299,7 @@ define([
Module.TwoColumnContainerWidgetView = base.WidgetView.extend({
className: base.WidgetView.prototype.className + ' mailpoet_droppable_layout_block',
getTemplate: function() { return templates.twoColumnLayoutInsertion; },
getTemplate: function() { return window.templates.twoColumnLayoutInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,
@ -317,7 +318,7 @@ define([
Module.ThreeColumnContainerWidgetView = base.WidgetView.extend({
className: base.WidgetView.prototype.className + ' mailpoet_droppable_layout_block',
getTemplate: function() { return templates.threeColumnLayoutInsertion; },
getTemplate: function() { return window.templates.threeColumnLayoutInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -2,17 +2,17 @@
* Divider content block
*/
define([
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore',
'jquery',
'mailpoet'
], function(App, BaseBlock, _, jQuery, MailPoet) {
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore',
'jquery',
'mailpoet'
], function(App, BaseBlock, _, jQuery, MailPoet) {
'use strict';
var Module = {},
base = BaseBlock;
base = BaseBlock;
Module.DividerBlockModel = base.BlockModel.extend({
defaults: function() {
@ -33,7 +33,7 @@ define([
Module.DividerBlockView = base.BlockView.extend({
className: 'mailpoet_block mailpoet_divider_block mailpoet_droppable_block',
getTemplate: function() { return templates.dividerBlock; },
getTemplate: function() { return window.templates.dividerBlock; },
modelEvents: _.omit(base.BlockView.prototype.modelEvents, 'change'),
behaviors: _.defaults({
ResizableBehavior: {
@ -84,7 +84,7 @@ define([
});
Module.DividerBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.dividerBlockSettings; },
getTemplate: function() { return window.templates.dividerBlockSettings; },
events: function() {
return {
'click .mailpoet_field_divider_style': 'changeStyle',
@ -129,7 +129,7 @@ define([
});
Module.DividerWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.dividerInsertion; },
getTemplate: function() { return window.templates.dividerInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -2,15 +2,16 @@
* Footer content block
*/
define([
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore'
], function(App, BaseBlock, _) {
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore',
'mailpoet'
], function(App, BaseBlock, _, MailPoet) {
'use strict';
var Module = {},
base = BaseBlock;
base = BaseBlock;
Module.FooterBlockModel = base.BlockModel.extend({
defaults: function() {
@ -38,7 +39,7 @@ define([
Module.FooterBlockView = base.BlockView.extend({
className: 'mailpoet_block mailpoet_footer_block mailpoet_droppable_block',
getTemplate: function() { return templates.footerBlock; },
getTemplate: function() { return window.templates.footerBlock; },
modelEvents: _.extend({
'change:styles.block.backgroundColor change:styles.text.fontColor change:styles.text.fontFamily change:styles.text.fontSize change:styles.text.textAlign change:styles.link.fontColor change:styles.link.textDecoration': 'render'
}, _.omit(base.BlockView.prototype.modelEvents, 'change')),
@ -75,7 +76,7 @@ define([
});
Module.FooterBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.footerBlockSettings; },
getTemplate: function() { return window.templates.footerBlockSettings; },
events: function() {
return {
'change .mailpoet_field_footer_text_color': _.partial(this.changeColorField, 'styles.text.fontColor'),
@ -83,8 +84,8 @@ define([
'change .mailpoet_field_footer_text_size': _.partial(this.changeField, 'styles.text.fontSize'),
'change #mailpoet_field_footer_link_color': _.partial(this.changeColorField, 'styles.link.fontColor'),
'change #mailpoet_field_footer_link_underline': function(event) {
this.model.set('styles.link.textDecoration', (event.target.checked) ? event.target.value : 'none');
},
this.model.set('styles.link.textDecoration', (event.target.checked) ? event.target.value : 'none');
},
'change .mailpoet_field_footer_background_color': _.partial(this.changeColorField, 'styles.block.backgroundColor'),
'change .mailpoet_field_footer_alignment': _.partial(this.changeField, 'styles.text.textAlign'),
'click .mailpoet_done_editing': 'close'
@ -98,7 +99,7 @@ define([
});
Module.FooterWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.footerInsertion; },
getTemplate: function() { return window.templates.footerInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -2,15 +2,16 @@
* Header content block
*/
define([
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore'
], function(App, BaseBlock, _) {
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore',
'mailpoet'
], function(App, BaseBlock, _, MailPoet) {
'use strict';
var Module = {},
base = BaseBlock;
base = BaseBlock;
Module.HeaderBlockModel = base.BlockModel.extend({
defaults: function() {
@ -38,7 +39,7 @@ define([
Module.HeaderBlockView = base.BlockView.extend({
className: 'mailpoet_block mailpoet_header_block mailpoet_droppable_block',
getTemplate: function() { return templates.headerBlock; },
getTemplate: function() { return window.templates.headerBlock; },
modelEvents: _.extend({
'change:styles.block.backgroundColor change:styles.text.fontColor change:styles.text.fontFamily change:styles.text.fontSize change:styles.text.textAlign change:styles.link.fontColor change:styles.link.textDecoration': 'render'
}, _.omit(base.BlockView.prototype.modelEvents, 'change')),
@ -75,7 +76,7 @@ define([
});
Module.HeaderBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.headerBlockSettings; },
getTemplate: function() { return window.templates.headerBlockSettings; },
events: function() {
return {
'change .mailpoet_field_header_text_color': _.partial(this.changeColorField, 'styles.text.fontColor'),
@ -98,7 +99,7 @@ define([
});
Module.HeaderWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.headerInsertion; },
getTemplate: function() { return window.templates.headerInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -2,17 +2,18 @@
* Image content block
*/
define([
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore',
'mailpoet'
], function(App, BaseBlock, _, MailPoet) {
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore',
'mailpoet',
'jquery'
], function(App, BaseBlock, _, MailPoet, jQuery) {
'use strict';
var Module = {},
base = BaseBlock,
ImageWidgetView;
base = BaseBlock,
ImageWidgetView;
Module.ImageBlockModel = base.BlockModel.extend({
defaults: function() {
@ -35,7 +36,7 @@ define([
Module.ImageBlockView = base.BlockView.extend({
className: 'mailpoet_block mailpoet_image_block mailpoet_droppable_block',
getTemplate: function() { return templates.imageBlock; },
getTemplate: function() { return window.templates.imageBlock; },
onDragSubstituteBy: function() { return Module.ImageWidgetView; },
templateContext: function() {
return _.extend({
@ -72,7 +73,7 @@ define([
tooltip: MailPoet.I18n.t('helpTooltipDesignerIdealWidth')
});
},
getTemplate: function() { return templates.imageBlockSettings; },
getTemplate: function() { return window.templates.imageBlockSettings; },
events: function() {
return {
'input .mailpoet_field_image_link': _.partial(this.changeField, 'link'),
@ -98,10 +99,10 @@ define([
return;
}
var MediaManager = wp.media.view.MediaFrame.Select.extend({
var MediaManager = window.wp.media.view.MediaFrame.Select.extend({
initialize: function() {
wp.media.view.MediaFrame.prototype.initialize.apply(this, arguments);
window.wp.media.view.MediaFrame.prototype.initialize.apply(this, arguments);
_.defaults(this.options, {
multiple: true,
@ -123,7 +124,7 @@ define([
},
createQuery: function(options) {
var query = wp.media.query(options);
var query = window.wp.media.query(options);
return query;
},
@ -133,7 +134,7 @@ define([
// Add the default states.
this.states.add([
// Main states.
new wp.media.controller.Library({
new window.wp.media.controller.Library({
id: 'insert',
title: 'Add images',
priority: 20,
@ -155,8 +156,8 @@ define([
})
]);
if(wp.media.view.settings.post.featuredImageId) {
this.states.add(new wp.media.controller.FeaturedImage());
if(window.wp.media.view.settings.post.featuredImageId) {
this.states.add(new window.wp.media.controller.FeaturedImage());
}
},
@ -176,14 +177,14 @@ define([
this.on('updateExcluded', this.browseContent, this);
var handlers = {
content: {
embed: 'embedContent',
'edit-selection': 'editSelectionContent'
},
toolbar: {
'main-insert': 'mainInsertToolbar'
}
};
content: {
embed: 'embedContent',
'edit-selection': 'editSelectionContent'
},
toolbar: {
'main-insert': 'mainInsertToolbar'
}
};
_.each(handlers, function(regionHandlers, region) {
_.each(regionHandlers, function(callback, handler) {
@ -193,13 +194,13 @@ define([
},
uploadContent: function() {
wp.media.view.MediaFrame.Select.prototype.uploadContent.apply(this, arguments);
window.wp.media.view.MediaFrame.Select.prototype.uploadContent.apply(this, arguments);
this.$el.addClass('hide-toolbar');
},
// Content
embedContent: function() {
var view = new wp.media.view.Embed({
var view = new window.wp.media.view.Embed({
controller: this,
model: this.state()
}).render();
@ -213,7 +214,7 @@ define([
selection = state.get('selection'),
view;
view = new wp.media.view.AttachmentsBrowser({
view = new window.wp.media.view.AttachmentsBrowser({
controller: this,
collection: selection,
selection: selection,
@ -222,7 +223,7 @@ define([
search: false,
dragInfo: true,
AttachmentView: wp.media.view.Attachment.EditSelection
AttachmentView: window.wp.media.view.Attachment.EditSelection
}).render();
view.toolbar.set('backToLibrary', {
@ -242,7 +243,7 @@ define([
selectionStatusToolbar: function(view) {
var editable = this.state().get('editable');
view.set('selection', new wp.media.view.Selection({
view.set('selection', new window.wp.media.view.Selection({
controller: this,
collection: this.state().get('selection'),
priority: -40,
@ -278,7 +279,7 @@ define([
mainEmbedToolbar: function(toolbar) {
var tbar = toolbar;
tbar.view = new wp.media.view.Toolbar.Embed({
tbar.view = new window.wp.media.view.Toolbar.Embed({
controller: this,
text: 'Add images'
});
@ -301,9 +302,9 @@ define([
}
}),
that = this;
this._mediaManager = theFrame;
this._mediaManager = theFrame;
this._mediaManager.on('insert', function() {
this._mediaManager.on('insert', function() {
// Append media manager image selections to Images tab
var selection = theFrame.state().get('selection');
selection.each(function(attachment) {
@ -363,7 +364,7 @@ define([
});
ImageWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.imageInsertion; },
getTemplate: function() { return window.templates.imageInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -11,36 +11,36 @@
* block settings view.
*/
define([
'backbone',
'backbone.marionette',
'backbone.radio',
'underscore',
'jquery',
'mailpoet',
'newsletter_editor/App',
'newsletter_editor/components/communication',
'newsletter_editor/blocks/base',
'newsletter_editor/blocks/button',
'newsletter_editor/blocks/divider',
'select2'
], function(
Backbone,
Marionette,
Radio,
_,
jQuery,
MailPoet,
App,
CommunicationComponent,
BaseBlock,
ButtonBlock,
DividerBlock
'backbone',
'backbone.marionette',
'backbone.radio',
'underscore',
'jquery',
'mailpoet',
'newsletter_editor/App',
'newsletter_editor/components/communication',
'newsletter_editor/blocks/base',
'newsletter_editor/blocks/button',
'newsletter_editor/blocks/divider',
'select2'
], function(
Backbone,
Marionette,
Radio,
_,
jQuery,
MailPoet,
App,
CommunicationComponent,
BaseBlock,
ButtonBlock,
DividerBlock
) {
'use strict';
var Module = {},
base = BaseBlock;
base = BaseBlock;
Module.PostsBlockModel = base.BlockModel.extend({
stale: ['_selectedPosts', '_availablePosts', '_transformedPosts'],
@ -177,7 +177,7 @@ define([
Module.PostsBlockView = base.BlockView.extend({
className: 'mailpoet_block mailpoet_posts_block mailpoet_droppable_block',
getTemplate: function() { return templates.postsBlock; },
getTemplate: function() { return window.templates.postsBlock; },
modelEvents: {}, // Forcefully disable all events
regions: _.extend({
postsRegion: '.mailpoet_posts_block_posts'
@ -216,7 +216,7 @@ define([
});
Module.PostsBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.postsBlockSettings; },
getTemplate: function() { return window.templates.postsBlockSettings; },
regions: {
selectionRegion: '.mailpoet_settings_posts_selection',
displayOptionsRegion: '.mailpoet_settings_posts_display_options'
@ -308,7 +308,7 @@ define([
});
var PostSelectionSettingsView = Marionette.View.extend({
getTemplate: function() { return templates.postSelectionPostsBlockSettings; },
getTemplate: function() { return window.templates.postSelectionPostsBlockSettings; },
regions: {
posts: '.mailpoet_post_selection_container'
},
@ -414,7 +414,7 @@ define([
},
_updateContentTypes: function(postTypes) {
var select = this.$('.mailpoet_settings_posts_content_type'),
selectedValue = this.model.get('contentType');
selectedValue = this.model.get('contentType');
select.find('option').remove();
_.each(postTypes, function(type) {
@ -428,11 +428,11 @@ define([
});
var EmptyPostSelectionSettingsView = Marionette.View.extend({
getTemplate: function() { return templates.emptyPostPostsBlockSettings; }
getTemplate: function() { return window.templates.emptyPostPostsBlockSettings; }
});
var SinglePostSelectionSettingsView = Marionette.View.extend({
getTemplate: function() { return templates.singlePostPostsBlockSettings; },
getTemplate: function() { return window.templates.singlePostPostsBlockSettings; },
events: function() {
return {
'change .mailpoet_select_post_checkbox': 'postSelectionChange'
@ -459,7 +459,7 @@ define([
});
var PostsDisplayOptionsSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.displayOptionsPostsBlockSettings; },
getTemplate: function() { return window.templates.displayOptionsPostsBlockSettings; },
events: function() {
return {
'click .mailpoet_posts_select_button': 'showButtonSettings',
@ -564,7 +564,7 @@ define([
});
Module.PostsWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.postsInsertion; },
getTemplate: function() { return window.templates.postsInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -2,23 +2,23 @@
* Social icons content block
*/
define([
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'backbone',
'backbone.marionette',
'backbone.supermodel',
'underscore',
'jquery'
], function(App, BaseBlock, Backbone, Marionette, SuperModel, _, jQuery) {
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'backbone',
'backbone.marionette',
'backbone.supermodel',
'underscore',
'jquery'
], function(App, BaseBlock, Backbone, Marionette, SuperModel, _, jQuery) {
'use strict';
var Module = {},
base = BaseBlock,
SocialBlockSettingsIconSelectorView,
SocialBlockSettingsIconView,
SocialBlockSettingsIconCollectionView,
SocialBlockSettingsStylesView;
base = BaseBlock,
SocialBlockSettingsIconSelectorView,
SocialBlockSettingsIconView,
SocialBlockSettingsIconCollectionView,
SocialBlockSettingsStylesView;
Module.SocialIconModel = SuperModel.extend({
defaults: function() {
@ -85,7 +85,7 @@ define([
var SocialIconView = Marionette.View.extend({
tagName: 'span',
getTemplate: function() { return templates.socialIconBlock; },
getTemplate: function() { return window.templates.socialIconBlock; },
modelEvents: {
change: 'render'
},
@ -105,7 +105,7 @@ define([
Module.SocialBlockView = base.BlockView.extend({
className: 'mailpoet_block mailpoet_social_block mailpoet_droppable_block',
getTemplate: function() { return templates.socialBlock; },
getTemplate: function() { return window.templates.socialBlock; },
regions: _.extend({}, base.BlockView.prototype.regions, {
icons: '.mailpoet_social'
}),
@ -131,7 +131,7 @@ define([
// Sidebar view container
Module.SocialBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.socialBlockSettings; },
getTemplate: function() { return window.templates.socialBlockSettings; },
regions: {
iconRegion: '#mailpoet_social_icons_selection',
stylesRegion: '#mailpoet_social_icons_styles'
@ -155,7 +155,7 @@ define([
// Single icon settings view, used by the selector view
SocialBlockSettingsIconView = Marionette.View.extend({
getTemplate: function() { return templates.socialSettingsIcon; },
getTemplate: function() { return window.templates.socialSettingsIcon; },
events: function() {
return {
'click .mailpoet_delete_block': 'deleteIcon',
@ -212,7 +212,7 @@ define([
// Select icons section container view
SocialBlockSettingsIconSelectorView = Marionette.View.extend({
getTemplate: function() { return templates.socialSettingsIconSelector; },
getTemplate: function() { return window.templates.socialSettingsIconSelector; },
regions: {
icons: '#mailpoet_social_icon_selector_contents'
},
@ -235,7 +235,7 @@ define([
});
SocialBlockSettingsStylesView = Marionette.View.extend({
getTemplate: function() { return templates.socialSettingsStyles; },
getTemplate: function() { return window.templates.socialSettingsStyles; },
modelEvents: {
change: 'render'
},
@ -263,7 +263,7 @@ define([
});
Module.SocialWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.socialInsertion; },
getTemplate: function() { return window.templates.socialInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -2,15 +2,15 @@
* Spacer content block
*/
define([
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore'
], function(App, BaseBlock, _) {
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore'
], function(App, BaseBlock, _) {
'use strict';
var Module = {},
base = BaseBlock;
base = BaseBlock;
Module.SpacerBlockModel = base.BlockModel.extend({
defaults: function() {
@ -28,7 +28,7 @@ define([
Module.SpacerBlockView = base.BlockView.extend({
className: 'mailpoet_block mailpoet_spacer_block mailpoet_droppable_block',
getTemplate: function() { return templates.spacerBlock; },
getTemplate: function() { return window.templates.spacerBlock; },
behaviors: _.defaults({
ResizableBehavior: {
elementSelector: '.mailpoet_spacer',
@ -66,7 +66,7 @@ define([
});
Module.SpacerBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.spacerBlockSettings; },
getTemplate: function() { return window.templates.spacerBlockSettings; },
events: function() {
return {
'change .mailpoet_field_spacer_background_color': _.partial(this.changeColorField, 'styles.block.backgroundColor'),
@ -76,7 +76,7 @@ define([
});
Module.SpacerWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.spacerInsertion; },
getTemplate: function() { return window.templates.spacerInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -2,15 +2,16 @@
* Text content block
*/
define([
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore'
], function(App, BaseBlock, _) {
'newsletter_editor/App',
'newsletter_editor/blocks/base',
'underscore',
'mailpoet'
], function(App, BaseBlock, _, MailPoet) {
'use strict';
var Module = {},
base = BaseBlock;
base = BaseBlock;
Module.TextBlockModel = base.BlockModel.extend({
defaults: function() {
@ -23,7 +24,7 @@ define([
Module.TextBlockView = base.BlockView.extend({
className: 'mailpoet_block mailpoet_text_block mailpoet_droppable_block',
getTemplate: function() { return templates.textBlock; },
getTemplate: function() { return window.templates.textBlock; },
modelEvents: _.omit(base.BlockView.prototype.modelEvents, 'change'), // Prevent rerendering on model change due to text editor redrawing
behaviors: _.extend({}, base.BlockView.prototype.behaviors, {
TextEditorBehavior: {
@ -78,11 +79,11 @@ define([
});
Module.TextBlockSettingsView = base.BlockSettingsView.extend({
getTemplate: function() { return templates.textBlockSettings; }
getTemplate: function() { return window.templates.textBlockSettings; }
});
Module.TextWidgetView = base.WidgetView.extend({
getTemplate: function() { return templates.textInsertion; },
getTemplate: function() { return window.templates.textInsertion; },
behaviors: {
DraggableBehavior: {
cloneOriginal: true,

View File

@ -1,9 +1,9 @@
define([
'newsletter_editor/App',
'underscore',
'mailpoet',
'ajax'
], function(App, _, MailPoet) {
'newsletter_editor/App',
'underscore',
'mailpoet',
'ajax'
], function(App, _, MailPoet) {
var Module = {};

View File

@ -1,7 +1,7 @@
define([
'newsletter_editor/App',
'backbone.supermodel'
], function(App, SuperModel) {
'newsletter_editor/App',
'backbone.supermodel'
], function(App, SuperModel) {
var Module = {};

View File

@ -1,9 +1,9 @@
define([
'newsletter_editor/App',
'backbone.supermodel',
'underscore',
'mailpoet'
], function(App, SuperModel, _, MailPoet) {
'newsletter_editor/App',
'backbone.supermodel',
'underscore',
'mailpoet'
], function(App, SuperModel, _, MailPoet) {
'use strict';
var Module = {};
@ -15,7 +15,7 @@ define([
whitelisted: ['id', 'subject', 'preheader'],
initialize: function(options) {
this.on('change', function() {
App.getChannel().trigger('autoSave');
App.getChannel().trigger('autoSave');
});
},
toJSON: function() {
@ -59,7 +59,7 @@ define([
};
Module.getNewsletter = function() {
return Module.newsletter;
return Module.newsletter;
};
Module.findModels = function(predicate) {

View File

@ -1,17 +1,18 @@
define([
'newsletter_editor/App',
'backbone',
'backbone.marionette',
'underscore',
'jquery'
], function(App, Backbone, Marionette, _, jQuery) {
'newsletter_editor/App',
'backbone',
'backbone.marionette',
'underscore',
'jquery',
'mailpoet'
], function(App, Backbone, Marionette, _, jQuery, MailPoet) {
'use strict';
var Module = {};
Module.HeadingView = Marionette.View.extend({
getTemplate: function() { return templates.heading; },
getTemplate: function() { return window.templates.heading; },
templateContext: function() {
return {
model: this.model.toJSON()

View File

@ -1,31 +1,35 @@
define([
'newsletter_editor/App',
'newsletter_editor/components/communication',
'mailpoet',
'notice',
'backbone',
'backbone.marionette',
'jquery',
'blob',
'file-saver',
'html2canvas'
], function(
App,
CommunicationComponent,
MailPoet,
Notice,
Backbone,
Marionette,
jQuery,
Blob,
FileSaver,
html2canvas
) {
'newsletter_editor/App',
'newsletter_editor/components/communication',
'mailpoet',
'notice',
'backbone',
'backbone.marionette',
'jquery',
'blob',
'file-saver',
'html2canvas',
'underscore',
'jquery'
], function(
App,
CommunicationComponent,
MailPoet,
Notice,
Backbone,
Marionette,
jQuery,
Blob,
FileSaver,
html2canvas,
_,
$
) {
'use strict';
var Module = {},
saveTimeout;
saveTimeout;
// Save editor contents to server
Module.save = function() {
@ -73,9 +77,9 @@ define([
// Removes 1px left transparent border from resulting canvas.
var oldContext = oldCanvas.getContext('2d'),
newCanvas = document.createElement('canvas'),
newContext = newCanvas.getContext('2d'),
leftBorderWidth = 1;
newCanvas = document.createElement('canvas'),
newContext = newCanvas.getContext('2d'),
leftBorderWidth = 1;
newCanvas.width = oldCanvas.width;
newCanvas.height = oldCanvas.height;
@ -92,7 +96,7 @@ define([
Module.saveTemplate = function(options) {
var that = this,
promise = jQuery.Deferred();
promise = jQuery.Deferred();
promise.then(function(thumbnail) {
var data = _.extend(options || {}, {
@ -139,7 +143,7 @@ define([
};
Module.SaveView = Marionette.View.extend({
getTemplate: function() { return templates.save; },
getTemplate: function() { return window.templates.save; },
events: {
'click .mailpoet_save_button': 'save',
'click .mailpoet_save_show_options': 'toggleSaveOptions',
@ -189,8 +193,8 @@ define([
},
saveAsTemplate: function() {
var templateName = this.$('.mailpoet_save_as_template_name').val(),
templateDescription = this.$('.mailpoet_save_as_template_description').val(),
that = this;
templateDescription = this.$('.mailpoet_save_as_template_description').val(),
that = this;
if (templateName === '') {
MailPoet.Notice.error(
@ -245,8 +249,8 @@ define([
},
exportTemplate: function() {
var templateName = this.$('.mailpoet_export_template_name').val(),
templateDescription = this.$('.mailpoet_export_template_description').val(),
that = this;
templateDescription = this.$('.mailpoet_export_template_description').val(),
that = this;
if (templateName === '') {
MailPoet.Notice.error(

View File

@ -1,23 +1,23 @@
define([
'newsletter_editor/App',
'newsletter_editor/components/communication',
'mailpoet',
'backbone',
'backbone.marionette',
'backbone.supermodel',
'underscore',
'jquery',
'sticky-kit'
], function(
App,
CommunicationComponent,
MailPoet,
Backbone,
Marionette,
SuperModel,
_,
jQuery,
StickyKit
'newsletter_editor/App',
'newsletter_editor/components/communication',
'mailpoet',
'backbone',
'backbone.marionette',
'backbone.supermodel',
'underscore',
'jquery',
'sticky-kit'
], function(
App,
CommunicationComponent,
MailPoet,
Backbone,
Marionette,
SuperModel,
_,
jQuery,
StickyKit
) {
'use strict';
@ -53,7 +53,7 @@ define([
Module.getLayoutWidgets = function() { return Module._layoutWidgets; };
var SidebarView = Marionette.View.extend({
getTemplate: function() { return templates.sidebar; },
getTemplate: function() { return window.templates.sidebar; },
regions: {
contentRegion: '.mailpoet_content_region',
layoutRegion: '.mailpoet_layout_region',
@ -147,7 +147,7 @@ define([
* Responsible for rendering draggable content widgets
*/
Module.SidebarWidgetsView = Marionette.View.extend({
getTemplate: function() { return templates.sidebarContent; },
getTemplate: function() { return window.templates.sidebarContent; },
regions: {
widgets: '.mailpoet_region_content'
},
@ -167,14 +167,14 @@ define([
* Responsible for rendering draggable layout widgets
*/
Module.SidebarLayoutWidgetsView = Module.SidebarWidgetsView.extend({
getTemplate: function() { return templates.sidebarLayout; }
getTemplate: function() { return window.templates.sidebarLayout; }
});
/**
* Responsible for managing global styles
*/
Module.SidebarStylesView = Marionette.View.extend({
getTemplate: function() { return templates.sidebarStyles; },
getTemplate: function() { return window.templates.sidebarStyles; },
behaviors: {
ColorPickerBehavior: {}
},
@ -238,7 +238,7 @@ define([
});
Module.SidebarPreviewView = Marionette.View.extend({
getTemplate: function() { return templates.sidebarPreview; },
getTemplate: function() { return window.templates.sidebarPreview; },
events: {
'click .mailpoet_show_preview': 'showPreview',
'click #mailpoet_send_preview': 'sendPreview'
@ -346,7 +346,7 @@ define([
});
Module.NewsletterPreviewView = Marionette.View.extend({
getTemplate: function() { return templates.newsletterPreview; },
getTemplate: function() { return window.templates.newsletterPreview; },
initialize: function(options) {
this.previewUrl = options.previewUrl;
this.width = '100%';

View File

@ -1,8 +1,9 @@
define([
'newsletter_editor/App',
'backbone.marionette',
'backbone.supermodel'
], function(App, Marionette, SuperModel) {
'newsletter_editor/App',
'backbone.marionette',
'backbone.supermodel',
'underscore'
], function(App, Marionette, SuperModel, _) {
'use strict';
@ -47,7 +48,7 @@ define([
});
Module.StylesView = Marionette.View.extend({
getTemplate: function() { return templates.styles; },
getTemplate: function() { return window.templates.styles; },
modelEvents: {
change: 'render'
},

View File

@ -1,27 +0,0 @@
/**
* A sample implementation of template widgets.
* A draggable widget, on drop creates a container with (image|text) block.
*/
ImageAndTextTemplateWidgetView = EditorApplication.module('blocks.base').WidgetView.extend({
getTemplate: function() { return templates.imageAndTextInsertion; },
className: 'mailpoet_droppable_block mailpoet_droppable_widget',
behaviors: {
DraggableBehavior: {
drop: function() {
return new (EditorApplication.getBlockTypeModel('container'))({
type: 'container',
orientation: 'horizontal',
blocks: [
{
type: 'image'
},
{
type: 'text',
text: 'Some random text'
}
]
}, {parse: true});
}
}
}
});

View File

@ -126,13 +126,13 @@ const _QueueMixin = {
return (
<div>
<div className={ progressClasses }>
<span
className="mailpoet_progress_bar"
style={ { width: progress_bar_width + '%' } }
<span
className="mailpoet_progress_bar"
style={ { width: progress_bar_width + '%' } }
></span>
<span className="mailpoet_progress_label">
{ percentage }
</span>
<span className="mailpoet_progress_label">
{ percentage }
</span>
</div>
<p style={{ textAlign:'center' }}>
{ label }
@ -346,8 +346,8 @@ const _MailerMixin = {
<p>{ mailer_check_settings_notice }</p>
<p>
<a href="javascript:;"
className="button"
onClick={ this.resumeMailerSending }
className="button"
onClick={ this.resumeMailerSending }
>{ MailPoet.I18n.t('mailerResumeSendingButton') }</a>
</p>
</div>

View File

@ -317,7 +317,7 @@ const NewsletterListNotification = React.createClass({
<ListingTabs tab="notification" />
<Listing
limit={ mailpoet_listing_per_page }
limit={ window.mailpoet_listing_per_page }
location={ this.props.location }
params={ this.props.params }
endpoint="newsletters"

View File

@ -110,7 +110,7 @@ const NewsletterListNotificationHistory = React.createClass({
>{MailPoet.I18n.t('backToPostNotifications')}</Link>
<Listing
limit={ mailpoet_listing_per_page }
limit={ window.mailpoet_listing_per_page }
location={ this.props.location }
params={ this.props.params }
endpoint="newsletters"

View File

@ -218,7 +218,7 @@ const NewsletterListStandard = React.createClass({
<ListingTabs tab="standard" />
<Listing
limit={ mailpoet_listing_per_page }
limit={ window.mailpoet_listing_per_page }
location={ this.props.location }
params={ this.props.params }
endpoint="newsletters"

View File

@ -295,7 +295,7 @@ const NewsletterListWelcome = React.createClass({
<ListingTabs tab="welcome" />
<Listing
limit={ mailpoet_listing_per_page }
limit={ window.mailpoet_listing_per_page }
location={ this.props.location }
params={ this.props.params }
endpoint="newsletters"

View File

@ -10,6 +10,7 @@ define(
'newsletters/send/welcome.jsx',
'newsletters/breadcrumb.jsx',
'help-tooltip.jsx',
'jquery',
],
(
React,
@ -21,7 +22,8 @@ define(
NotificationNewsletterFields,
WelcomeNewsletterFields,
Breadcrumb,
HelpTooltip
HelpTooltip,
jQuery
) => {
const NewsletterSend = React.createClass({
@ -283,6 +285,7 @@ define(
}
return newField;
});
const sendButtonOptions = this.getSendButtonOptions();
return (
<div>
<h1>{MailPoet.I18n.t('finalNewsletterStep')}</h1>
@ -300,18 +303,18 @@ define(
<p className="submit">
{
isPaused ?
<input
className="button button-primary"
type="button"
onClick={ this.handleResume }
value={MailPoet.I18n.t('resume')} />
<input
className="button button-primary"
type="button"
onClick={ this.handleResume }
value={MailPoet.I18n.t('resume')} />
:
<input
className="button button-primary"
type="button"
onClick={ this.handleSend }
value={MailPoet.I18n.t('send')}
{...this.getSendButtonOptions()}
<input
className="button button-primary"
type="button"
onClick={ this.handleSend }
value={MailPoet.I18n.t('send')}
{...sendButtonOptions}
/>
}
&nbsp;
@ -328,10 +331,12 @@ define(
{MailPoet.I18n.t('goBackToDesign')}
</a>.
</p>
<HelpTooltip
tooltip={MailPoet.I18n.t('helpTooltipSendEmail')}
tooltipId="helpTooltipSendEmail"
/>
{ !isPaused && sendButtonOptions['disabled'] && sendButtonOptions['disabled'] === 'disabled' && (
<HelpTooltip
tooltip={MailPoet.I18n.t('helpTooltipSendEmail')}
tooltipId="helpTooltipSendEmail"
/>
) }
</Form>
</div>
);

View File

@ -244,24 +244,24 @@ define(
</div>
<div className="mailpoet_description">
<h3>{ template.name }</h3>
<p>{ template.description }</p>
<h3>{ template.name }</h3>
<p>{ template.description }</p>
</div>
<div className="mailpoet_actions">
<a
className="button button-secondary"
onClick={ this.handleShowTemplate.bind(null, template) }
<a
className="button button-secondary"
onClick={ this.handleShowTemplate.bind(null, template) }
>
{MailPoet.I18n.t('preview')}
</a>
{MailPoet.I18n.t('preview')}
</a>
&nbsp;
<a
className="button button-primary"
onClick={ this.handleSelectTemplate.bind(null, template) }
<a
className="button button-primary"
onClick={ this.handleSelectTemplate.bind(null, template) }
>
{MailPoet.I18n.t('select')}
</a>
{MailPoet.I18n.t('select')}
</a>
</div>
{ (template.readonly === '1') ? false : deleteLink }
</li>

View File

@ -75,7 +75,7 @@ define('notice', ['mailpoet', 'jquery'], function(mp, jQuery) {
// setup onClose callback
var onClose = null;
if (this.options.onClose !== null) {
onClose = this.options.onClose;
onClose = this.options.onClose;
}
// listen to remove event
@ -83,7 +83,7 @@ define('notice', ['mailpoet', 'jquery'], function(mp, jQuery) {
jQuery(this).fadeOut(200, function() {
// on close callback
if (onClose !== null) {
onClose();
onClose();
}
// remove notice
jQuery(this).remove();
@ -144,13 +144,13 @@ define('notice', ['mailpoet', 'jquery'], function(mp, jQuery) {
switch (this.options.type) {
case 'success':
this.element.addClass('notice notice-success');
break;
break;
case 'system':
this.element.addClass('notice notice-warning');
break;
break;
case 'error':
this.element.addClass('notice notice-error');
break;
break;
}
// make the notice appear
@ -167,7 +167,7 @@ define('notice', ['mailpoet', 'jquery'], function(mp, jQuery) {
} else if (this.options.hideClose === false) {
this.element.append('<a href="javascript:;" class="mailpoet_notice_close"><span class="dashicons dashicons-dismiss"></span></a>');
this.element.find('.mailpoet_notice_close').on('click', function() {
jQuery(this).trigger('close');
jQuery(this).trigger('close');
});
}

View File

@ -4,19 +4,19 @@ define('num',
], function(
mp
) {
'use strict';
'use strict';
var MailPoet = mp;
MailPoet.Num = {
toLocaleFixed: function (num, precisionOpts) {
var precision = precisionOpts || 0;
var factor = Math.pow(10, precision);
return (Math.round(num * factor) / factor)
var MailPoet = mp;
MailPoet.Num = {
toLocaleFixed: function (num, precisionOpts) {
var precision = precisionOpts || 0;
var factor = Math.pow(10, precision);
return (Math.round(num * factor) / factor)
.toLocaleString(
undefined,
{minimumFractionDigits: precision, maximumFractionDigits: precision}
);
}
};
}
};
});
});

View File

@ -33,13 +33,13 @@ function(
form.parsley().on('form:submit', function(parsley) {
var form_data = form.serializeObject() || {};
// check if we're on the same domain
if(isSameDomain(MailPoetForm.ajax_url) === false) {
if(isSameDomain(window.MailPoetForm.ajax_url) === false) {
// non ajax post request
return true;
} else {
// ajax request
MailPoet.Ajax.post({
url: MailPoetForm.ajax_url,
url: window.MailPoetForm.ajax_url,
token: form_data.token,
api_version: form_data.api_version,
endpoint: 'subscribers',

View File

@ -258,7 +258,7 @@ const SegmentList = React.createClass({
</h1>
<Listing
limit={ mailpoet_listing_per_page }
limit={ window.mailpoet_listing_per_page }
location={ this.props.location }
params={ this.props.params }
messages={ messages }

View File

@ -1,44 +1,44 @@
define(
[
'underscore',
'jquery',
'mailpoet',
'handlebars',
'select2'
],
[
'underscore',
'jquery',
'mailpoet',
'handlebars',
'select2'
],
function (
_,
jQuery,
MailPoet,
Handlebars,
select2
_,
jQuery,
MailPoet,
Handlebars,
select2
) {
if (!jQuery('#mailpoet_subscribers_export').length) {
return;
}
jQuery(document).ready(function () {
if (!exportData.segments) {
if (!window.exportData.segments) {
return;
}
var subscribers_export_template =
Handlebars.compile(jQuery('#mailpoet_subscribers_export_template').html());
//render template
jQuery('#mailpoet_subscribers_export > div.inside').html(subscribers_export_template(exportData));
jQuery('#mailpoet_subscribers_export > div.inside').html(subscribers_export_template(window.exportData));
// define reusable variables
var segmentsContainerElement = jQuery('#export_lists'),
subscriberFieldsContainerElement = jQuery('#export_columns'),
exportConfirmedOptionElement = jQuery(':radio[name="option_confirmed"]'),
groupBySegmentOptionElement = jQuery(':checkbox[name="option_group_by_list"]'),
nextStepButton = jQuery('a.mailpoet_export_process'),
renderSegmentsAndFields = function (container, data) {
if (container.data('select2')) {
container
subscriberFieldsContainerElement = jQuery('#export_columns'),
exportConfirmedOptionElement = jQuery(':radio[name="option_confirmed"]'),
groupBySegmentOptionElement = jQuery(':checkbox[name="option_group_by_list"]'),
nextStepButton = jQuery('a.mailpoet_export_process'),
renderSegmentsAndFields = function (container, data) {
if (container.data('select2')) {
container
.html('')
.select2('destroy');
}
container
}
container
.select2({
data: data,
width: '20em',
@ -55,11 +55,11 @@ define(
})
.on('select2:selecting', function (selectEvent) {
var selectElement = this,
selectedOptionId = selectEvent.params.args.data.id,
fieldsToExclude = [
'select',
'deselect'
];
selectedOptionId = selectEvent.params.args.data.id,
fieldsToExclude = [
'select',
'deselect'
];
if (_.contains(fieldsToExclude, selectedOptionId)) {
selectEvent.preventDefault();
if (selectedOptionId === 'deselect') {
@ -77,9 +77,9 @@ define(
}
})
.on('change', function () {
if ((exportData.segments && segmentsContainerElement.select2('data').length && subscriberFieldsContainerElement.select2('data').length)
if ((window.exportData.segments && segmentsContainerElement.select2('data').length && subscriberFieldsContainerElement.select2('data').length)
||
(!exportData.segments && subscriberFieldsContainerElement.select2('data').length)
(!window.exportData.segments && subscriberFieldsContainerElement.select2('data').length)
) {
toggleNextStepButton('on');
}
@ -87,20 +87,20 @@ define(
toggleNextStepButton('off');
}
if (segmentsContainerElement.select2('data').length > 1 && exportData.groupBySegmentOption) {
if (segmentsContainerElement.select2('data').length > 1 && window.exportData.groupBySegmentOption) {
jQuery('.mailpoet_group_by_list').show();
}
else if (exportData.groupBySegmentOption) {
else if (window.exportData.groupBySegmentOption) {
jQuery('.mailpoet_group_by_list').hide();
}
});
};
};
// set confirmed subscribers export option to false
exportData.exportConfirmedOption = false;
window.exportData.exportConfirmedOption = false;
renderSegmentsAndFields(subscriberFieldsContainerElement, subscriberFieldsSelect2);
renderSegmentsAndFields(segmentsContainerElement, segments);
renderSegmentsAndFields(subscriberFieldsContainerElement, window.subscriberFieldsSelect2);
renderSegmentsAndFields(segmentsContainerElement, window.segments);
subscriberFieldsContainerElement.val([
'email',
@ -112,12 +112,12 @@ define(
exportConfirmedOptionElement.change(function () {
var selectedSegments = segmentsContainerElement.val();
if (this.value == 1) {
exportData.exportConfirmedOption = true;
renderSegmentsAndFields(segmentsContainerElement, segmentsWithConfirmedSubscribers);
window.exportData.exportConfirmedOption = true;
renderSegmentsAndFields(segmentsContainerElement, window.segmentsWithConfirmedSubscribers);
}
else {
exportData.exportConfirmedOption = false;
renderSegmentsAndFields(segmentsContainerElement, segments);
window.exportData.exportConfirmedOption = false;
renderSegmentsAndFields(segmentsContainerElement, window.segments);
}
segmentsContainerElement.val(selectedSegments).trigger('change');
});
@ -139,39 +139,39 @@ define(
MailPoet.Modal.loading(true);
var exportFormat = jQuery(':radio[name="option_format"]:checked').val();
MailPoet.Ajax.post({
api_version: window.mailpoet_api_version,
endpoint: 'ImportExport',
action: 'processExport',
data: JSON.stringify({
export_confirmed_option: exportData.exportConfirmedOption,
export_format_option: exportFormat,
group_by_segment_option: (groupBySegmentOptionElement.is(':visible')) ? groupBySegmentOptionElement.prop('checked') : false,
segments: (exportData.segments) ? segmentsContainerElement.val() : false,
subscriber_fields: subscriberFieldsContainerElement.val()
})
}).always(function(response) {
MailPoet.Modal.loading(false);
}).done(function(response) {
resultMessage = MailPoet.I18n.t('exportMessage')
.replace('%1$s', '<strong>' + parseInt(response.data.totalExported).toLocaleString() + '</strong>')
.replace('[link]', '<a href="' + response.data.exportFileURL + '" target="_blank" >')
.replace('[/link]', '</a>');
jQuery('#export_result_notice').html('<p>' + resultMessage + '</p>').show();
window.location.href = response.data.exportFileURL;
MailPoet.trackEvent('Subscribers export completed', {
'Total exported': response.data.totalExported,
'Only confirmed?': exportData.exportConfirmedOption,
'File Format': exportFormat,
'MailPoet Free version': window.mailpoet_version
});
}).fail(function(response) {
if (response.errors.length > 0) {
MailPoet.Notice.error(
api_version: window.mailpoet_api_version,
endpoint: 'ImportExport',
action: 'processExport',
data: JSON.stringify({
export_confirmed_option: window.exportData.exportConfirmedOption,
export_format_option: exportFormat,
group_by_segment_option: (groupBySegmentOptionElement.is(':visible')) ? groupBySegmentOptionElement.prop('checked') : false,
segments: (window.exportData.segments) ? segmentsContainerElement.val() : false,
subscriber_fields: subscriberFieldsContainerElement.val()
})
}).always(function(response) {
MailPoet.Modal.loading(false);
}).done(function(response) {
var resultMessage = MailPoet.I18n.t('exportMessage')
.replace('%1$s', '<strong>' + parseInt(response.data.totalExported).toLocaleString() + '</strong>')
.replace('[link]', '<a href="' + response.data.exportFileURL + '" target="_blank" >')
.replace('[/link]', '</a>');
jQuery('#export_result_notice').html('<p>' + resultMessage + '</p>').show();
window.location.href = response.data.exportFileURL;
MailPoet.trackEvent('Subscribers export completed', {
'Total exported': response.data.totalExported,
'Only confirmed?': window.exportData.exportConfirmedOption,
'File Format': exportFormat,
'MailPoet Free version': window.mailpoet_version
});
}).fail(function(response) {
if (response.errors.length > 0) {
MailPoet.Notice.error(
response.errors.map(function(error) { return error.message; }),
{ scroll: true }
);
}
});
}
});
});
});
});

View File

@ -1,15 +1,15 @@
define(
[
'backbone',
'underscore',
'jquery',
'mailpoet',
'handlebars',
'papaparse',
'asyncqueue',
'moment',
'select2'
],
[
'backbone',
'underscore',
'jquery',
'mailpoet',
'handlebars',
'papaparse',
'asyncqueue',
'moment',
'select2'
],
function (
Backbone,
_,
@ -27,7 +27,7 @@ define(
jQuery(document).ready(function () {
jQuery('input[name="select_method"]').attr('checked', false);
// configure router
router = new (Backbone.Router.extend({
var router = new (Backbone.Router.extend({
routes: {
'': 'home',
step1: 'step1',
@ -51,13 +51,13 @@ define(
*/
router.on('route:step1', function () {
// set or reset temporary validation rule on all columns
mailpoetColumns = jQuery.map(mailpoetColumns, function (column, columnIndex) {
window.mailpoetColumns = jQuery.map(window.mailpoetColumns, function (column, columnIndex) {
var col = column;
col.validation_rule = false;
return col;
});
if (typeof (importData.step1) !== 'undefined') {
if (typeof (window.importData.step1) !== 'undefined') {
showCurrentStep();
return;
}
@ -69,21 +69,21 @@ define(
// define reusable variables
var currentStepE = jQuery(location.hash),
methodSelectionElement = jQuery('#select_method'),
pasteInputElement = jQuery('#paste_input'),
pasteInputPlaceholderElement =
methodSelectionElement = jQuery('#select_method'),
pasteInputElement = jQuery('#paste_input'),
pasteInputPlaceholderElement =
pasteInputElement.data('placeholder').replace(/\\n/g, '\n'),
pasteProcessButtonElement =
pasteProcessButtonElement =
jQuery('#method_paste > div.mailpoet_method_process')
.find('a.mailpoet_process'),
mailChimpKeyInputElement = jQuery('#mailchimp_key'),
mailChimpKeyVerifyButtonElement = jQuery('#mailchimp_key_verify'),
mailChimpListsContainerElement = jQuery('#mailchimp_lists'),
mailChimpProcessButtonElement =
mailChimpKeyInputElement = jQuery('#mailchimp_key'),
mailChimpKeyVerifyButtonElement = jQuery('#mailchimp_key_verify'),
mailChimpListsContainerElement = jQuery('#mailchimp_lists'),
mailChimpProcessButtonElement =
jQuery('#method_mailchimp > div.mailpoet_method_process')
.find('a.mailpoet_process'),
uploadElement = jQuery('#file_local'),
uploadProcessButtonElement =
uploadElement = jQuery('#file_local'),
uploadProcessButtonElement =
jQuery('#method_file > div.mailpoet_method_process')
.find('a.mailpoet_process');
@ -91,7 +91,7 @@ define(
methodSelectionElement.change(function () {
MailPoet.Notice.hide();
var available_methods = jQuery(':radio[name="select_method"]'),
selected_method =
selected_method =
available_methods.index(available_methods.filter(':checked'));
// hide all methods
currentStepE.find('.inside')
@ -134,7 +134,7 @@ define(
MailPoet.Notice.hide();
// get an approximate size of textarea paste in bytes
var pasteSize = encodeURI(pasteInputElement.val()).split(/%..|./).length - 1;
if (pasteSize > maxPostSizeBytes) {
if (pasteSize > window.maxPostSizeBytes) {
MailPoet.Notice.error(MailPoet.I18n.t('maxPostSizeNotice'));
return;
}
@ -150,11 +150,11 @@ define(
*/
uploadElement.change(function () {
MailPoet.Notice.hide();
var ext = this.value.match(/\.(.+)$/);
if (ext === null || ext[1].toLowerCase() !== 'csv') {
this.value = '';
MailPoet.Notice.error(MailPoet.I18n.t('wrongFileFormat'));
}
var ext = this.value.match(/\.(.+)$/);
if (ext === null || ext[1].toLowerCase() !== 'csv') {
this.value = '';
MailPoet.Notice.error(MailPoet.I18n.t('wrongFileFormat'));
}
toggleNextStepButton(
uploadProcessButtonElement,
@ -237,7 +237,7 @@ define(
}).always(function(response) {
MailPoet.Modal.loading(false);
}).done(function(response) {
importData.step1 = response.data;
window.importData.step1 = response.data;
MailPoet.trackEvent('Subscribers import started', {
source: 'MailChimp',
'MailPoet Free version': window.mailpoet_version
@ -295,23 +295,23 @@ define(
function parseCSV(isFile) {
var processedSubscribers = [],
parsedEmails = [],
duplicateEmails = [],
invalidEmails = [],
emailColumnPosition = null,
columnCount = null,
isHeaderFound = false,
advancedOptionHeader = true,
advancedOptionDelimiter = '',
advancedOptionNewline = '',
advancedOptionComments = false,
parsedEmails = [],
duplicateEmails = [],
invalidEmails = [],
emailColumnPosition = null,
columnCount = null,
isHeaderFound = false,
advancedOptionHeader = true,
advancedOptionDelimiter = '',
advancedOptionNewline = '',
advancedOptionComments = false,
// trim spaces, commas, periods,
// single/double quotes and convert to lowercase
detectAndCleanupEmail = function (emailString) {
var test;
detectAndCleanupEmail = function (emailString) {
var test;
// decode HTML entities
var email = jQuery('<div />').html(emailString).text();
email = email
var email = jQuery('<div />').html(emailString).text();
email = email
.toLowerCase()
// left/right trim spaces, punctuation (e.g., " 'email@email.com'; ")
// right trim non-printable characters (e.g., "email@email.com<6F>")
@ -320,22 +320,22 @@ define(
// remove urlencoded characters
.replace(/\s+|%\d+|,+/g, '');
// detect e-mails that will be otherwise rejected by email regex
test = /<(.*?)>/.exec(email);
if (test) {
test = /<(.*?)>/.exec(email);
if (test) {
// is the email inside angle brackets (e.g., 'some@email.com <some@email.com>')?
email = test[1].trim();
}
test = /mailto:(?:\s+)?(.*)/.exec(email);
if (test) {
email = test[1].trim();
}
test = /mailto:(?:\s+)?(.*)/.exec(email);
if (test) {
// is the email in 'mailto:email' format?
email = test[1].trim();
}
email = test[1].trim();
}
// test for valid characters using WP's rule (https://core.trac.wordpress.org/browser/tags/4.7.3/src/wp-includes/formatting.php#L2902)
if (!/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.\-@]+$/.test(email) ) {
return false;
}
return email;
};
if (!/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.\-@]+$/.test(email) ) {
return false;
}
return email;
};
return {
skipEmptyLines: true,
@ -368,7 +368,7 @@ define(
for (var column in rowData) {
var email = detectAndCleanupEmail(rowData[column]);
if (emailColumnPosition === null
&& emailRegex.test(email)) {
&& window.emailRegex.test(email)) {
emailColumnPosition = column;
parsedEmails[email] = true; // add current e-mail to an object index
rowData[column] = email;
@ -387,7 +387,7 @@ define(
if (_.has(parsedEmails, email)) {
duplicateEmails.push(email);
}
else if (!emailRegex.test(email)) {
else if (!window.emailRegex.test(email)) {
invalidEmails.push(rowData[emailColumnPosition]);
}
// if we haven't yet processed this e-mail and it passed
@ -410,8 +410,8 @@ define(
) {
// since we assume that the header line is always present, we need
// to detect the header by checking if it contains a valid e-mail address
importData.step1 = {
header: (!emailRegex.test(
window.importData.step1 = {
header: (!window.emailRegex.test(
processedSubscribers[0][emailColumnPosition])
) ? processedSubscribers.shift() : null,
subscribers: processedSubscribers,
@ -438,37 +438,37 @@ define(
});
router.on('route:step2', function () {
if (typeof (importData.step1) === 'undefined') {
if (typeof (window.importData.step1) === 'undefined') {
router.navigate('step1', {trigger: true});
return;
}
// define reusable variables
var nextStepButton = jQuery('#step2_process'),
previousStepButton = jQuery('#return_to_step1'),
previousStepButton = jQuery('#return_to_step1'),
// create a copy of subscribers object for further manipulation
subscribers = jQuery.extend(true, {}, importData.step1),
subscribersDataTemplate =
subscribers = jQuery.extend(true, {}, window.importData.step1),
subscribersDataTemplate =
Handlebars
.compile(jQuery('#subscribers_data_template')
.html()),
subscribersDataTemplatePartial =
subscribersDataTemplatePartial =
Handlebars
.compile(jQuery('#subscribers_data_template_partial')
.html()),
subscribersDataParseResultsTemplate =
subscribersDataParseResultsTemplate =
Handlebars
.compile(jQuery('#subscribers_data_parse_results_template')
.html()),
segmentSelectElement = jQuery('#mailpoet_segments_select'),
maxRowsToShow = 10,
filler = '. . .',
segmentSelectElement = jQuery('#mailpoet_segments_select'),
maxRowsToShow = 10,
filler = '. . .',
// create an array of filler data with the same number of
// elements as in the subscribers' data row
fillerArray = Array.apply(
fillerArray = Array.apply(
null,
new Array(subscribers.subscribers[0].length)
).map(String.prototype.valueOf, filler),
fillerPosition;
fillerPosition;
showCurrentStep();
@ -526,7 +526,7 @@ define(
});
// show available segments
if (mailpoetSegments.length) {
if (window.mailpoetSegments.length) {
jQuery('.mailpoet_segments').show();
}
else {
@ -599,7 +599,7 @@ define(
description: segmentDescription
}
}).done(function(response) {
mailpoetSegments.push({
window.mailpoetSegments.push({
id: response.data.id,
name: response.data.name,
subscriberCount: 0
@ -612,7 +612,7 @@ define(
selected_values.push(response.data.id);
}
enableSegmentSelection(mailpoetSegments);
enableSegmentSelection(window.mailpoetSegments);
segmentSelectElement.val(selected_values).trigger('change');
jQuery('.mailpoet_segments:hidden').show();
jQuery('.mailpoet_no_segments:visible').hide();
@ -643,22 +643,22 @@ define(
'show_and_match_columns',
function (subscribers, options) {
var displayedColumns = [],
displayedColumnsIds = [];
displayedColumnsIds = [];
// go through all elements of the first row in subscribers data
for (var i in subscribers.subscribers[0]) {
var columnData = subscribers.subscribers[0][i],
columnId = 'ignore'; // set default column type
columnId = 'ignore'; // set default column type
// if the column is not undefined and has a valid e-mail, set type as email
if (columnData % 1 !== 0 && emailRegex.test(columnData)) {
if (columnData % 1 !== 0 && window.emailRegex.test(columnData)) {
columnId = 'email';
} else if (subscribers.header) {
var headerName = subscribers.header[i],
headerNameMatch = mailpoetColumns.map(function (el) {
return el.name;
}).indexOf(headerName);
headerNameMatch = window.mailpoetColumns.map(function (el) {
return el.name;
}).indexOf(headerName);
// set column type using header
if (headerNameMatch !== -1) {
columnId = mailpoetColumns[headerNameMatch].id;
columnId = window.mailpoetColumns[headerNameMatch].id;
}// set column type using header name
else if (headerName) {
if (/first|first name|given name/i.test(headerName)) {
@ -723,7 +723,7 @@ define(
// filter displayed data
jQuery('select.mailpoet_subscribers_column_data_match')
.select2({
data: mailpoetColumnsSelect2,
data: window.mailpoetColumnsSelect2,
width: '15em',
templateResult: function (item) {
return item.name;
@ -734,7 +734,7 @@ define(
})
.on('select2:selecting', function (selectEvent) {
var selectElement = this,
selectedOptionId = selectEvent.params.args.data.id;
selectedOptionId = selectEvent.params.args.data.id;
// CREATE CUSTOM FIELD
if (selectedOptionId === 'create') {
selectEvent.preventDefault();
@ -762,21 +762,21 @@ define(
custom: true
};
// if this is the first custom column, create an "optgroup"
if (mailpoetColumnsSelect2.length === 2) {
mailpoetColumnsSelect2.push({
if (window.mailpoetColumnsSelect2.length === 2) {
window.mailpoetColumnsSelect2.push({
name: MailPoet.I18n.t('userColumns'),
children: []
});
}
mailpoetColumnsSelect2[2].children.push(new_column_data);
mailpoetColumns.push(new_column_data);
window.mailpoetColumnsSelect2[2].children.push(new_column_data);
window.mailpoetColumns.push(new_column_data);
jQuery('select.mailpoet_subscribers_column_data_match')
.each(function () {
jQuery(this)
.html('')
.select2('destroy')
.select2({
data: mailpoetColumnsSelect2,
data: window.mailpoetColumnsSelect2,
width: '15em',
templateResult: function (item) {
return item.name;
@ -808,7 +808,7 @@ define(
jQuery('select.mailpoet_subscribers_column_data_match')
.each(function () {
var element = this,
elementId = jQuery(element).val();
elementId = jQuery(element).val();
// if another column has the same value and it's not an 'ignore', prompt user
if (elementId === selectedOptionId
&& elementId !== 'ignore') {
@ -825,7 +825,7 @@ define(
})
.on('select2:select', function (selectEvent) {
var selectElement = this,
selectedOptionId = selectEvent.params.data.id;
selectedOptionId = selectEvent.params.data.id;
jQuery(selectElement).data('column-id', selectedOptionId);
filterSubscribers();
});
@ -836,8 +836,8 @@ define(
'[data-id="notice_invalidEmail"], [data-id="notice_invalidDate"]')
.remove();
var subscribersClone = jQuery.extend(true, {}, subscribers),
preventNextStep = false,
displayedColumns = jQuery.map(
preventNextStep = false,
displayedColumns = jQuery.map(
jQuery('.mailpoet_subscribers_column_data_match'), function (element, elementIndex) {
var columnId = jQuery(element).data('column-id');
var validationRule = jQuery(element).data('validation-rule');
@ -845,14 +845,14 @@ define(
return { id: columnId, index: elementIndex, validationRule: validationRule, element: element };
});
// iterate through the object of mailpoet columns
jQuery.map(mailpoetColumns, function (column, columnIndex) {
jQuery.map(window.mailpoetColumns, function (column, columnIndex) {
// check if the column id matches the selected id of one of the
// subscriber's data columns
var matchedColumn = _.find(displayedColumns, function(data) { return data.id === column.id; });
// EMAIL filter: if the first value in the column doesn't have a valid
// email, hide the next button
if (column.id === 'email') {
if (!emailRegex.test(subscribersClone.subscribers[0][matchedColumn.index])) {
if (!window.emailRegex.test(subscribersClone.subscribers[0][matchedColumn.index])) {
preventNextStep = true;
if (!jQuery('[data-id="notice_invalidEmail"]').length) {
MailPoet.Notice.error(MailPoet.I18n.t('columnContainsInvalidElement'), {
@ -996,7 +996,7 @@ define(
return res;
}, []);
},
subscribers = splitSubscribers(importData.step1.subscribers, batchSize);
subscribers = splitSubscribers(window.importData.step1.subscribers, batchSize);
_.each(jQuery('select.mailpoet_subscribers_column_data_match'),
function (column, columnIndex) {
@ -1020,7 +1020,7 @@ define(
subscribers: subscribers[batchNumber],
timestamp: timestamp,
segments: segmentSelectElement.val(),
updateSubscribers: (jQuery(':radio[name="subscriber_update_option"]:checked').val() === 'yes') ? true : false
updateSubscribers: (jQuery(':radio[name="subscriber_update_option"]:checked').val() === 'yes')
})
}).done(function(response) {
importResults.created += response.data.created;
@ -1050,37 +1050,37 @@ define(
);
}
else {
mailpoetSegments = importResults.segments;
window.mailpoetSegments = importResults.segments;
importResults.segments = _.map(segmentSelectElement.select2('data'),
function (data) {
return data.name;
});
importData.step2 = importResults;
enableSegmentSelection(mailpoetSegments);
window.importData.step2 = importResults;
enableSegmentSelection(window.mailpoetSegments);
router.navigate('step3', {trigger: true});
}
});
});
filterSubscribers();
enableSegmentSelection(mailpoetSegments);
enableSegmentSelection(window.mailpoetSegments);
});
router.on('route:step3', function () {
if (typeof (importData.step2) === 'undefined') {
if (typeof (window.importData.step2) === 'undefined') {
router.navigate('step2', {trigger: true});
return;
}
showCurrentStep();
if (importData.step2.errors.length > 0) {
MailPoet.Notice.error(_.flatten(importData.step2.errors));
if (window.importData.step2.errors.length > 0) {
MailPoet.Notice.error(_.flatten(window.importData.step2.errors));
}
MailPoet.trackEvent('Subscribers import finished', {
'Subscribers created': importData.step2.created,
'Subscribers updated': importData.step2.updated,
'Subscribers created': window.importData.step2.created,
'Subscribers updated': window.importData.step2.updated,
'MailPoet Free version': window.mailpoet_version
});
@ -1089,21 +1089,21 @@ define(
Handlebars
.compile(jQuery('#subscribers_data_import_results_template')
.html()),
exportMenuElement = jQuery('span.mailpoet_export'),
importResults = {
created: (importData.step2.created)
exportMenuElement = jQuery('span.mailpoet_export'),
importResults = {
created: (window.importData.step2.created)
? MailPoet.I18n.t('subscribersCreated')
.replace('%1$s', '<strong>' + importData.step2.created.toLocaleString() + '</strong>')
.replace('%2$s', '"' + importData.step2.segments.join('", "') + '"')
.replace('%1$s', '<strong>' + window.importData.step2.created.toLocaleString() + '</strong>')
.replace('%2$s', '"' + window.importData.step2.segments.join('", "') + '"')
: false,
updated: (importData.step2.updated)
updated: (window.importData.step2.updated)
? MailPoet.I18n.t('subscribersUpdated')
.replace('%1$s', '<strong>' + importData.step2.updated.toLocaleString() + '</strong>')
.replace('%2$s', '"' + importData.step2.segments.join('", "') + '"')
.replace('%1$s', '<strong>' + window.importData.step2.updated.toLocaleString() + '</strong>')
.replace('%2$s', '"' + window.importData.step2.segments.join('", "') + '"')
: false,
no_action: (!importData.step2.created && !importData.step2.updated),
added_to_segment_with_welcome_notification: importData.step2.added_to_segment_with_welcome_notification
};
no_action: (!window.importData.step2.created && !window.importData.step2.updated),
added_to_segment_with_welcome_notification: window.importData.step2.added_to_segment_with_welcome_notification
};
jQuery('#subscribers_data_import_results')
.html(subscribersDataImportResultsTemplate(importResults))
@ -1125,7 +1125,7 @@ define(
}
// reset previous step's data so that coming back to this step is prevented
importData.step2 = undefined;
window.importData.step2 = undefined;
});
if (!Backbone.History.started) {

View File

@ -83,7 +83,7 @@ const messages = {
MailPoet.Notice.success(message);
},
onNoItemsFound: (group) => {
if (group === 'bounced' && !mailpoet_premium_active) {
if (group === 'bounced' && !window.mailpoet_premium_active) {
return (
<div>
<p>{MailPoet.I18n.t('bouncedSubscribersHelp')}</p>
@ -245,7 +245,7 @@ const item_actions = [
const SubscriberList = React.createClass({
getSegmentFromId: function (segment_id) {
let result = false;
mailpoet_segments.map((segment) => {
window.mailpoet_segments.map((segment) => {
if (segment.id === segment_id) {
result = segment;
}
@ -350,7 +350,7 @@ const SubscriberList = React.createClass({
</h1>
<Listing
limit={ mailpoet_listing_per_page }
limit={ window.mailpoet_listing_per_page }
location={ this.props.location }
params={ this.props.params }
endpoint="subscribers"

View File

@ -2,6 +2,8 @@
namespace MailPoet\Config;
use MailPoet\Models\Setting;
if(!defined('ABSPATH')) exit;
class Activator {
@ -11,8 +13,7 @@ class Activator {
$populator = new Populator();
$populator->up();
update_option('mailpoet_db_version', Env::$version);
Setting::setValue('db_version', Env::$version);
}
function deactivate() {

View File

@ -4,6 +4,7 @@ namespace MailPoet\Config;
use MailPoet\API;
use MailPoet\Cron\CronTrigger;
use MailPoet\Models\Setting;
use MailPoet\Router;
use MailPoet\Util\ConflictResolver;
use MailPoet\Util\Helpers;
@ -61,12 +62,17 @@ class Initializer {
add_action('init', array(
$this,
'onInit'
'preInitialize'
), 0);
add_action('init', array(
$this,
'initialize'
));
add_action('wp_loaded', array(
$this,
'setupHooks'
'postInitialize'
));
add_action('admin_init', array(
@ -90,7 +96,27 @@ class Initializer {
$database->init();
}
function onInit() {
function preInitialize() {
try {
$this->setupRenderer();
$this->setupWidget();
} catch(\Exception $e) {
$this->handleFailedInitialization($e);
}
}
function setupRenderer() {
$caching = !WP_DEBUG;
$debugging = WP_DEBUG;
$this->renderer = new Renderer($caching, $debugging);
}
function setupWidget() {
$widget = new Widget($this->renderer);
$widget->init();
}
function initialize() {
try {
$this->setupAccessControl();
@ -98,8 +124,6 @@ class Initializer {
$this->setupInstaller();
$this->setupUpdater();
$this->setupRenderer();
$this->setupWidget();
$this->setupLocalizer();
$this->setupMenu();
$this->setupShortcodes();
@ -109,8 +133,6 @@ class Initializer {
$this->setupCronTrigger();
$this->setupConflictResolver();
$this->setupJSONAPI();
$this->setupRouter();
$this->setupPages();
do_action('mailpoet_initialized', MAILPOET_VERSION);
@ -122,7 +144,11 @@ class Initializer {
}
function maybeDbUpdate() {
$current_db_version = get_option('mailpoet_db_version', false);
try {
$current_db_version = Setting::getValue('db_version');
} catch(\Exception $e) {
$current_db_version = null;
}
// if current db version and plugin version differ
if(version_compare($current_db_version, Env::$version) !== 0) {
@ -158,19 +184,8 @@ class Initializer {
$updater->init();
}
function setupRenderer() {
$caching = !WP_DEBUG;
$debugging = WP_DEBUG;
$this->renderer = new Renderer($caching, $debugging);
}
function setupWidget() {
$widget = new Widget($this->renderer);
$widget->init();
}
function setupLocalizer() {
$localizer = new Localizer($this->renderer);
$localizer = new Localizer();
$localizer->init();
}
@ -206,6 +221,17 @@ class Initializer {
$conflict_resolver->init();
}
function postInitialize() {
if(!defined(self::INITIALIZED)) return;
try {
$this->setupHooks();
$this->setupJSONAPI();
$this->setupRouter();
} catch(\Exception $e) {
$this->handleFailedInitialization($e);
}
}
function setupJSONAPI() {
$json_api = API\API::JSON($this->access_control);
$json_api->init();
@ -222,13 +248,8 @@ class Initializer {
}
function setupHooks() {
if(!defined(self::INITIALIZED)) return;
try {
$hooks = new Hooks();
$hooks->init();
} catch(\Exception $e) {
$this->handleFailedInitialization($e);
}
$hooks = new Hooks();
$hooks->init();
}
function handleFailedInitialization($exception) {

View File

@ -1,32 +1,21 @@
<?php
namespace MailPoet\Config;
if(!defined('ABSPATH')) exit;
class Localizer {
function __construct($renderer) {
$this->renderer = $renderer;
}
function init() {
add_action(
'init',
array($this, 'setup')
);
}
function setup() {
$this->loadGlobalText();
$this->loadPluginText();
$this->setGlobalRtl();
}
function loadGlobalText() {
$language_path =
Env::$languages_path
. '/'
. $this->locale()
. '.mo';
$language_path = sprintf(
'%s/%s.mo',
Env::$languages_path,
$this->locale()
);
load_textdomain(Env::$plugin_name, $language_path);
}
@ -38,10 +27,6 @@ class Localizer {
);
}
function setGlobalRtl() {
$this->renderer->addGlobal('is_rtl', is_rtl());
}
function locale() {
$locale = apply_filters(
'plugin_locale',

View File

@ -148,7 +148,7 @@ class MP2Migrator {
}
ob_start();
$datetime = new \MailPoet\WP\DateTime();
$this->log(sprintf('=== ' . __('START IMPORT', 'mailpoet') . ' %s ===', $datetime->formatTime(time(), \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT)));
$this->log(sprintf('=== ' . mb_strtoupper(__('Start import', 'mailpoet'), 'UTF-8') . ' %s ===', $datetime->formatTime(time(), \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT)));
Setting::setValue('import_stopped', false); // Reset the stop import action
if(!Setting::getValue('mailpoet_migration_started', false)) {
@ -165,10 +165,10 @@ class MP2Migrator {
if(!$this->importStopped()) {
Setting::setValue('mailpoet_migration_complete', true);
$this->log(__('IMPORT COMPLETE', 'mailpoet'));
$this->log(mb_strtoupper(__('Import complete', 'mailpoet'), 'UTF-8'));
}
$this->log(sprintf('=== ' . __('END IMPORT', 'mailpoet') . ' %s ===', $datetime->formatTime(time(), \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT)));
$this->log(sprintf('=== ' . mb_strtoupper(__('End import', 'mailpoet'), 'UTF-8') . ' %s ===', $datetime->formatTime(time(), \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT)));
$result = ob_get_contents();
ob_clean();
return $result;
@ -223,7 +223,7 @@ class MP2Migrator {
*/
public function stopImport() {
Setting::setValue('import_stopped', true);
$this->log(__('IMPORT STOPPED BY USER', 'mailpoet'));
$this->log(mb_strtoupper(__('Import stopped by user', 'mailpoet'), 'UTF-8'));
}
/**
@ -486,7 +486,7 @@ class MP2Migrator {
break;
default:
$params['date_format'] = strtoupper($params['date_order']);
$params['date_format'] = mb_strtoupper($params['date_order'], 'UTF-8');
}
unset($params['date_order']);
}
@ -1140,4 +1140,4 @@ class MP2Migrator {
}
return $emails_number;
}
}
}

View File

@ -172,7 +172,8 @@ class Migrator {
'deleted_at TIMESTAMP NULL,',
'unconfirmed_data longtext,',
'PRIMARY KEY (id),',
'UNIQUE KEY email (email)'
'UNIQUE KEY email (email),',
'KEY wp_user_id (wp_user_id)',
);
return $this->sqlify(__FUNCTION__, $attributes);
}

View File

@ -3,8 +3,6 @@
namespace MailPoet\Config;
class PluginActivatedHook {
/** @var DeferredAdminNotices */
private $deferred_admin_notices;
public function __construct(DeferredAdminNotices $deferred_admin_notices) {
@ -13,8 +11,7 @@ class PluginActivatedHook {
public function action($plugin, $network_wide) {
if($plugin === plugin_basename(Env::$file) && $network_wide) {
$this->deferred_admin_notices->addNetworkAdminNotice(__('We noticed that you\'re using an unsupported environment. While MailPoet might work within a MultiSite environment, we dont support it.', 'mailpoet'));
$this->deferred_admin_notices->addNetworkAdminNotice(__("We noticed that you're using an unsupported environment. While MailPoet might work within a MultiSite environment, we dont support it.", 'mailpoet'));
}
}
}

View File

@ -337,7 +337,7 @@ class Populator {
function convertExistingDataToUTF8() {
global $wpdb;
if(!version_compare(get_option('mailpoet_db_version', '3.0.0-beta.33'), '3.0.0-beta.32', '<=')) {
if(!version_compare(Setting::getValue('db_version', '3.0.0-beta.33'), '3.0.0-beta.32', '<=')) {
// Data conversion should only be performed only once, when migrating from
// older version
return false;
@ -402,7 +402,7 @@ class Populator {
global $wpdb;
// perform once for versions below 3.0.0-beta.36.2.1
if(version_compare(get_option('mailpoet_db_version', '3.0.0-beta.36.2.3'), '3.0.0-beta.36.2.1', '>=')) {
if(version_compare(Setting::getValue('db_version', '3.0.0-beta.36.2.3'), '3.0.0-beta.36.2.1', '>=')) {
return false;
}
@ -455,7 +455,7 @@ class Populator {
global $wpdb;
// perform once for versions below 3.0.0-beta.36.2.1
if(version_compare(get_option('mailpoet_db_version', '3.0.0-beta.36.2.3'), '3.0.0-beta.36.2.1', '>=')) {
if(version_compare(Setting::getValue('db_version', '3.0.0-beta.36.2.3'), '3.0.0-beta.36.2.1', '>=')) {
return false;
}

View File

@ -15,7 +15,7 @@ class NewsDay {
function get() {
return array(
'name' => __("News Day", 'mailpoet'),
'description' => __("Media ready template. ", 'mailpoet'),
'description' => __("Media ready template.", 'mailpoet'),
'readonly' => 1,
'thumbnail' => $this->getThumbnail(),
'body' => json_encode($this->getBody()),
@ -552,4 +552,4 @@ class NewsDay {
return $this->template_image_url . '/news-day.jpg';
}
}
}

View File

@ -117,7 +117,7 @@ class NewsletterBlank12Column {
),
array(
"type" => "text",
"text" => __("<h1 style=\"text-align: center;\"><strong>Let's Get Started!</strong></h1>\n<p></p>\n<p>It's time to design your newsletter! In the right sidebar, you'll find 4 menu items that will help you customize your newsletter:</p>\n<ol>\n<li>Content</li>\n<li>Columns</li>\n<li>Styles</li>\n<li>Preview</li>\n</ol>", 'mailpoet')
"text" => __("<h1 style=\"text-align: center;\"><strong>Let's Get Started!</strong></h1>\n<p>&nbsp;</p>\n<p>It's time to design your newsletter! In the right sidebar, you'll find 4 menu items that will help you customize your newsletter:</p>\n<ol>\n<li>Content</li>\n<li>Columns</li>\n<li>Styles</li>\n<li>Preview</li>\n</ol>", 'mailpoet')
),
array(
"type" => "divider",

View File

@ -117,7 +117,7 @@ class NewsletterBlank13Column {
),
array(
"type" => "text",
"text" => __("<h1 style=\"text-align: center;\"><strong>Let's Get Started! </strong></h1>\n<p></p>\n<p>It's time to design your newsletter! In the right sidebar, you'll find four menu items that will help you customize your newsletter:</p>\n<ol>\n<li>Content</li>\n<li>Columns</li>\n<li>Styles</li>\n<li>Preview</li>\n</ol>", 'mailpoet')
"text" => __("<h1 style=\"text-align: center;\"><strong>Let's Get Started! </strong></h1>\n<p>&nbsp;</p>\n<p>It's time to design your newsletter! In the right sidebar, you'll find four menu items that will help you customize your newsletter:</p>\n<ol>\n<li>Content</li>\n<li>Columns</li>\n<li>Styles</li>\n<li>Preview</li>\n</ol>", 'mailpoet')
),
array(
"type" => "divider",

View File

@ -117,7 +117,7 @@ class NewsletterBlank1Column {
),
array(
"type" => "text",
"text" => __("<h1 style=\"text-align: center;\"><strong>Let's Get Started! </strong></h1>\n<p></p>\n<p>It's time to design your newsletter! In the right sidebar, you'll find 4 menu items that will help you customize your newsletter:</p>\n<ol>\n<li>Content</li>\n<li>Columns</li>\n<li>Styles</li>\n<li>Preview</li>\n</ol>", 'mailpoet')
"text" => __("<h1 style=\"text-align: center;\"><strong>Let's Get Started! </strong></h1>\n<p>&nbsp;</p>\n<p>It's time to design your newsletter! In the right sidebar, you'll find 4 menu items that will help you customize your newsletter:</p>\n<ol>\n<li>Content</li>\n<li>Columns</li>\n<li>Styles</li>\n<li>Preview</li>\n</ol>", 'mailpoet')
)
)
)

View File

@ -117,7 +117,7 @@ class PostNotificationsBlank1Column {
),
array(
"type" => "text",
"text" => __("<h1 style=\"text-align: center;\"><strong>Check Out Our New Blog Posts! </strong></h1>\n<p></p>\n<p>MailPoet can <span style=\"line-height: 1.6em; background-color: inherit;\"><em>automatically</em> </span><span style=\"line-height: 1.6em; background-color: inherit;\">send your new blog posts to your subscribers.</span></p>\n<p><span style=\"line-height: 1.6em; background-color: inherit;\"></span></p>\n<p><span style=\"line-height: 1.6em; background-color: inherit;\">Below, you'll find three recent posts, which are displayed automatically, thanks to the <em>Automatic Latest Content</em> widget, which can be found in the right sidebar, under <em>Content</em>.</span></p>\n<p><span style=\"line-height: 1.6em; background-color: inherit;\"></span></p>\n<p><span style=\"line-height: 1.6em; background-color: inherit;\">To edit the settings and styles of your post, simply click on a post below.</span></p>", 'mailpoet')
"text" => __("<h1 style=\"text-align: center;\"><strong>Check Out Our New Blog Posts! </strong></h1>\n<p>&nbsp;</p>\n<p>MailPoet can <span style=\"line-height: 1.6em; background-color: inherit;\"><em>automatically</em> </span><span style=\"line-height: 1.6em; background-color: inherit;\">send your new blog posts to your subscribers.</span></p>\n<p><span style=\"line-height: 1.6em; background-color: inherit;\"></span></p>\n<p><span style=\"line-height: 1.6em; background-color: inherit;\">Below, you'll find three recent posts, which are displayed automatically, thanks to the <em>Automatic Latest Content</em> widget, which can be found in the right sidebar, under <em>Content</em>.</span></p>\n<p><span style=\"line-height: 1.6em; background-color: inherit;\"></span></p>\n<p><span style=\"line-height: 1.6em; background-color: inherit;\">To edit the settings and styles of your post, simply click on a post below.</span></p>", 'mailpoet')
),
array(
"type" => "divider",

View File

@ -132,7 +132,7 @@ class SimpleText {
),
array(
"type" => "text",
"text" => __("<p>Thanks for reading. See you soon!</p>\n<p></p>\n<p><strong><em>The MailPoet Team</em></strong></p>", 'mailpoet')
"text" => __("<p>Thanks for reading. See you soon!</p>\n<p>&nbsp;</p>\n<p><strong><em>The MailPoet Team</em></strong></p>", 'mailpoet')
),
array(
"type" => "footer",

View File

@ -117,7 +117,7 @@ class WelcomeBlank12Column {
),
array(
"type" => "text",
"text" => __("<h1 style=\"text-align: center;\"><strong>Hi, new subscriber!</strong></h1>\n<p></p>\n<p>[subscriber:firstname | default:Subscriber],</p>\n<p></p>\n<p>You recently joined our list and we'd like to give you a warm welcome!</p>", 'mailpoet')
"text" => __("<h1 style=\"text-align: center;\"><strong>Hi, new subscriber!</strong></h1>\n<p>&nbsp;</p>\n<p>[subscriber:firstname | default:Subscriber],</p>\n<p>&nbsp;</p>\n<p>You recently joined our list and we'd like to give you a warm welcome!</p>", 'mailpoet')
),
array(
"type" => "divider",

View File

@ -117,7 +117,7 @@ class WelcomeBlank1Column {
),
array(
"type" => "text",
"text" => __("<h1 style=\"text-align: center;\"><strong>Hi, new subscriber!</strong></h1>\n<p></p>\n<p>[subscriber:firstname | default:Subscriber],</p>\n<p></p>\n<p>You recently joined our list and we'd like to give you a warm welcome!</p>\n<p></p>\n<p>Want to get to know us better? Check out some of our most popular articles: </p>\n<ol>\n<li><a href=\"http://www.mailpoet.com/the-importance-of-focus-when-writing/\">The Importance of Focus When Writing</a></li>\n<li><a href=\"http://www.mailpoet.com/write-great-subject-line/\">How to Write a Great Subject Line</a></li>\n<li><a href=\"http://www.mailpoet.com/just-sit-write-advice-motivation-ernest-hemingway/\">Just Sit Down and Write &ndash; Advice on Motivation from Ernest Hemingway</a></li>\n</ol>", 'mailpoet')
"text" => __("<h1 style=\"text-align: center;\"><strong>Hi, new subscriber!</strong></h1>\n<p>&nbsp;</p>\n<p>[subscriber:firstname | default:Subscriber],</p>\n<p>&nbsp;</p>\n<p>You recently joined our list and we'd like to give you a warm welcome!</p>\n<p>&nbsp;</p>\n<p>Want to get to know us better? Check out some of our most popular articles: </p>\n<ol>\n<li><a href=\"http://www.mailpoet.com/the-importance-of-focus-when-writing/\">The Importance of Focus When Writing</a></li>\n<li><a href=\"http://www.mailpoet.com/write-great-subject-line/\">How to Write a Great Subject Line</a></li>\n<li><a href=\"http://www.mailpoet.com/just-sit-write-advice-motivation-ernest-hemingway/\">Just Sit Down and Write &ndash; Advice on Motivation from Ernest Hemingway</a></li>\n</ol>", 'mailpoet')
)
)
)

View File

@ -15,7 +15,7 @@ class WorldCup {
function get() {
return array(
'name' => __("World Cup", 'mailpoet'),
'description' => __("Always a winner. ", 'mailpoet'),
'description' => __("Always a winner.", 'mailpoet'),
'readonly' => 1,
'thumbnail' => $this->getThumbnail(),
'body' => json_encode($this->getBody()),
@ -782,4 +782,4 @@ class WorldCup {
return $this->template_image_url . '/world-cup.jpg';
}
}
}

View File

@ -34,7 +34,6 @@ class Renderer {
$this->assets_manifest_js = $this->getAssetManifest(Env::$assets_path . '/js/manifest.json');
$this->assets_manifest_css = $this->getAssetManifest(Env::$assets_path . '/css/manifest.json');
$this->setupDebug();
$this->setupTranslations();
$this->setupFunctions();
@ -112,10 +111,6 @@ class Renderer {
}
}
function addGlobal($key, $value) {
return $this->renderer->addGlobal($key, $value);
}
function getAssetManifest($manifest_file) {
return (is_readable($manifest_file)) ?
json_decode(file_get_contents($manifest_file), true) :

View File

@ -13,6 +13,7 @@ class RequirementsChecker {
const TEST_XML_EXTENSION = 'XmlExtension';
const TEST_ZIP_EXTENSION = 'ZipExtension';
const TEST_VENDOR_SOURCE = 'VendorSource';
const TWIG_SUPPORTED_VERSIONS = '1.26.0-1.34.4';
public $display_error_notice;
public $vendor_classes = array(
@ -22,7 +23,6 @@ class RequirementsChecker {
'\Twig_Loader_Filesystem',
'\Twig_Lexer',
'\Twig_Extension',
'\Twig_Extension_GlobalsInterface',
'\Twig_SimpleFunction',
'\Swift_Mailer',
'\Swift_SmtpTransport',
@ -141,13 +141,30 @@ class RequirementsChecker {
$dependency_path
);
return $this->processError($error);
$return_error = true;
// if a Twig dependency is loaded by another plugin, check for valid version
if(strpos($dependency, '\Twig_') === 0) {
$return_error = ($this->isValidTwigVersion()) ? false : $return_error;
}
if($return_error) return $this->processError($error);
}
}
return true;
}
function isValidTwigVersion() {
list($minimum_version, $maximum_version) = explode('-', self::TWIG_SUPPORTED_VERSIONS);
return (
class_exists('\Twig_Environment') &&
defined('\Twig_Environment::VERSION') &&
version_compare(\Twig_Environment::VERSION, $minimum_version, '>=') &&
version_compare(\Twig_Environment::VERSION, $maximum_version, '<=')
);
}
private function getDependencyPath($namespaced_class) {
try {
$reflector = new \ReflectionClass($namespaced_class);
@ -163,4 +180,4 @@ class RequirementsChecker {
}
return false;
}
}
}

View File

@ -40,7 +40,7 @@ class ServicesChecker {
$date_time = new DateTime();
$date = $date_time->formatDate(strtotime($mss_key['data']['expire_at']));
$error = Helpers::replaceLinkTags(
__('Your newsletters are awesome! Don\'t forget to [link]upgrade your MailPoet email plan[/link] by %s to keep sending them to your subscribers.', 'mailpoet'),
__("Your newsletters are awesome! Don't forget to [link]upgrade your MailPoet email plan[/link] by %s to keep sending them to your subscribers.", 'mailpoet'),
'https://account.mailpoet.com?s=' . Subscriber::getTotalSubscribers(),
array('target' => '_blank')
);
@ -93,7 +93,7 @@ class ServicesChecker {
$date_time = new DateTime();
$date = $date_time->formatDate(strtotime($premium_key['data']['expire_at']));
$error = Helpers::replaceLinkTags(
__('Your License Key is expiring! Don\'t forget to [link]renew your license[/link] by %s to keep enjoying automatic updates and Premium support.', 'mailpoet'),
__("Your License Key is expiring! Don't forget to [link]renew your license[/link] by %s to keep enjoying automatic updates and Premium support.", 'mailpoet'),
'https://account.mailpoet.com',
array('target' => '_blank')
);

View File

@ -1,17 +1,19 @@
<?php
namespace MailPoet\Cron;
use MailPoet\Models\Setting;
use MailPoet\Router\Endpoints\CronDaemon as CronDaemonEndpoint;
use MailPoet\Router\Router;
use MailPoet\Util\Security;
use MailPoet\WP\Hooks as WPHooks;
if(!defined('ABSPATH')) exit;
class CronHelper {
const DAEMON_EXECUTION_LIMIT = 20; // seconds
const DAEMON_EXECUTION_TIMEOUT = 35; // seconds
const DAEMON_REQUEST_TIMEOUT = 2; // seconds
const DAEMON_REQUEST_TIMEOUT = 5; // seconds
const DAEMON_SETTING = 'cron_daemon';
static function createDaemon($token) {
@ -47,39 +49,50 @@ class CronHelper {
}
static function pingDaemon() {
$url = Router::buildRequest(
CronDaemonEndpoint::ENDPOINT,
$url = self::getCronUrl(
CronDaemonEndpoint::ACTION_PING_RESPONSE
);
$url = str_replace(home_url(), self::getSiteUrl(), $url);
$args = array(
'blocking' => true,
'sslverify' => false,
'timeout' => self::DAEMON_REQUEST_TIMEOUT,
'user-agent' => 'MailPoet (www.mailpoet.com) Cron'
);
$result = wp_remote_get($url, $args);
return wp_remote_retrieve_body($result) === 'pong';
$result = self::queryCronUrl($url);
return (is_wp_error($result)) ?
$result->get_error_message() :
wp_remote_retrieve_body($result);
}
static function accessDaemon($token, $timeout = self::DAEMON_REQUEST_TIMEOUT) {
static function accessDaemon($token) {
$data = array('token' => $token);
$url = Router::buildRequest(
CronDaemonEndpoint::ENDPOINT,
$url = self::getCronUrl(
CronDaemonEndpoint::ACTION_RUN,
$data
);
$url = str_replace(home_url(), self::getSiteUrl(), $url);
$args = array(
'blocking' => true,
'sslverify' => false,
'timeout' => $timeout,
'user-agent' => 'MailPoet (www.mailpoet.com) Cron'
);
$result = wp_remote_get($url, $args);
$result = self::queryCronUrl($url);
return wp_remote_retrieve_body($result);
}
static function queryCronUrl($url) {
$args = WPHooks::applyFilters(
'mailpoet_cron_request_args',
array(
'blocking' => true,
'sslverify' => false,
'timeout' => self::DAEMON_REQUEST_TIMEOUT,
'user-agent' => 'MailPoet Cron'
)
);
return wp_remote_get($url, $args);
}
static function getCronUrl($action, $data = false) {
$url = Router::buildRequest(
CronDaemonEndpoint::ENDPOINT,
$action,
$data
);
$custom_cron_url = WPHooks::applyFilters('mailpoet_cron_request_url', $url);
return ($custom_cron_url === $url) ?
str_replace(home_url(), self::getSiteUrl(), $url) :
$custom_cron_url;
}
static function getSiteUrl($site_url = false) {
// additional check for some sites running inside a virtual machine or behind
// proxy where there could be different ports (e.g., host:8080 => guest:80)

View File

@ -13,7 +13,6 @@ class Daemon {
public $daemon;
public $request_data;
public $timer;
const REQUEST_TIMEOUT = 5; // seconds
function __construct($request_data = false) {
$this->request_data = $request_data;
@ -100,7 +99,7 @@ class Daemon {
}
function callSelf() {
CronHelper::accessDaemon($this->token, self::REQUEST_TIMEOUT);
CronHelper::accessDaemon($this->token);
return $this->terminateRequest();
}

View File

@ -5,6 +5,7 @@ use MailPoet\Models\Subscriber;
use MailPoet\Models\Setting;
use MailPoet\Router\Endpoints\CronDaemon;
use MailPoet\Router\Router;
use MailPoet\Services\Bridge;
if(!defined('ABSPATH')) exit;
@ -20,12 +21,14 @@ class Beacon {
CronDaemon::ACTION_PING
);
$cron_ping_url = str_replace(home_url(), CronHelper::getSiteUrl(), $cron_ping_url);
$premium_key = Setting::getValue(Bridge::PREMIUM_KEY_SETTING_NAME) ?: Setting::getValue(Bridge::API_KEY_SETTING_NAME);
return array(
'name' => $current_user->display_name,
'email' => $current_user->user_email,
'PHP version' => PHP_VERSION,
'MailPoet Free version' => MAILPOET_VERSION,
'MailPoet Premium version' => (defined('MAILPOET_PREMIUM_VERSION')) ? MAILPOET_PREMIUM_VERSION : 'N/A',
'MailPoet Premium/MSS key' => $premium_key,
'WordPress version' => get_bloginfo('version'),
'Database version' => $db_version,
'Web server' => (!empty($_SERVER["SERVER_SOFTWARE"])) ? $_SERVER["SERVER_SOFTWARE"] : 'N/A',

View File

@ -79,28 +79,109 @@ class WP {
}
static function synchronizeUsers() {
// get wordpress users list
$wp_segment = Segment::getWPSegment();
// fetch all wp users id
$wp_users = \get_users(array(
'count_total' => false,
'fields' => 'ID'
));
// update data for each wp user
foreach($wp_users as $wp_user_id) {
static::synchronizeUser($wp_user_id);
}
// remove orphaned wp segment subscribers (not having a matching wp user id),
// e.g. if wp users were deleted directly from the database
$wp_segment->subscribers()
->whereNotIn('wp_user_id', $wp_users)
->findResultSet()
->set('wp_user_id', null)
->delete();
self::updateSubscribersEmails();
self::insertSubscribers();
self::removeFromTrash();
self::updateFirstNames();
self::updateLastNames();
self::updateFristNameIfMissing();
self::insertUsersToSegment();
self::removeOrphanedSubscribers();
return true;
}
private static function updateSubscribersEmails() {
global $wpdb;
$subscribers_table = Subscriber::$_table;
Subscriber::raw_execute(sprintf('
UPDATE IGNORE %s
JOIN %s as wu ON %s.wp_user_id = wu.id
SET email = user_email
WHERE %s.wp_user_id IS NOT NULL
', $subscribers_table, $wpdb->users, $subscribers_table, $subscribers_table));
}
private static function insertSubscribers() {
global $wpdb;
$subscribers_table = Subscriber::$_table;
Subscriber::raw_execute(sprintf('
INSERT IGNORE INTO %s(wp_user_id, email, status, created_at)
SELECT wu.id, wu.user_email, "subscribed", CURRENT_TIMESTAMP() FROM %s wu
LEFT JOIN %s mps ON wu.id = mps.wp_user_id
WHERE mps.wp_user_id IS NULL
', $subscribers_table, $wpdb->users, $subscribers_table));
}
private static function updateFirstNames() {
global $wpdb;
$subscribers_table = Subscriber::$_table;
Subscriber::raw_execute(sprintf('
UPDATE %s
JOIN %s as wpum ON %s.wp_user_id = wpum.user_id AND meta_key = "first_name"
SET first_name = meta_value
WHERE %s.first_name = ""
AND %s.wp_user_id IS NOT NULL
', $subscribers_table, $wpdb->usermeta, $subscribers_table, $subscribers_table, $subscribers_table));
}
private static function updateLastNames() {
global $wpdb;
$subscribers_table = Subscriber::$_table;
Subscriber::raw_execute(sprintf('
UPDATE %s
JOIN %s as wpum ON %s.wp_user_id = wpum.user_id AND meta_key = "last_name"
SET last_name = meta_value
WHERE %s.last_name = ""
AND %s.wp_user_id IS NOT NULL
', $subscribers_table, $wpdb->usermeta, $subscribers_table, $subscribers_table, $subscribers_table));
}
private static function updateFristNameIfMissing() {
global $wpdb;
$subscribers_table = Subscriber::$_table;
Subscriber::raw_execute(sprintf('
UPDATE %s
JOIN %s wu ON %s.wp_user_id = wu.id
SET first_name = display_name
WHERE %s.first_name = ""
AND %s.wp_user_id IS NOT NULL
', $subscribers_table, $wpdb->users, $subscribers_table, $subscribers_table, $subscribers_table));
}
private static function insertUsersToSegment() {
$wp_segment = Segment::getWPSegment();
$subscribers_table = Subscriber::$_table;
$wp_mailpoet_subscriber_segment_table = SubscriberSegment::$_table;
Subscriber::raw_execute(sprintf('
INSERT IGNORE INTO %s(subscriber_id, segment_id, created_at)
SELECT mps.id, "%s", CURRENT_TIMESTAMP() FROM %s mps
WHERE mps.wp_user_id > 0
', $wp_mailpoet_subscriber_segment_table, $wp_segment->id, $subscribers_table));
}
private static function removeFromTrash() {
$subscribers_table = Subscriber::$_table;
Subscriber::raw_execute(sprintf('
UPDATE %s
SET deleted_at = NULL
WHERE %s.wp_user_id IS NOT NULL
', $subscribers_table, $subscribers_table));
}
private static function removeOrphanedSubscribers() {
// remove orphaned wp segment subscribers (not having a matching wp user id),
// e.g. if wp users were deleted directly from the database
global $wpdb;
$wp_segment = Segment::getWPSegment();
$wp_segment->subscribers()
->leftOuterJoin($wpdb->users, array(MP_SUBSCRIBERS_TABLE . '.wp_user_id', '=', 'wu.id'), 'wu')
->whereNull('wu.id')
->findResultSet()
->set('wp_user_id', null)
->delete();
}
}

View File

@ -1,4 +1,5 @@
<?php
namespace MailPoet\Twig;
use MailPoet\Analytics\Reporter;
@ -7,11 +8,6 @@ use MailPoet\Analytics\Analytics as AnalyticsGenerator;
if(!defined('ABSPATH')) exit;
class Analytics extends \Twig_Extension {
public function getName() {
return 'analytics';
}
public function getFunctions() {
$analytics = new AnalyticsGenerator(new Reporter());
return array(

View File

@ -1,25 +1,16 @@
<?php
namespace MailPoet\Twig;
use MailPoet\Config\Env;
namespace MailPoet\Twig;
if(!defined('ABSPATH')) exit;
class Assets extends \Twig_Extension implements \Twig_Extension_GlobalsInterface {
class Assets extends \Twig_Extension {
private $_globals;
function __construct($globals) {
$this->_globals = $globals;
}
function getName() {
return 'assets';
}
function getGlobals() {
return $this->_globals;
}
function getFunctions() {
return array(
new \Twig_SimpleFunction(

View File

@ -1,15 +1,12 @@
<?php
namespace MailPoet\Twig;
use MailPoet\Config\ServicesChecker;
if(!defined('ABSPATH')) exit;
class Functions extends \Twig_Extension {
function getName() {
return 'functions';
}
function getFunctions() {
return array(
new \Twig_SimpleFunction(
@ -86,6 +83,11 @@ class Functions extends \Twig_Extension {
'do_action',
'do_action',
array('is_safe' => array('all'))
),
new \Twig_SimpleFunction(
'is_rtl',
array($this, 'isRtl'),
array('is_safe' => array('all'))
)
);
}
@ -162,4 +164,8 @@ class Functions extends \Twig_Extension {
$checker = new ServicesChecker();
return $checker->isPremiumKeyValid(false);
}
}
function isRtl() {
return is_rtl();
}
}

View File

@ -1,23 +1,23 @@
<?php
namespace MailPoet\Twig;
if(!defined('ABSPATH')) exit;
class Handlebars extends \Twig_Extension {
public function getName() {
return 'handlebars';
}
public function getFunctions() {
return array(
new \Twig_SimpleFunction(
'partial',
array($this, 'generatePartial'),
array(
$this,
'generatePartial'
),
array(
'needs_environment' => true,
'needs_context' => true,
'is_safe' => array('all'))
'needs_context' => true,
'is_safe' => array('all')
)
)
);
}
@ -41,23 +41,28 @@ class Handlebars extends \Twig_Extension {
return;
}
$output = array();
$rendered_template = twig_include($env, $context, $file);
$output[] = '<script id="'.$id.'" type="text/x-handlebars-template">';
$output[] = twig_include($env, $context, $file);
$output[] = '</script>';
$output = <<<EOL
<script id="$id" type="text/x-handlebars-template">
$rendered_template
</script>
EOL;
if($alias !== null) {
$output[] = '<script type="text/javascript">';
$output[] = 'jQuery(function($) {';
$output[] = '$(function() {';
$output[] = ' Handlebars.registerPartial(
"'.$alias.'",
jQuery("#'.$id.'").html());';
$output[] = '});';
$output[] = '});';
$output[] = '</script>';
$output .= <<<EOL
<script type="text/javascript">
jQuery(function($) {
$(function() {
Handlebars.registerPartial(
'$alias',
jQuery('#$id').html()
);
});
});
</script>
EOL;
}
return join("\n", $output);
return $output;
}
}

View File

@ -1,14 +1,10 @@
<?php
namespace MailPoet\Twig;
if(!defined('ABSPATH')) exit;
class Helpscout extends \Twig_Extension {
public function getName() {
return 'helpscout';
}
public function getFunctions() {
return array(
new \Twig_SimpleFunction(

View File

@ -1,4 +1,5 @@
<?php
namespace MailPoet\Twig;
if(!defined('ABSPATH')) exit;
@ -12,10 +13,6 @@ class I18n extends \Twig_Extension {
$this->_text_domain = $text_domain;
}
function getName() {
return 'i18n';
}
function getFunctions() {
// twig custom functions
$twig_functions = array();

Some files were not shown because too many files have changed in this diff Show More