@forgewp/compiler 0.4.3 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -0
- package/bin/add.js +20 -14
- package/bin/cli.js +145 -70
- package/bin/doctor.js +21 -12
- package/bin/export.js +69 -20
- package/bin/fresh.js +5 -0
- package/bin/i18n-extract.js +3 -10
- package/bin/i18n-translate.js +15 -24
- package/bin/make-block.js +13 -0
- package/bin/make-editable.js +166 -0
- package/bin/make-form.js +131 -0
- package/bin/make-loop.js +40 -43
- package/bin/make-mail.js +27 -0
- package/bin/make-post-type.js +57 -29
- package/bin/make-sandbox.js +62 -11
- package/bin/make-section.js +221 -0
- package/bin/make-shell.js +375 -0
- package/bin/repair.js +14 -26
- package/bin/seed.js +119 -0
- package/bin/sync-routes.js +107 -85
- package/lib/adapters/html-adapter.js +5 -0
- package/lib/adapters/stub-adapter.js +4 -0
- package/lib/add-component.js +153 -92
- package/lib/asset-loader.js +313 -3
- package/lib/assets/asset-graph.js +432 -0
- package/lib/assets/asset-pipeline.js +125 -0
- package/lib/assets/diagnostics-report.js +345 -0
- package/lib/assets/external-fetcher.js +173 -0
- package/lib/assets/font-orchestrator.js +348 -0
- package/lib/assets/font-usage-scanner.js +242 -0
- package/lib/assets/image-optimizer.js +229 -0
- package/lib/assets/index.js +51 -0
- package/lib/assets/preload-generator.js +70 -0
- package/lib/assets/public-url.js +153 -0
- package/lib/block-authoring-help.js +11 -0
- package/lib/blocks/ast-parser.js +67 -0
- package/lib/blocks/discover-blocks.js +146 -0
- package/lib/blocks/editor-scope.js +733 -0
- package/lib/blocks/editor-transpiler.js +1229 -0
- package/lib/blocks/index.js +2838 -0
- package/lib/blocks/php-transpiler.js +4928 -0
- package/lib/blocks/scanner.js +1487 -0
- package/lib/blocks/shared-utils.js +290 -0
- package/lib/blocks/source-sanitize.js +1449 -0
- package/lib/blueprints.js +31 -91
- package/lib/build-assets.js +38 -33
- package/lib/collect-page-template-routes.js +102 -0
- package/lib/collect-static-routes.js +175 -0
- package/lib/diagnostics.js +58 -33
- package/lib/export-theme.js +84 -5
- package/lib/extract-template-content.js +90 -0
- package/lib/forms-preview.js +42 -0
- package/lib/functions/cpt-routing.js +69 -0
- package/lib/functions/forms.js +2461 -0
- package/lib/functions/hydration-enqueuer.js +400 -0
- package/lib/functions/index.js +1623 -0
- package/lib/functions/load-menus.js +112 -0
- package/lib/functions/load-translations.js +148 -0
- package/lib/functions/rest-endpoints.js +2923 -0
- package/lib/functions/routing.js +765 -0
- package/lib/functions/seed-mock-data.js +392 -0
- package/lib/functions/seed-products.js +481 -0
- package/lib/functions/settings-page.js +273 -0
- package/lib/functions/theme-setup.js +494 -0
- package/lib/generate-theme.js +1916 -339
- package/lib/hydration/editable-schemas.js +332 -0
- package/lib/hydration/enter-hidden-initial.js +65 -0
- package/lib/hydration/form-schemas.js +227 -0
- package/lib/hydration/index.js +12 -0
- package/lib/hydration/is-interactive.js +951 -0
- package/lib/hydration/island-split.js +1231 -0
- package/lib/hydration/islands-scanner.js +599 -0
- package/lib/hydration/resolve-island-chunk.js +103 -0
- package/lib/hydration/resolve-island-component.js +52 -0
- package/lib/hydration/rollup-inputs.js +81 -0
- package/lib/hydration/root-class-extractor.js +220 -0
- package/lib/hydration/scan-app-providers.js +154 -0
- package/lib/hydration/static-lint.js +382 -0
- package/lib/hydration/transform.js +257 -0
- package/lib/hydration/uses-block-area.js +49 -0
- package/lib/hydration/utils.js +119 -0
- package/lib/i18n/translation-cache.js +141 -0
- package/lib/icon-registry.js +72 -0
- package/lib/index.d.ts +287 -8
- package/lib/index.js +2 -1
- package/lib/load-config.js +338 -242
- package/lib/mail-templates.js +37 -0
- package/lib/markup-processor.js +388 -102
- package/lib/node-runtime.js +7 -0
- package/lib/page-config-plugin.js +64 -20
- package/lib/php-builders.js +383 -44
- package/lib/react-adapter.js +983 -235
- package/lib/registration-metadata.js +11 -0
- package/lib/render-theme.mts +1410 -616
- package/lib/route-layout.js +76 -0
- package/lib/template-discovery.js +58 -0
- package/lib/theme-compatibility.js +32 -0
- package/lib/validate-export.js +2 -2
- package/lib/validate.js +27 -5
- package/lib/virtual-plugin.js +319 -0
- package/lib/walkthrough.md +26 -0
- package/package.json +16 -5
- package/templates/auth/cms/email-logs.json +9 -0
- package/templates/auth/cms/menus.json +11 -0
- package/templates/auth/cms/mock-data.json +123 -0
- package/templates/auth/cms/roles.json +7 -0
- package/templates/auth/cms/sessions.json +1 -0
- package/templates/auth/cms/site-settings.json +28 -0
- package/templates/auth/cms/translations.json +4 -0
- package/templates/auth/cms/users.json +46 -0
- package/templates/auth/components/forgot-password-form-wrapper.tsx +10 -2
- package/templates/auth/components/login-form-wrapper.tsx +118 -21
- package/templates/auth/components/reset-password-form-wrapper.tsx +10 -2
- package/templates/auth/components/signup-form-wrapper.tsx +2 -2
- package/templates/auth/components/verify-email-view-wrapper.tsx +5 -5
- package/templates/auth/pages/DashboardPage.tsx +1 -4
- package/templates/auth/pages/ForgotPasswordPage.tsx +1 -4
- package/templates/auth/pages/LoginPage.tsx +1 -4
- package/templates/auth/pages/ResetPasswordPage.tsx +1 -4
- package/templates/auth/pages/SignUpPage.tsx +1 -4
- package/templates/auth/pages/VerifyEmailPage.tsx +1 -4
- package/templates/auth/ui/button.tsx +57 -0
- package/templates/auth/ui/card.tsx +76 -0
- package/templates/auth/ui/field.tsx +242 -0
- package/templates/auth/ui/input.tsx +22 -0
- package/templates/auth/ui/label.tsx +24 -0
- package/templates/auth/ui/separator.tsx +31 -0
- package/templates/menus.json +12 -10
- package/templates/users.json +8 -4
- package/templates/wordpress.tsx +690 -245
- package/lib/block-compiler.js +0 -552
- package/lib/functions-builder.js +0 -2970
- package/lib/hydration-scanner.js +0 -833
|
@@ -0,0 +1,2923 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { registrationMetaFields } from '../registration-metadata.js';
|
|
4
|
+
|
|
5
|
+
function generatePhpArgs(queryObj) {
|
|
6
|
+
const phpLines = [];
|
|
7
|
+
phpLines.push(`$args = array(`);
|
|
8
|
+
|
|
9
|
+
if (queryObj.postType && typeof queryObj.postType === 'string') {
|
|
10
|
+
phpLines.push(` 'post_type' => '${queryObj.postType}',`);
|
|
11
|
+
} else {
|
|
12
|
+
phpLines.push(` 'post_type' => 'post',`);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
if (queryObj.postsPerPage !== undefined) {
|
|
16
|
+
const ppp = parseInt(queryObj.postsPerPage, 10);
|
|
17
|
+
phpLines.push(` 'posts_per_page' => ${isNaN(ppp) ? 10 : ppp},`);
|
|
18
|
+
} else {
|
|
19
|
+
phpLines.push(` 'posts_per_page' => 10,`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (queryObj.orderby) {
|
|
23
|
+
phpLines.push(` 'orderby' => '${queryObj.orderby}',`);
|
|
24
|
+
}
|
|
25
|
+
if (queryObj.order) {
|
|
26
|
+
phpLines.push(` 'order' => '${queryObj.order}',`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (queryObj.categoryName) {
|
|
30
|
+
if (String(queryObj.categoryName).startsWith('__DYNAMIC_')) {
|
|
31
|
+
const varName = String(queryObj.categoryName)
|
|
32
|
+
.replace(/^__DYNAMIC_/, '')
|
|
33
|
+
.replace(/__$/, '');
|
|
34
|
+
phpLines.push(
|
|
35
|
+
` 'category_name' => $request->get_param('${varName}') ? sanitize_text_field($request->get_param('${varName}')) : '',`,
|
|
36
|
+
);
|
|
37
|
+
} else {
|
|
38
|
+
phpLines.push(` 'category_name' => '${queryObj.categoryName}',`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
phpLines.push(` 'paged' => $paged,`);
|
|
43
|
+
|
|
44
|
+
if (
|
|
45
|
+
queryObj.taxQuery &&
|
|
46
|
+
Array.isArray(queryObj.taxQuery) &&
|
|
47
|
+
queryObj.taxQuery.length > 0
|
|
48
|
+
) {
|
|
49
|
+
phpLines.push(` 'tax_query' => array(`);
|
|
50
|
+
for (const [index, taxQ] of queryObj.taxQuery.entries()) {
|
|
51
|
+
phpLines.push(` array(`);
|
|
52
|
+
phpLines.push(` 'taxonomy' => '${taxQ.taxonomy}',`);
|
|
53
|
+
phpLines.push(` 'field' => '${taxQ.field || 'slug'}',`);
|
|
54
|
+
const termsVal = taxQ.terms;
|
|
55
|
+
let staticTermsPhp;
|
|
56
|
+
if (typeof termsVal === 'string' && termsVal.startsWith('__DYNAMIC_')) {
|
|
57
|
+
const varName = termsVal.replace(/^__DYNAMIC_/, '').replace(/__$/, '');
|
|
58
|
+
staticTermsPhp = `$request->get_param('${varName}') ? sanitize_text_field($request->get_param('${varName}')) : ''`;
|
|
59
|
+
} else if (Array.isArray(termsVal)) {
|
|
60
|
+
const termsPhp = termsVal
|
|
61
|
+
.map((t) =>
|
|
62
|
+
typeof t === 'string' ? `'${t.replace(/'/g, "\\'")}'` : t,
|
|
63
|
+
)
|
|
64
|
+
.join(', ');
|
|
65
|
+
staticTermsPhp = `array(${termsPhp})`;
|
|
66
|
+
} else {
|
|
67
|
+
staticTermsPhp =
|
|
68
|
+
typeof termsVal === 'string'
|
|
69
|
+
? `'${termsVal.replace(/'/g, "\\'")}'`
|
|
70
|
+
: String(termsVal);
|
|
71
|
+
}
|
|
72
|
+
phpLines.push(` 'terms' => (function() use ($request) {
|
|
73
|
+
$raw_terms = $request->get_param('tax_${index}');
|
|
74
|
+
if ($raw_terms === null) return ${staticTermsPhp};
|
|
75
|
+
$decoded_terms = json_decode($raw_terms, true);
|
|
76
|
+
if (is_array($decoded_terms)) {
|
|
77
|
+
return array_map('sanitize_text_field', $decoded_terms);
|
|
78
|
+
}
|
|
79
|
+
return sanitize_text_field((string) $raw_terms);
|
|
80
|
+
})(),`);
|
|
81
|
+
phpLines.push(` ),`);
|
|
82
|
+
}
|
|
83
|
+
phpLines.push(` ),`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (
|
|
87
|
+
queryObj.metaQuery &&
|
|
88
|
+
Array.isArray(queryObj.metaQuery) &&
|
|
89
|
+
queryObj.metaQuery.length > 0
|
|
90
|
+
) {
|
|
91
|
+
phpLines.push(` 'meta_query' => array(`);
|
|
92
|
+
if (queryObj.metaRelation) {
|
|
93
|
+
phpLines.push(` 'relation' => '${queryObj.metaRelation}',`);
|
|
94
|
+
}
|
|
95
|
+
for (const [index, metaQ] of queryObj.metaQuery.entries()) {
|
|
96
|
+
phpLines.push(` array(`);
|
|
97
|
+
phpLines.push(
|
|
98
|
+
` 'key' => '${String(metaQ.key).replace(/'/g, "\\'")}',`,
|
|
99
|
+
);
|
|
100
|
+
if (metaQ.compare) {
|
|
101
|
+
phpLines.push(` 'compare' => '${metaQ.compare}',`);
|
|
102
|
+
}
|
|
103
|
+
const metaType =
|
|
104
|
+
metaQ.type || (typeof metaQ.value === 'number' ? 'NUMERIC' : '');
|
|
105
|
+
if (metaType) {
|
|
106
|
+
phpLines.push(` 'type' => '${metaType}',`);
|
|
107
|
+
}
|
|
108
|
+
if (metaQ.value !== undefined) {
|
|
109
|
+
const val = metaQ.value;
|
|
110
|
+
let staticValuePhp;
|
|
111
|
+
if (typeof val === 'string' && val.startsWith('__DYNAMIC_')) {
|
|
112
|
+
const varName = val.replace(/^__DYNAMIC_/, '').replace(/__$/, '');
|
|
113
|
+
staticValuePhp = `$request->get_param('${varName}') ? sanitize_text_field($request->get_param('${varName}')) : ''`;
|
|
114
|
+
} else if (typeof val === 'string') {
|
|
115
|
+
staticValuePhp = `'${val.replace(/'/g, "\\'")}'`;
|
|
116
|
+
} else {
|
|
117
|
+
staticValuePhp = String(val);
|
|
118
|
+
}
|
|
119
|
+
phpLines.push(` 'value' => (function() use ($request) {
|
|
120
|
+
$raw_value = $request->get_param('meta_${index}');
|
|
121
|
+
if ($raw_value === null) return ${staticValuePhp};
|
|
122
|
+
$decoded_value = json_decode($raw_value, true);
|
|
123
|
+
return json_last_error() === JSON_ERROR_NONE
|
|
124
|
+
? $decoded_value
|
|
125
|
+
: sanitize_text_field((string) $raw_value);
|
|
126
|
+
})(),`);
|
|
127
|
+
}
|
|
128
|
+
phpLines.push(` ),`);
|
|
129
|
+
}
|
|
130
|
+
phpLines.push(` ),`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
phpLines.push(` );`);
|
|
134
|
+
return phpLines.join('\n');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function buildRestEndpointsPhp(
|
|
138
|
+
config,
|
|
139
|
+
queries,
|
|
140
|
+
hasAuth,
|
|
141
|
+
defaultPasswordResetEmailSubject,
|
|
142
|
+
defaultPasswordResetEmailBody,
|
|
143
|
+
defaultVerificationEmailSubject,
|
|
144
|
+
defaultVerificationEmailBody,
|
|
145
|
+
defaultLoginField,
|
|
146
|
+
defaultEmailVerificationEnabled,
|
|
147
|
+
defaultRegistrationEnabled,
|
|
148
|
+
defaultBlockLoginUntilVerified,
|
|
149
|
+
defaultAutoLoginAfterSignup,
|
|
150
|
+
defaultDefaultRole,
|
|
151
|
+
reservedUsernamesPhp,
|
|
152
|
+
) {
|
|
153
|
+
let queryEndpointsPhp = '';
|
|
154
|
+
if (queries && queries.length > 0) {
|
|
155
|
+
queryEndpointsPhp += `\n\n/**\n * ── Compiled REST Query Endpoints (Milestone 2) ──\n */\n`;
|
|
156
|
+
queryEndpointsPhp += `
|
|
157
|
+
if (!function_exists('forgewp_format_rest_post')) {
|
|
158
|
+
function forgewp_format_rest_post($post) {
|
|
159
|
+
$id = $post->ID;
|
|
160
|
+
$title = get_the_title($post);
|
|
161
|
+
$excerpt = get_the_excerpt($post);
|
|
162
|
+
|
|
163
|
+
$content = apply_filters('the_content', $post->post_content);
|
|
164
|
+
$date = get_the_date('', $post);
|
|
165
|
+
$author = get_the_author_meta('display_name', $post->post_author);
|
|
166
|
+
|
|
167
|
+
$featured_image = 'https://picsum.photos/seed/forgewp/1200/630';
|
|
168
|
+
if (has_post_thumbnail($post)) {
|
|
169
|
+
$thumbnail_url = get_the_post_thumbnail_url($post, 'full');
|
|
170
|
+
if ($thumbnail_url) {
|
|
171
|
+
$featured_image = $thumbnail_url;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
$permalink = get_permalink($post);
|
|
176
|
+
|
|
177
|
+
$custom_fields = array();
|
|
178
|
+
$meta = get_post_meta($id);
|
|
179
|
+
if (is_array($meta)) {
|
|
180
|
+
foreach ($meta as $key => $values) {
|
|
181
|
+
$val = isset($values[0]) ? maybe_unserialize($values[0]) : '';
|
|
182
|
+
$custom_fields[$key] = $val;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (function_exists('get_fields')) {
|
|
187
|
+
$acf_fields = get_fields($id);
|
|
188
|
+
if (is_array($acf_fields)) {
|
|
189
|
+
$custom_fields = array_merge($custom_fields, $acf_fields);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
$terms_data = array();
|
|
194
|
+
$taxonomies = get_object_taxonomies($post->post_type);
|
|
195
|
+
if (is_array($taxonomies)) {
|
|
196
|
+
foreach ($taxonomies as $taxonomy) {
|
|
197
|
+
$terms = get_the_terms($post, $taxonomy);
|
|
198
|
+
if (is_array($terms)) {
|
|
199
|
+
$terms_data[$taxonomy] = array();
|
|
200
|
+
foreach ($terms as $t) {
|
|
201
|
+
$terms_data[$taxonomy][] = array(
|
|
202
|
+
'id' => $t->term_id,
|
|
203
|
+
'slug' => $t->slug,
|
|
204
|
+
'name' => html_entity_decode($t->name, ENT_QUOTES, 'UTF-8'),
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return array(
|
|
212
|
+
'ID' => $id,
|
|
213
|
+
'title' => $title,
|
|
214
|
+
'excerpt' => $excerpt,
|
|
215
|
+
'content' => $content,
|
|
216
|
+
'date' => $date,
|
|
217
|
+
'author' => $author,
|
|
218
|
+
'featuredImage' => $featured_image,
|
|
219
|
+
'permalink' => $permalink,
|
|
220
|
+
'customFields' => $custom_fields,
|
|
221
|
+
'_terms' => $terms_data,
|
|
222
|
+
'post_type' => $post->post_type,
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
`;
|
|
227
|
+
|
|
228
|
+
queryEndpointsPhp += `
|
|
229
|
+
add_action('rest_api_init', function() {`;
|
|
230
|
+
for (const q of queries) {
|
|
231
|
+
const cleanId = q.queryId
|
|
232
|
+
.toLowerCase()
|
|
233
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
234
|
+
.replace(/(^-|-$)/g, '');
|
|
235
|
+
const querySlug = 'query-' + cleanId;
|
|
236
|
+
const callbackName = 'forgewp_rest_query_' + cleanId.replace(/-/g, '_');
|
|
237
|
+
queryEndpointsPhp += `
|
|
238
|
+
register_rest_route('forgewp/v1', '/${querySlug}', array(
|
|
239
|
+
'methods' => 'GET',
|
|
240
|
+
'callback' => '${callbackName}',
|
|
241
|
+
'permission_callback' => '__return_true',
|
|
242
|
+
));`;
|
|
243
|
+
}
|
|
244
|
+
queryEndpointsPhp += `
|
|
245
|
+
});
|
|
246
|
+
`;
|
|
247
|
+
|
|
248
|
+
for (const q of queries) {
|
|
249
|
+
const cleanId = q.queryId
|
|
250
|
+
.toLowerCase()
|
|
251
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
252
|
+
.replace(/(^-|-$)/g, '');
|
|
253
|
+
const callbackName = 'forgewp_rest_query_' + cleanId.replace(/-/g, '_');
|
|
254
|
+
const phpArgs = generatePhpArgs(q);
|
|
255
|
+
|
|
256
|
+
queryEndpointsPhp += `
|
|
257
|
+
function ${callbackName}(WP_REST_Request $request) {
|
|
258
|
+
$paged = $request->get_param('page') ? intval($request->get_param('page')) : 1;
|
|
259
|
+
$s = $request->get_param('search');
|
|
260
|
+
if (empty($s)) {
|
|
261
|
+
$s = $request->get_param('s');
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
${phpArgs}
|
|
265
|
+
|
|
266
|
+
if (!empty($s)) {
|
|
267
|
+
$args['s'] = sanitize_text_field($s);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
$lang = $request->get_param('lang');
|
|
271
|
+
if (!empty($lang)) {
|
|
272
|
+
$args['lang'] = sanitize_text_field($lang);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
$query = new WP_Query($args);
|
|
276
|
+
$posts = array();
|
|
277
|
+
if ($query->have_posts()) {
|
|
278
|
+
while ($query->have_posts()) {
|
|
279
|
+
$query->the_post();
|
|
280
|
+
$posts[] = forgewp_format_rest_post($query->post);
|
|
281
|
+
}
|
|
282
|
+
wp_reset_postdata();
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return new WP_REST_Response(array(
|
|
286
|
+
'posts' => $posts,
|
|
287
|
+
'total' => intval($query->found_posts),
|
|
288
|
+
'totalPages' => intval($query->max_num_pages),
|
|
289
|
+
), 200);
|
|
290
|
+
}
|
|
291
|
+
`;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
let authControllersPhp = '';
|
|
296
|
+
if (hasAuth) {
|
|
297
|
+
authControllersPhp = `
|
|
298
|
+
/**
|
|
299
|
+
* ── ForgeWP REST Authentication Controllers ─────────────────────────────────
|
|
300
|
+
*/
|
|
301
|
+
|
|
302
|
+
function forgewp_get_current_user_hydration_payload() {
|
|
303
|
+
if ( ! is_user_logged_in() ) {
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
$user = wp_get_current_user();
|
|
307
|
+
if ( ! $user || $user->ID === 0 ) {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
$capabilities = array();
|
|
311
|
+
if ( is_array( $user->allcaps ) ) {
|
|
312
|
+
foreach ( $user->allcaps as $cap => $value ) {
|
|
313
|
+
if ( $value ) {
|
|
314
|
+
$capabilities[] = $cap;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
$verified_meta = get_user_meta( $user->ID, 'forgewp_email_verified', true );
|
|
320
|
+
$email_verified = ( $verified_meta === '' ) || ( $verified_meta === '1' ) || ( $verified_meta === true );
|
|
321
|
+
|
|
322
|
+
$first_name = $user->first_name ?: get_user_meta( $user->ID, 'first_name', true );
|
|
323
|
+
$last_name = $user->last_name ?: get_user_meta( $user->ID, 'last_name', true );
|
|
324
|
+
|
|
325
|
+
$billing = array(
|
|
326
|
+
'first_name' => get_user_meta( $user->ID, 'billing_first_name', true ) ?: $first_name,
|
|
327
|
+
'last_name' => get_user_meta( $user->ID, 'billing_last_name', true ) ?: $last_name,
|
|
328
|
+
'company' => get_user_meta( $user->ID, 'billing_company', true ),
|
|
329
|
+
'address_1' => get_user_meta( $user->ID, 'billing_address_1', true ),
|
|
330
|
+
'address_2' => get_user_meta( $user->ID, 'billing_address_2', true ),
|
|
331
|
+
'city' => get_user_meta( $user->ID, 'billing_city', true ),
|
|
332
|
+
'state' => get_user_meta( $user->ID, 'billing_state', true ),
|
|
333
|
+
'postcode' => get_user_meta( $user->ID, 'billing_postcode', true ),
|
|
334
|
+
'country' => get_user_meta( $user->ID, 'billing_country', true ) ?: 'US',
|
|
335
|
+
'email' => get_user_meta( $user->ID, 'billing_email', true ) ?: $user->user_email,
|
|
336
|
+
'phone' => get_user_meta( $user->ID, 'billing_phone', true ),
|
|
337
|
+
);
|
|
338
|
+
|
|
339
|
+
$shipping = array(
|
|
340
|
+
'first_name' => get_user_meta( $user->ID, 'shipping_first_name', true ) ?: $first_name,
|
|
341
|
+
'last_name' => get_user_meta( $user->ID, 'shipping_last_name', true ) ?: $last_name,
|
|
342
|
+
'company' => get_user_meta( $user->ID, 'shipping_company', true ),
|
|
343
|
+
'address_1' => get_user_meta( $user->ID, 'shipping_address_1', true ),
|
|
344
|
+
'address_2' => get_user_meta( $user->ID, 'shipping_address_2', true ),
|
|
345
|
+
'city' => get_user_meta( $user->ID, 'shipping_city', true ),
|
|
346
|
+
'state' => get_user_meta( $user->ID, 'shipping_state', true ),
|
|
347
|
+
'postcode' => get_user_meta( $user->ID, 'shipping_postcode', true ),
|
|
348
|
+
'country' => get_user_meta( $user->ID, 'shipping_country', true ) ?: 'US',
|
|
349
|
+
'phone' => get_user_meta( $user->ID, 'shipping_phone', true ) ?: get_user_meta( $user->ID, 'billing_phone', true ),
|
|
350
|
+
);
|
|
351
|
+
|
|
352
|
+
// Collect custom registered user meta
|
|
353
|
+
$all_meta = get_user_meta( $user->ID );
|
|
354
|
+
$custom_meta = array();
|
|
355
|
+
$internal_prefixes = array( '_', 'wp_', 'closedpostboxes', 'metaboxhidden', 'session_tokens', 'community-events' );
|
|
356
|
+
if ( is_array( $all_meta ) ) {
|
|
357
|
+
foreach ( $all_meta as $key => $values ) {
|
|
358
|
+
$is_internal = false;
|
|
359
|
+
foreach ( $internal_prefixes as $pfx ) {
|
|
360
|
+
if ( str_starts_with( $key, $pfx ) ) {
|
|
361
|
+
$is_internal = true;
|
|
362
|
+
break;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
if ( ! $is_internal && ! empty( $values ) ) {
|
|
366
|
+
$val = maybe_unserialize( $values[0] );
|
|
367
|
+
$custom_meta[ $key ] = $val;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return array(
|
|
373
|
+
'id' => $user->ID,
|
|
374
|
+
'username' => $user->user_login,
|
|
375
|
+
'email' => $user->user_email,
|
|
376
|
+
'displayName' => $user->display_name,
|
|
377
|
+
'firstName' => $first_name,
|
|
378
|
+
'lastName' => $last_name,
|
|
379
|
+
'roles' => array_values( $user->roles ),
|
|
380
|
+
'avatarUrl' => get_avatar_url( $user->ID ),
|
|
381
|
+
'capabilities' => $capabilities,
|
|
382
|
+
'emailVerified' => $email_verified,
|
|
383
|
+
'billing' => $billing,
|
|
384
|
+
'shipping' => $shipping,
|
|
385
|
+
'metadata' => $custom_meta,
|
|
386
|
+
'meta' => $custom_meta,
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Register dynamic authentication settings in WP Admin Settings Submenu page.
|
|
392
|
+
*/
|
|
393
|
+
add_action( 'admin_menu', 'forgewp_auth_admin_menu' );
|
|
394
|
+
function forgewp_auth_admin_menu() {
|
|
395
|
+
add_options_page(
|
|
396
|
+
'ForgeWP Auth Settings',
|
|
397
|
+
'ForgeWP Auth',
|
|
398
|
+
'manage_options',
|
|
399
|
+
'forgewp-auth-settings',
|
|
400
|
+
'forgewp_auth_settings_page_render'
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function forgewp_auth_settings_page_render() {
|
|
405
|
+
if ( ! current_user_can( 'manage_options' ) ) {
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
?>
|
|
409
|
+
<div class="wrap">
|
|
410
|
+
<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
|
|
411
|
+
<form action="options.php" method="post">
|
|
412
|
+
<?php
|
|
413
|
+
settings_fields( 'forgewp_auth_settings_group' );
|
|
414
|
+
do_settings_sections( 'forgewp-auth-settings' );
|
|
415
|
+
submit_button( 'Save Settings' );
|
|
416
|
+
?>
|
|
417
|
+
</form>
|
|
418
|
+
</div>
|
|
419
|
+
<?php
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
add_action( 'admin_init', 'forgewp_register_auth_settings' );
|
|
423
|
+
function forgewp_register_auth_settings() {
|
|
424
|
+
register_setting( 'general', 'forgewp_auth_login_field', array(
|
|
425
|
+
'type' => 'string',
|
|
426
|
+
'sanitize_callback' => 'sanitize_text_field',
|
|
427
|
+
'default' => '${defaultLoginField}',
|
|
428
|
+
) );
|
|
429
|
+
|
|
430
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_login_field', array(
|
|
431
|
+
'type' => 'string',
|
|
432
|
+
'sanitize_callback' => 'sanitize_text_field',
|
|
433
|
+
'default' => '${defaultLoginField}',
|
|
434
|
+
) );
|
|
435
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_registration_enabled', array(
|
|
436
|
+
'type' => 'string',
|
|
437
|
+
'sanitize_callback' => 'sanitize_text_field',
|
|
438
|
+
'default' => '${defaultRegistrationEnabled}',
|
|
439
|
+
) );
|
|
440
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_email_verification_enabled', array(
|
|
441
|
+
'type' => 'string',
|
|
442
|
+
'sanitize_callback' => 'sanitize_text_field',
|
|
443
|
+
'default' => '${defaultEmailVerificationEnabled}',
|
|
444
|
+
) );
|
|
445
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_block_login_until_verified', array(
|
|
446
|
+
'type' => 'string',
|
|
447
|
+
'sanitize_callback' => 'sanitize_text_field',
|
|
448
|
+
'default' => '${defaultBlockLoginUntilVerified}',
|
|
449
|
+
) );
|
|
450
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_default_role', array(
|
|
451
|
+
'type' => 'string',
|
|
452
|
+
'sanitize_callback' => 'sanitize_text_field',
|
|
453
|
+
'default' => '${defaultDefaultRole}',
|
|
454
|
+
) );
|
|
455
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_auto_login_after_signup', array(
|
|
456
|
+
'type' => 'string',
|
|
457
|
+
'sanitize_callback' => 'sanitize_text_field',
|
|
458
|
+
'default' => '${defaultAutoLoginAfterSignup}',
|
|
459
|
+
) );
|
|
460
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_verification_email_subject', array(
|
|
461
|
+
'type' => 'string',
|
|
462
|
+
'sanitize_callback' => 'sanitize_text_field',
|
|
463
|
+
'default' => '${defaultVerificationEmailSubject.replace(/'/g, "\\'")}',
|
|
464
|
+
) );
|
|
465
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_verification_email_body', array(
|
|
466
|
+
'type' => 'string',
|
|
467
|
+
'sanitize_callback' => 'sanitize_textarea_field',
|
|
468
|
+
'default' => '${defaultVerificationEmailBody.replace(/\r?\n/g, '\\n').replace(/'/g, "\\'")}',
|
|
469
|
+
) );
|
|
470
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_password_reset_email_subject', array(
|
|
471
|
+
'type' => 'string',
|
|
472
|
+
'sanitize_callback' => 'sanitize_text_field',
|
|
473
|
+
'default' => '${defaultPasswordResetEmailSubject.replace(/'/g, "\\'")}',
|
|
474
|
+
) );
|
|
475
|
+
register_setting( 'forgewp_auth_settings_group', 'forgewp_auth_password_reset_email_body', array(
|
|
476
|
+
'type' => 'string',
|
|
477
|
+
'sanitize_callback' => 'sanitize_textarea_field',
|
|
478
|
+
'default' => '${defaultPasswordResetEmailBody.replace(/\r?\n/g, '\\n').replace(/'/g, "\\'")}',
|
|
479
|
+
) );
|
|
480
|
+
|
|
481
|
+
add_settings_section(
|
|
482
|
+
'forgewp_auth_settings_section',
|
|
483
|
+
'Authentication Configurations',
|
|
484
|
+
null,
|
|
485
|
+
'forgewp-auth-settings'
|
|
486
|
+
);
|
|
487
|
+
|
|
488
|
+
add_settings_field(
|
|
489
|
+
'forgewp_auth_login_field',
|
|
490
|
+
'Allowed Login Field',
|
|
491
|
+
function() {
|
|
492
|
+
$val = get_option('forgewp_auth_login_field', '${defaultLoginField}');
|
|
493
|
+
?>
|
|
494
|
+
<select name="forgewp_auth_login_field">
|
|
495
|
+
<option value="usernameAndEmail" <?php selected($val, 'usernameAndEmail'); ?>>Username or Email</option>
|
|
496
|
+
<option value="emailOnly" <?php selected($val, 'emailOnly'); ?>>Email Only</option>
|
|
497
|
+
<option value="usernameOnly" <?php selected($val, 'usernameOnly'); ?>>Username Only</option>
|
|
498
|
+
</select>
|
|
499
|
+
<p class="description">Select the credential field type allowed during login.</p>
|
|
500
|
+
<?php
|
|
501
|
+
},
|
|
502
|
+
'forgewp-auth-settings',
|
|
503
|
+
'forgewp_auth_settings_section'
|
|
504
|
+
);
|
|
505
|
+
|
|
506
|
+
add_settings_field(
|
|
507
|
+
'forgewp_auth_registration_enabled',
|
|
508
|
+
'Enable Public Registration',
|
|
509
|
+
function() {
|
|
510
|
+
$val = get_option('forgewp_auth_registration_enabled', '${defaultRegistrationEnabled}');
|
|
511
|
+
?>
|
|
512
|
+
<input type="checkbox" name="forgewp_auth_registration_enabled" value="1" <?php checked($val, '1'); ?> />
|
|
513
|
+
<p class="description">Allow visitors to register accounts.</p>
|
|
514
|
+
<?php
|
|
515
|
+
},
|
|
516
|
+
'forgewp-auth-settings',
|
|
517
|
+
'forgewp_auth_settings_section'
|
|
518
|
+
);
|
|
519
|
+
|
|
520
|
+
add_settings_field(
|
|
521
|
+
'forgewp_auth_email_verification_enabled',
|
|
522
|
+
'Require Email Verification',
|
|
523
|
+
function() {
|
|
524
|
+
$val = get_option('forgewp_auth_email_verification_enabled', '${defaultEmailVerificationEnabled}');
|
|
525
|
+
?>
|
|
526
|
+
<input type="checkbox" name="forgewp_auth_email_verification_enabled" value="1" <?php checked($val, '1'); ?> />
|
|
527
|
+
<p class="description">Require verification via email before account activation.</p>
|
|
528
|
+
<?php
|
|
529
|
+
},
|
|
530
|
+
'forgewp-auth-settings',
|
|
531
|
+
'forgewp_auth_settings_section'
|
|
532
|
+
);
|
|
533
|
+
|
|
534
|
+
add_settings_field(
|
|
535
|
+
'forgewp_auth_block_login_until_verified',
|
|
536
|
+
'Block Login Until Verified',
|
|
537
|
+
function() {
|
|
538
|
+
$val = get_option('forgewp_auth_block_login_until_verified', '${defaultBlockLoginUntilVerified}');
|
|
539
|
+
?>
|
|
540
|
+
<input type="checkbox" name="forgewp_auth_block_login_until_verified" value="1" <?php checked($val, '1'); ?> />
|
|
541
|
+
<p class="description">Block logins for unverified accounts.</p>
|
|
542
|
+
<?php
|
|
543
|
+
},
|
|
544
|
+
'forgewp-auth-settings',
|
|
545
|
+
'forgewp_auth_settings_section'
|
|
546
|
+
);
|
|
547
|
+
|
|
548
|
+
add_settings_field(
|
|
549
|
+
'forgewp_auth_default_role',
|
|
550
|
+
'Default User Role',
|
|
551
|
+
function() {
|
|
552
|
+
$val = get_option('forgewp_auth_default_role', '${defaultDefaultRole}');
|
|
553
|
+
$roles = wp_roles()->get_names();
|
|
554
|
+
?>
|
|
555
|
+
<select name="forgewp_auth_default_role">
|
|
556
|
+
<?php foreach ($roles as $role => $name): ?>
|
|
557
|
+
<option value="<?php echo esc_attr($role); ?>" <?php selected($val, $role); ?>><?php echo esc_html($name); ?></option>
|
|
558
|
+
<?php endforeach; ?>
|
|
559
|
+
</select>
|
|
560
|
+
<p class="description">Default role assigned to new registrations.</p>
|
|
561
|
+
<?php
|
|
562
|
+
},
|
|
563
|
+
'forgewp-auth-settings',
|
|
564
|
+
'forgewp_auth_settings_section'
|
|
565
|
+
);
|
|
566
|
+
|
|
567
|
+
add_settings_field(
|
|
568
|
+
'forgewp_auth_auto_login_after_signup',
|
|
569
|
+
'Auto Login After Signup',
|
|
570
|
+
function() {
|
|
571
|
+
$val = get_option('forgewp_auth_auto_login_after_signup', '${defaultAutoLoginAfterSignup}');
|
|
572
|
+
?>
|
|
573
|
+
<input type="checkbox" name="forgewp_auth_auto_login_after_signup" value="1" <?php checked($val, '1'); ?> />
|
|
574
|
+
<p class="description">Automatically log in user after successful registration (bypassed if verification is required).</p>
|
|
575
|
+
<?php
|
|
576
|
+
},
|
|
577
|
+
'forgewp-auth-settings',
|
|
578
|
+
'forgewp_auth_settings_section'
|
|
579
|
+
);
|
|
580
|
+
|
|
581
|
+
add_settings_field(
|
|
582
|
+
'forgewp_auth_verification_email_subject',
|
|
583
|
+
'Verification Email Subject',
|
|
584
|
+
function() {
|
|
585
|
+
$val = get_option('forgewp_auth_verification_email_subject', '${defaultVerificationEmailSubject.replace(/'/g, "\\'")}');
|
|
586
|
+
?>
|
|
587
|
+
<input type="text" name="forgewp_auth_verification_email_subject" value="<?php echo esc_attr($val); ?>" class="regular-text" />
|
|
588
|
+
<?php
|
|
589
|
+
},
|
|
590
|
+
'forgewp-auth-settings',
|
|
591
|
+
'forgewp_auth_settings_section'
|
|
592
|
+
);
|
|
593
|
+
|
|
594
|
+
add_settings_field(
|
|
595
|
+
'forgewp_auth_verification_email_body',
|
|
596
|
+
'Verification Email Body',
|
|
597
|
+
function() {
|
|
598
|
+
$val = get_option('forgewp_auth_verification_email_body', '${defaultVerificationEmailBody.replace(/\r?\n/g, '\\n').replace(/'/g, "\\'")}');
|
|
599
|
+
?>
|
|
600
|
+
<textarea name="forgewp_auth_verification_email_body" rows="6" cols="50" class="large-text"><?php echo esc_textarea($val); ?></textarea>
|
|
601
|
+
<p class="description">Tags allowed: {username}, {email}, {verification_url}</p>
|
|
602
|
+
<?php
|
|
603
|
+
},
|
|
604
|
+
'forgewp-auth-settings',
|
|
605
|
+
'forgewp_auth_settings_section'
|
|
606
|
+
);
|
|
607
|
+
|
|
608
|
+
add_settings_field(
|
|
609
|
+
'forgewp_auth_password_reset_email_subject',
|
|
610
|
+
'Password Reset Email Subject',
|
|
611
|
+
function() {
|
|
612
|
+
$val = get_option('forgewp_auth_password_reset_email_subject', '${defaultPasswordResetEmailSubject.replace(/'/g, "\\'")}');
|
|
613
|
+
?>
|
|
614
|
+
<input type="text" name="forgewp_auth_password_reset_email_subject" value="<?php echo esc_attr($val); ?>" class="regular-text" />
|
|
615
|
+
<?php
|
|
616
|
+
},
|
|
617
|
+
'forgewp-auth-settings',
|
|
618
|
+
'forgewp_auth_settings_section'
|
|
619
|
+
);
|
|
620
|
+
|
|
621
|
+
add_settings_field(
|
|
622
|
+
'forgewp_auth_password_reset_email_body',
|
|
623
|
+
'Password Reset Email Body',
|
|
624
|
+
function() {
|
|
625
|
+
$val = get_option('forgewp_auth_password_reset_email_body', '${defaultPasswordResetEmailBody.replace(/\r?\n/g, '\\n').replace(/'/g, "\\'")}');
|
|
626
|
+
?>
|
|
627
|
+
<textarea name="forgewp_auth_password_reset_email_body" rows="6" cols="50" class="large-text"><?php echo esc_textarea($val); ?></textarea>
|
|
628
|
+
<p class="description">Tags allowed: {username}, {reset_url}</p>
|
|
629
|
+
<?php
|
|
630
|
+
},
|
|
631
|
+
'forgewp-auth-settings',
|
|
632
|
+
'forgewp_auth_settings_section'
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* Register custom authentication REST routes.
|
|
638
|
+
*/
|
|
639
|
+
add_action( 'rest_api_init', 'forgewp_auth_register_rest_routes' );
|
|
640
|
+
function forgewp_auth_register_rest_routes() {
|
|
641
|
+
register_rest_route( 'forgewp/v1', '/auth/login', array(
|
|
642
|
+
'methods' => 'POST',
|
|
643
|
+
'callback' => 'forgewp_rest_login',
|
|
644
|
+
'permission_callback' => '__return_true',
|
|
645
|
+
) );
|
|
646
|
+
register_rest_route( 'forgewp/v1', '/auth/signup', array(
|
|
647
|
+
'methods' => 'POST',
|
|
648
|
+
'callback' => 'forgewp_rest_signup',
|
|
649
|
+
'permission_callback' => '__return_true',
|
|
650
|
+
) );
|
|
651
|
+
register_rest_route( 'forgewp/v1', '/auth/register', array(
|
|
652
|
+
'methods' => 'POST',
|
|
653
|
+
'callback' => 'forgewp_rest_signup',
|
|
654
|
+
'permission_callback' => '__return_true',
|
|
655
|
+
) );
|
|
656
|
+
register_rest_route( 'forgewp/v1', '/auth/logout', array(
|
|
657
|
+
'methods' => 'POST',
|
|
658
|
+
'callback' => 'forgewp_rest_logout',
|
|
659
|
+
'permission_callback' => '__return_true',
|
|
660
|
+
) );
|
|
661
|
+
register_rest_route( 'forgewp/v1', '/auth/me', array(
|
|
662
|
+
'methods' => 'GET',
|
|
663
|
+
'callback' => 'forgewp_rest_me',
|
|
664
|
+
'permission_callback' => '__return_true',
|
|
665
|
+
) );
|
|
666
|
+
register_rest_route( 'forgewp/v1', '/auth/config', array(
|
|
667
|
+
'methods' => 'GET',
|
|
668
|
+
'callback' => 'forgewp_rest_auth_config',
|
|
669
|
+
'permission_callback' => '__return_true',
|
|
670
|
+
) );
|
|
671
|
+
register_rest_route( 'forgewp/v1', '/auth/verify-email', array(
|
|
672
|
+
'methods' => 'POST',
|
|
673
|
+
'callback' => 'forgewp_rest_verify_email',
|
|
674
|
+
'permission_callback' => '__return_true',
|
|
675
|
+
) );
|
|
676
|
+
register_rest_route( 'forgewp/v1', '/auth/resend-verification', array(
|
|
677
|
+
'methods' => 'POST',
|
|
678
|
+
'callback' => 'forgewp_rest_resend_verification',
|
|
679
|
+
'permission_callback' => '__return_true',
|
|
680
|
+
) );
|
|
681
|
+
register_rest_route( 'forgewp/v1', '/auth/lost-password', array(
|
|
682
|
+
'methods' => 'POST',
|
|
683
|
+
'callback' => 'forgewp_rest_lost_password',
|
|
684
|
+
'permission_callback' => '__return_true',
|
|
685
|
+
) );
|
|
686
|
+
register_rest_route( 'forgewp/v1', '/auth/reset-password', array(
|
|
687
|
+
'methods' => 'POST',
|
|
688
|
+
'callback' => 'forgewp_rest_reset_password',
|
|
689
|
+
'permission_callback' => '__return_true',
|
|
690
|
+
) );
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function forgewp_rest_auth_config() {
|
|
694
|
+
$login_field = get_option( 'forgewp_auth_login_field', '${defaultLoginField}' );
|
|
695
|
+
$verification_enabled = get_option( 'forgewp_auth_email_verification_enabled', '${defaultEmailVerificationEnabled}' ) === '1';
|
|
696
|
+
return rest_ensure_response( array(
|
|
697
|
+
'loginField' => $login_field,
|
|
698
|
+
'emailVerificationEnabled' => $verification_enabled,
|
|
699
|
+
) );
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function forgewp_get_frontend_origin() {
|
|
703
|
+
$origin = home_url();
|
|
704
|
+
if ( defined( 'FORGEWP_FRONTEND_ORIGIN' ) ) {
|
|
705
|
+
$origin = FORGEWP_FRONTEND_ORIGIN;
|
|
706
|
+
}
|
|
707
|
+
return rtrim( $origin, '/' );
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function forgewp_rest_login( $request ) {
|
|
711
|
+
$params = $request->get_json_params();
|
|
712
|
+
$login_field = get_option( 'forgewp_auth_login_field', '${defaultLoginField}' );
|
|
713
|
+
|
|
714
|
+
$username = '';
|
|
715
|
+
$email = '';
|
|
716
|
+
$credential = '';
|
|
717
|
+
if ( isset( $params['credential'] ) && ! empty( trim( $params['credential'] ) ) ) {
|
|
718
|
+
$credential = sanitize_text_field( $params['credential'] );
|
|
719
|
+
} elseif ( isset( $params['username'] ) && ! empty( trim( $params['username'] ) ) ) {
|
|
720
|
+
$credential = sanitize_text_field( $params['username'] );
|
|
721
|
+
} elseif ( isset( $params['email'] ) && ! empty( trim( $params['email'] ) ) ) {
|
|
722
|
+
$credential = sanitize_text_field( $params['email'] );
|
|
723
|
+
} elseif ( isset( $params['user'] ) && ! empty( trim( $params['user'] ) ) ) {
|
|
724
|
+
$credential = sanitize_text_field( $params['user'] );
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
$password = isset( $params['password'] ) ? $params['password'] : ( isset( $params['user_password'] ) ? $params['user_password'] : '' );
|
|
728
|
+
|
|
729
|
+
if ( empty( $credential ) || empty( $password ) ) {
|
|
730
|
+
return new WP_Error( 'rest_missing_fields', 'Credential and password are required.', array( 'status' => 400 ) );
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
if ( $login_field === 'emailOnly' ) {
|
|
734
|
+
$user = get_user_by( 'email', $credential );
|
|
735
|
+
if ( ! $user ) {
|
|
736
|
+
return new WP_Error( 'rest_invalid_credentials', 'Invalid email or password.', array( 'status' => 403 ) );
|
|
737
|
+
}
|
|
738
|
+
$username = $user->user_login;
|
|
739
|
+
} elseif ( $login_field === 'usernameOnly' ) {
|
|
740
|
+
$username = $credential;
|
|
741
|
+
} else {
|
|
742
|
+
// usernameAndEmail
|
|
743
|
+
if ( is_email( $credential ) ) {
|
|
744
|
+
$user = get_user_by( 'email', $credential );
|
|
745
|
+
if ( $user ) {
|
|
746
|
+
$username = $user->user_login;
|
|
747
|
+
} else {
|
|
748
|
+
return new WP_Error( 'rest_invalid_credentials', 'Invalid credentials.', array( 'status' => 403 ) );
|
|
749
|
+
}
|
|
750
|
+
} else {
|
|
751
|
+
$username = $credential;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
$creds = array(
|
|
756
|
+
'user_login' => $username,
|
|
757
|
+
'user_password' => $password,
|
|
758
|
+
'remember' => true,
|
|
759
|
+
);
|
|
760
|
+
|
|
761
|
+
$user = wp_signon( $creds, is_ssl() );
|
|
762
|
+
|
|
763
|
+
if ( is_wp_error( $user ) ) {
|
|
764
|
+
return new WP_Error( 'rest_login_failed', $user->get_error_message(), array( 'status' => 403 ) );
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// Check email verification if enabled
|
|
768
|
+
$verification_enabled = get_option( 'forgewp_auth_email_verification_enabled', '${defaultEmailVerificationEnabled}' ) === '1';
|
|
769
|
+
$block_login = get_option( 'forgewp_auth_block_login_until_verified', '${defaultBlockLoginUntilVerified}' ) === '1';
|
|
770
|
+
|
|
771
|
+
if ( $verification_enabled && $block_login ) {
|
|
772
|
+
$verified_meta = get_user_meta( $user->ID, 'forgewp_email_verified', true );
|
|
773
|
+
$email_verified = ( $verified_meta === '1' ) || ( $verified_meta === true );
|
|
774
|
+
if ( ! $email_verified ) {
|
|
775
|
+
wp_logout();
|
|
776
|
+
return new WP_Error( 'rest_unverified_email', 'Please verify your email address before logging in.', array( 'status' => 403 ) );
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
wp_set_current_user( $user->ID );
|
|
781
|
+
|
|
782
|
+
$user_payload = forgewp_get_current_user_hydration_payload();
|
|
783
|
+
$response = array(
|
|
784
|
+
'success' => true,
|
|
785
|
+
'user' => $user_payload,
|
|
786
|
+
);
|
|
787
|
+
if ( is_array( $user_payload ) ) {
|
|
788
|
+
$response = array_merge( $user_payload, $response );
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
return rest_ensure_response( $response );
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function forgewp_rest_signup( $request ) {
|
|
795
|
+
$registration_enabled = get_option( 'forgewp_auth_registration_enabled', '${defaultRegistrationEnabled}' ) === '1';
|
|
796
|
+
if ( ! $registration_enabled ) {
|
|
797
|
+
return new WP_Error( 'rest_registration_disabled', 'Registration is currently disabled.', array( 'status' => 403 ) );
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
$params = $request->get_json_params();
|
|
801
|
+
$email = isset( $params['email'] ) ? sanitize_email( $params['email'] ) : '';
|
|
802
|
+
$username = isset( $params['username'] ) ? sanitize_user( $params['username'] ) : '';
|
|
803
|
+
$password = isset( $params['password'] ) ? $params['password'] : '';
|
|
804
|
+
$displayName = isset( $params['displayName'] ) ? sanitize_text_field( $params['displayName'] ) : '';
|
|
805
|
+
|
|
806
|
+
if ( empty( $email ) || empty( $password ) ) {
|
|
807
|
+
return new WP_Error( 'rest_missing_fields', 'Email and password are required.', array( 'status' => 400 ) );
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
$login_field = get_option( 'forgewp_auth_login_field', '${defaultLoginField}' );
|
|
811
|
+
if ( $login_field === 'emailOnly' ) {
|
|
812
|
+
// Auto-generate username from email
|
|
813
|
+
$username = sanitize_user( current( explode( '@', $email ) ) );
|
|
814
|
+
$base_username = $username;
|
|
815
|
+
$i = 1;
|
|
816
|
+
while ( username_exists( $username ) ) {
|
|
817
|
+
$username = $base_username . $i;
|
|
818
|
+
$i++;
|
|
819
|
+
}
|
|
820
|
+
} else {
|
|
821
|
+
if ( empty( $username ) ) {
|
|
822
|
+
return new WP_Error( 'rest_missing_fields', 'Username is required.', array( 'status' => 400 ) );
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// Reserved usernames validation
|
|
827
|
+
$reserved = array(${reservedUsernamesPhp});
|
|
828
|
+
if ( in_array( strtolower( $username ), $reserved, true ) ) {
|
|
829
|
+
return new WP_Error( 'rest_reserved_username', 'This username is reserved.', array( 'status' => 400 ) );
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
if ( username_exists( $username ) ) {
|
|
833
|
+
return new WP_Error( 'rest_username_exists', 'Username already exists.', array( 'status' => 400 ) );
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
if ( email_exists( $email ) ) {
|
|
837
|
+
return new WP_Error( 'rest_email_exists', 'Email already exists.', array( 'status' => 400 ) );
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
$default_role = get_option( 'forgewp_auth_default_role', '${defaultDefaultRole}' );
|
|
841
|
+
|
|
842
|
+
$allowed_metadata = array(${registrationMetaFields(config.auth).map((key) => `'${key}'`).join(', ')});
|
|
843
|
+
$metadata = isset( $params['metadata'] ) ? $params['metadata'] : array();
|
|
844
|
+
if ( ! is_array( $metadata ) ) {
|
|
845
|
+
return new WP_Error( 'rest_invalid_metadata', 'Registration metadata must be an object.', array( 'status' => 400 ) );
|
|
846
|
+
}
|
|
847
|
+
foreach ( $metadata as $meta_key => $meta_val ) {
|
|
848
|
+
if ( ! in_array( $meta_key, $allowed_metadata, true ) || ! is_scalar( $meta_val ) ) {
|
|
849
|
+
return new WP_Error( 'rest_invalid_metadata', 'Registration metadata contains an unsupported field or value.', array( 'status' => 400 ) );
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
$user_id = wp_create_user( $username, $password, $email );
|
|
854
|
+
|
|
855
|
+
if ( is_wp_error( $user_id ) ) {
|
|
856
|
+
return new WP_Error( 'rest_signup_failed', $user_id->get_error_message(), array( 'status' => 500 ) );
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
$user = get_user_by( 'id', $user_id );
|
|
860
|
+
$user->set_role( $default_role );
|
|
861
|
+
|
|
862
|
+
if ( ! empty( $displayName ) ) {
|
|
863
|
+
wp_update_user( array( 'ID' => $user_id, 'display_name' => $displayName ) );
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
if ( ! empty( $metadata ) ) {
|
|
867
|
+
foreach ( $metadata as $meta_key => $meta_val ) {
|
|
868
|
+
$clean_key = sanitize_key( $meta_key );
|
|
869
|
+
$clean_val = is_scalar( $meta_val ) ? sanitize_text_field( $meta_val ) : $meta_val;
|
|
870
|
+
update_user_meta( $user_id, $clean_key, $clean_val );
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// Check verification status
|
|
875
|
+
$verification_enabled = get_option( 'forgewp_auth_email_verification_enabled', '${defaultEmailVerificationEnabled}' ) === '1';
|
|
876
|
+
$verification_email_sent = null;
|
|
877
|
+
if ( $verification_enabled ) {
|
|
878
|
+
update_user_meta( $user_id, 'forgewp_email_verified', '0' );
|
|
879
|
+
// Send email verification
|
|
880
|
+
$verification_email_sent = forgewp_send_email_verification( $user );
|
|
881
|
+
} else {
|
|
882
|
+
update_user_meta( $user_id, 'forgewp_email_verified', '1' );
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
$auto_login = get_option( 'forgewp_auth_auto_login_after_signup', '${defaultAutoLoginAfterSignup}' ) === '1';
|
|
886
|
+
|
|
887
|
+
if ( $auto_login && ! $verification_enabled ) {
|
|
888
|
+
$creds = array(
|
|
889
|
+
'user_login' => $username,
|
|
890
|
+
'user_password' => $password,
|
|
891
|
+
'remember' => true,
|
|
892
|
+
);
|
|
893
|
+
$signed_in = wp_signon( $creds, is_ssl() );
|
|
894
|
+
if ( is_wp_error( $signed_in ) ) {
|
|
895
|
+
return rest_ensure_response( array(
|
|
896
|
+
'success' => true,
|
|
897
|
+
'requiresVerification' => false,
|
|
898
|
+
'message' => 'Registration successful. Please sign in.',
|
|
899
|
+
) );
|
|
900
|
+
}
|
|
901
|
+
wp_set_current_user( $user_id );
|
|
902
|
+
$user_payload = forgewp_get_current_user_hydration_payload();
|
|
903
|
+
$response = array(
|
|
904
|
+
'success' => true,
|
|
905
|
+
'user' => $user_payload,
|
|
906
|
+
);
|
|
907
|
+
if ( is_array( $user_payload ) ) {
|
|
908
|
+
$response = array_merge( $user_payload, $response );
|
|
909
|
+
}
|
|
910
|
+
return rest_ensure_response( $response );
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
return rest_ensure_response( array(
|
|
914
|
+
'success' => true,
|
|
915
|
+
'requiresVerification' => $verification_enabled,
|
|
916
|
+
'verificationEmailSent' => $verification_email_sent,
|
|
917
|
+
'message' => $verification_enabled
|
|
918
|
+
? ( $verification_email_sent ? 'Registration successful. Please verify your email.' : 'Your account was created, but the verification email could not be sent. Please request another verification email.' )
|
|
919
|
+
: 'Registration successful. Please sign in.',
|
|
920
|
+
) );
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function forgewp_rest_logout() {
|
|
924
|
+
wp_logout();
|
|
925
|
+
return rest_ensure_response( array( 'success' => true ) );
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
function forgewp_rest_me() {
|
|
929
|
+
$payload = forgewp_get_current_user_hydration_payload();
|
|
930
|
+
return rest_ensure_response( array( 'user' => $payload ) );
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
function forgewp_rest_verify_email( $request ) {
|
|
934
|
+
$params = $request->get_json_params();
|
|
935
|
+
$user_id = isset( $params['userId'] ) ? intval( $params['userId'] ) : 0;
|
|
936
|
+
$token = isset( $params['token'] ) ? sanitize_text_field( $params['token'] ) : '';
|
|
937
|
+
|
|
938
|
+
if ( $user_id <= 0 || empty( $token ) ) {
|
|
939
|
+
return new WP_Error( 'rest_missing_fields', 'User ID and token are required.', array( 'status' => 400 ) );
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
$saved_id = get_transient( 'forgewp_verify_email_' . $token );
|
|
943
|
+
if ( $saved_id === false || intval( $saved_id ) !== $user_id || ! get_user_by( 'id', $user_id ) ) {
|
|
944
|
+
return new WP_Error( 'rest_invalid_token', 'Invalid or expired verification token.', array( 'status' => 400 ) );
|
|
945
|
+
}
|
|
946
|
+
delete_transient( 'forgewp_verify_email_' . $token );
|
|
947
|
+
delete_transient( 'forgewp_verify_email_user_' . $user_id );
|
|
948
|
+
update_user_meta( $user_id, 'forgewp_email_verified', '1' );
|
|
949
|
+
|
|
950
|
+
wp_set_current_user( $user_id );
|
|
951
|
+
wp_set_auth_cookie( $user_id, true, is_ssl() );
|
|
952
|
+
$user_payload = forgewp_get_current_user_hydration_payload();
|
|
953
|
+
$response = array(
|
|
954
|
+
'success' => true,
|
|
955
|
+
'user' => $user_payload,
|
|
956
|
+
);
|
|
957
|
+
if ( is_array( $user_payload ) ) {
|
|
958
|
+
$response = array_merge( $user_payload, $response );
|
|
959
|
+
}
|
|
960
|
+
return rest_ensure_response( $response );
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
function forgewp_rest_resend_verification( $request ) {
|
|
964
|
+
$params = $request->get_json_params();
|
|
965
|
+
$input = isset( $params['email'] ) ? sanitize_text_field( $params['email'] ) : '';
|
|
966
|
+
if ( empty( $input ) && isset( $params['username'] ) ) {
|
|
967
|
+
$input = sanitize_text_field( $params['username'] );
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
if ( empty( $input ) ) {
|
|
971
|
+
return new WP_Error( 'rest_missing_fields', 'Email or username is required.', array( 'status' => 400 ) );
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
$user = null;
|
|
975
|
+
if ( is_email( $input ) ) {
|
|
976
|
+
$user = get_user_by( 'email', $input );
|
|
977
|
+
}
|
|
978
|
+
if ( ! $user ) {
|
|
979
|
+
$user = get_user_by( 'login', $input );
|
|
980
|
+
}
|
|
981
|
+
if ( ! $user ) {
|
|
982
|
+
return new WP_Error( 'rest_invalid_email', 'User not found.', array( 'status' => 404 ) );
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
$verified_meta = get_user_meta( $user->ID, 'forgewp_email_verified', true );
|
|
986
|
+
if ( $verified_meta === '1' || $verified_meta === true ) {
|
|
987
|
+
return new WP_Error( 'rest_already_verified', 'Email is already verified.', array( 'status' => 400 ) );
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
if ( ! forgewp_send_email_verification( $user ) ) {
|
|
991
|
+
return new WP_Error( 'rest_verification_mail_failed', 'The verification email could not be sent. Please try again.', array( 'status' => 502 ) );
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
return rest_ensure_response( array( 'success' => true ) );
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
function forgewp_send_email_verification( $user ) {
|
|
998
|
+
$email = $user->user_email;
|
|
999
|
+
if ( empty( $email ) ) {
|
|
1000
|
+
return false;
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
$token = wp_generate_password( 32, false );
|
|
1004
|
+
|
|
1005
|
+
$origin = forgewp_get_frontend_origin();
|
|
1006
|
+
$verification_url = $origin . '/verify-email?userId=' . $user->ID . '&token=' . $token;
|
|
1007
|
+
|
|
1008
|
+
$subject = get_option( 'forgewp_auth_verification_email_subject', '${defaultVerificationEmailSubject.replace(/'/g, "\\'")}' );
|
|
1009
|
+
$body = get_option( 'forgewp_auth_verification_email_body', '${defaultVerificationEmailBody.replace(/\r?\n/g, '\\n').replace(/'/g, "\\'")}' );
|
|
1010
|
+
|
|
1011
|
+
$body = str_replace(
|
|
1012
|
+
array( '{username}', '{email}', '{verification_url}' ),
|
|
1013
|
+
array( $user->user_login, $email, $verification_url ),
|
|
1014
|
+
$body
|
|
1015
|
+
);
|
|
1016
|
+
|
|
1017
|
+
$from_name = get_bloginfo( 'name' );
|
|
1018
|
+
$admin_email = get_option( 'admin_email' );
|
|
1019
|
+
if ( empty( $admin_email ) || ! is_email( $admin_email ) ) {
|
|
1020
|
+
$admin_email = 'no-reply@' . ( isset( $_SERVER['HTTP_HOST'] ) ? preg_replace( '/:\d+$/', '', $_SERVER['HTTP_HOST'] ) : 'localhost' );
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
$headers = array(
|
|
1024
|
+
'Content-Type: text/plain; charset=UTF-8',
|
|
1025
|
+
'From: ' . $from_name . ' <' . $admin_email . '>',
|
|
1026
|
+
);
|
|
1027
|
+
|
|
1028
|
+
$sent = wp_mail( $email, $subject, $body, $headers );
|
|
1029
|
+
if ( ! $sent ) {
|
|
1030
|
+
error_log( '[ForgeWP Auth] wp_mail failed to send verification email to ' . $email );
|
|
1031
|
+
return false;
|
|
1032
|
+
}
|
|
1033
|
+
$prev_token = get_transient( 'forgewp_verify_email_user_' . $user->ID );
|
|
1034
|
+
if ( is_string( $prev_token ) && ! empty( $prev_token ) && $prev_token !== $token ) {
|
|
1035
|
+
delete_transient( 'forgewp_verify_email_' . $prev_token );
|
|
1036
|
+
}
|
|
1037
|
+
set_transient( 'forgewp_verify_email_' . $token, $user->ID, DAY_IN_SECONDS );
|
|
1038
|
+
set_transient( 'forgewp_verify_email_user_' . $user->ID, $token, DAY_IN_SECONDS );
|
|
1039
|
+
return $sent;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
function forgewp_rest_lost_password( $request ) {
|
|
1043
|
+
$params = $request->get_json_params();
|
|
1044
|
+
if ( ! is_array( $params ) ) {
|
|
1045
|
+
return new WP_Error( 'rest_missing_fields', 'Account fields are required.', array( 'status' => 400 ) );
|
|
1046
|
+
}
|
|
1047
|
+
foreach ( array('user_login', 'email', 'username') as $field ) {
|
|
1048
|
+
if ( isset( $params[$field] ) && ! is_string( $params[$field] ) ) {
|
|
1049
|
+
return new WP_Error( 'rest_invalid_fields', 'Account fields must be text values.', array( 'status' => 400 ) );
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
$user_login = isset( $params['user_login'] ) ? sanitize_text_field( $params['user_login'] ) : '';
|
|
1053
|
+
if ( empty( $user_login ) && isset( $params['email'] ) ) {
|
|
1054
|
+
$user_login = sanitize_text_field( $params['email'] );
|
|
1055
|
+
}
|
|
1056
|
+
if ( empty( $user_login ) && isset( $params['username'] ) ) {
|
|
1057
|
+
$user_login = sanitize_text_field( $params['username'] );
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
if ( empty( $user_login ) ) {
|
|
1061
|
+
return new WP_Error( 'rest_missing_fields', 'Email or username is required.', array( 'status' => 400 ) );
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
if ( ! function_exists( 'retrieve_password' ) ) {
|
|
1065
|
+
require_once ABSPATH . 'wp-login.php';
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
$errors = retrieve_password( $user_login );
|
|
1069
|
+
|
|
1070
|
+
if ( is_wp_error( $errors ) ) {
|
|
1071
|
+
return new WP_Error( 'rest_recovery_failed', $errors->get_error_message(), array( 'status' => 400 ) );
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
return rest_ensure_response( array( 'success' => true ) );
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
function forgewp_rest_reset_password( $request ) {
|
|
1078
|
+
$params = $request->get_json_params();
|
|
1079
|
+
if ( ! is_array( $params ) ) {
|
|
1080
|
+
return new WP_Error( 'rest_missing_fields', 'Account fields are required.', array( 'status' => 400 ) );
|
|
1081
|
+
}
|
|
1082
|
+
foreach ( array('login', 'username', 'user_login', 'key', 'password') as $field ) {
|
|
1083
|
+
if ( isset( $params[$field] ) && ! is_string( $params[$field] ) ) {
|
|
1084
|
+
return new WP_Error( 'rest_invalid_fields', 'Account fields must be text values.', array( 'status' => 400 ) );
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
$user_login = isset( $params['login'] ) ? sanitize_text_field( $params['login'] ) : '';
|
|
1088
|
+
if ( empty( $user_login ) && isset( $params['username'] ) ) {
|
|
1089
|
+
$user_login = sanitize_text_field( $params['username'] );
|
|
1090
|
+
}
|
|
1091
|
+
if ( empty( $user_login ) && isset( $params['user_login'] ) ) {
|
|
1092
|
+
$user_login = sanitize_text_field( $params['user_login'] );
|
|
1093
|
+
}
|
|
1094
|
+
$key = isset( $params['key'] ) ? sanitize_text_field( $params['key'] ) : '';
|
|
1095
|
+
$password = isset( $params['password'] ) ? $params['password'] : '';
|
|
1096
|
+
|
|
1097
|
+
if ( empty( $user_login ) || empty( $key ) || empty( $password ) ) {
|
|
1098
|
+
return new WP_Error( 'rest_missing_fields', 'Username, key, and password are required.', array( 'status' => 400 ) );
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
if ( ! function_exists( 'check_password_reset_key' ) ) {
|
|
1102
|
+
require_once ABSPATH . 'wp-login.php';
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
$user = check_password_reset_key( $key, $user_login );
|
|
1106
|
+
|
|
1107
|
+
if ( is_wp_error( $user ) ) {
|
|
1108
|
+
return new WP_Error( 'rest_invalid_key', 'The password reset link is invalid or has expired.', array( 'status' => 400 ) );
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
reset_password( $user, $password );
|
|
1112
|
+
|
|
1113
|
+
return rest_ensure_response( array( 'success' => true ) );
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
/**
|
|
1117
|
+
* Intercept retrieve password mail subject and body to support custom template and headless redirect.
|
|
1118
|
+
*/
|
|
1119
|
+
add_filter( 'retrieve_password_title', 'forgewp_retrieve_password_title', 10, 3 );
|
|
1120
|
+
function forgewp_retrieve_password_title( $title, $user_login, $user_data ) {
|
|
1121
|
+
$custom_subject = get_option( 'forgewp_auth_password_reset_email_subject', '${defaultPasswordResetEmailSubject.replace(/'/g, "\\'")}' );
|
|
1122
|
+
if ( ! empty( $custom_subject ) ) {
|
|
1123
|
+
return $custom_subject;
|
|
1124
|
+
}
|
|
1125
|
+
return $title;
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
add_filter( 'retrieve_password_message', 'forgewp_retrieve_password_message', 10, 4 );
|
|
1129
|
+
function forgewp_retrieve_password_message( $message, $key, $user_login, $user_data ) {
|
|
1130
|
+
$origin = forgewp_get_frontend_origin();
|
|
1131
|
+
$reset_url = $origin . '/reset-password?key=' . $key . '&login=' . rawurlencode( $user_login );
|
|
1132
|
+
|
|
1133
|
+
$custom_body = get_option( 'forgewp_auth_password_reset_email_body', '${defaultPasswordResetEmailBody.replace(/\r?\n/g, '\\n').replace(/'/g, "\\'")}' );
|
|
1134
|
+
if ( ! empty( $custom_body ) ) {
|
|
1135
|
+
$body = str_replace(
|
|
1136
|
+
array( '{username}', '{reset_url}' ),
|
|
1137
|
+
array( $user_login, $reset_url ),
|
|
1138
|
+
$custom_body
|
|
1139
|
+
);
|
|
1140
|
+
return $body;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
$message = "Hello!\\n\\nYou asked us to reset your password for your account: " . $user_login . "\\n\\nIf this was a mistake, just ignore this email.\\n\\nTo reset your password, visit the following link:\\n\\n" . $reset_url . "\\n";
|
|
1144
|
+
return $message;
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
function forgewp_auth_head_hydration() {
|
|
1148
|
+
$payload = forgewp_get_current_user_hydration_payload();
|
|
1149
|
+
$login_field = get_option( 'forgewp_auth_login_field', '${defaultLoginField}' );
|
|
1150
|
+
$verification_enabled = get_option( 'forgewp_auth_email_verification_enabled', '${defaultEmailVerificationEnabled}' ) === '1';
|
|
1151
|
+
|
|
1152
|
+
$session_data = array(
|
|
1153
|
+
'loggedIn' => ! empty( $payload ),
|
|
1154
|
+
'user' => $payload,
|
|
1155
|
+
'loginField' => $login_field,
|
|
1156
|
+
'emailVerificationEnabled' => $verification_enabled,
|
|
1157
|
+
);
|
|
1158
|
+
?>
|
|
1159
|
+
<script type="application/json" id="forgewp-session">
|
|
1160
|
+
<?php echo wp_json_encode($session_data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE); ?>
|
|
1161
|
+
</script>
|
|
1162
|
+
<script id="forgewp-auth-hydration">
|
|
1163
|
+
if (!window.forgeWpHydration) {
|
|
1164
|
+
window.forgeWpHydration = {};
|
|
1165
|
+
}
|
|
1166
|
+
window.forgeWpHydration.currentUser = <?php echo wp_json_encode($payload, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE); ?>;
|
|
1167
|
+
window.forgeWpHydration.loginField = <?php echo wp_json_encode($login_field); ?>;
|
|
1168
|
+
window.forgeWpHydration.emailVerificationEnabled = <?php echo wp_json_encode($verification_enabled); ?>;
|
|
1169
|
+
window.forgeWpHydration.restNonce = <?php echo wp_json_encode(wp_create_nonce('wp_rest')); ?>;
|
|
1170
|
+
</script>
|
|
1171
|
+
<?php
|
|
1172
|
+
}
|
|
1173
|
+
add_action('wp_head', 'forgewp_auth_head_hydration', 1);
|
|
1174
|
+
|
|
1175
|
+
/**
|
|
1176
|
+
* Register Product Review REST routes.
|
|
1177
|
+
*/
|
|
1178
|
+
add_action( 'rest_api_init', 'forgewp_product_reviews_register_rest_routes' );
|
|
1179
|
+
function forgewp_product_reviews_register_rest_routes() {
|
|
1180
|
+
register_rest_route( 'forgewp/v1', '/products/(?P<id>\\d+)/reviews', array(
|
|
1181
|
+
array(
|
|
1182
|
+
'methods' => 'GET',
|
|
1183
|
+
'callback' => 'forgewp_rest_get_product_reviews',
|
|
1184
|
+
'permission_callback' => '__return_true',
|
|
1185
|
+
),
|
|
1186
|
+
array(
|
|
1187
|
+
'methods' => 'POST',
|
|
1188
|
+
'callback' => 'forgewp_rest_submit_product_review',
|
|
1189
|
+
'permission_callback' => '__return_true',
|
|
1190
|
+
),
|
|
1191
|
+
array(
|
|
1192
|
+
'methods' => 'DELETE',
|
|
1193
|
+
'callback' => 'forgewp_rest_delete_product_review',
|
|
1194
|
+
'permission_callback' => '__return_true',
|
|
1195
|
+
),
|
|
1196
|
+
) );
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
function forgewp_rest_get_product_reviews( $request ) {
|
|
1200
|
+
$product_id = intval( $request->get_param( 'id' ) );
|
|
1201
|
+
if ( ! $product_id ) {
|
|
1202
|
+
return new WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 400 ) );
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
$sort = sanitize_text_field( $request->get_param( 'sort' ) ?: 'newest' );
|
|
1206
|
+
$page = max( 1, intval( $request->get_param( 'page' ) ?: 1 ) );
|
|
1207
|
+
$per_page = max( 1, min( 50, intval( $request->get_param( 'per_page' ) ?: 5 ) ) );
|
|
1208
|
+
|
|
1209
|
+
$current_user_id = get_current_user_id();
|
|
1210
|
+
if ( ! $current_user_id && ! empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
|
|
1211
|
+
$cookie_user_id = wp_validate_auth_cookie( $_COOKIE[ LOGGED_IN_COOKIE ], 'logged_in' );
|
|
1212
|
+
if ( $cookie_user_id ) {
|
|
1213
|
+
wp_set_current_user( $cookie_user_id );
|
|
1214
|
+
$current_user_id = $cookie_user_id;
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
$comments = get_comments( array(
|
|
1219
|
+
'post_id' => $product_id,
|
|
1220
|
+
'type' => 'review',
|
|
1221
|
+
'status' => 'approve',
|
|
1222
|
+
'order' => 'DESC',
|
|
1223
|
+
'orderby' => 'comment_date_gmt',
|
|
1224
|
+
) );
|
|
1225
|
+
|
|
1226
|
+
$all_formatted = array();
|
|
1227
|
+
$user_review = null;
|
|
1228
|
+
$total_rating = 0;
|
|
1229
|
+
$rating_breakdown = array( '1' => 0, '2' => 0, '3' => 0, '4' => 0, '5' => 0 );
|
|
1230
|
+
|
|
1231
|
+
foreach ( $comments as $c ) {
|
|
1232
|
+
$rating = get_comment_meta( $c->comment_ID, 'rating', true );
|
|
1233
|
+
$rating = ! empty( $rating ) ? max( 1, min( 5, intval( $rating ) ) ) : 5;
|
|
1234
|
+
$verified = get_comment_meta( $c->comment_ID, 'verified', true );
|
|
1235
|
+
$total_rating += $rating;
|
|
1236
|
+
$rating_breakdown[ strval( $rating ) ]++;
|
|
1237
|
+
|
|
1238
|
+
$is_owner = ( $current_user_id > 0 && intval( $c->user_id ) === $current_user_id );
|
|
1239
|
+
|
|
1240
|
+
$rev_data = array(
|
|
1241
|
+
'id' => intval( $c->comment_ID ),
|
|
1242
|
+
'author' => $c->comment_author ? $c->comment_author : 'Customer',
|
|
1243
|
+
'content' => wp_strip_all_tags( $c->comment_content ),
|
|
1244
|
+
'rating' => $rating,
|
|
1245
|
+
'date' => mysql2date( 'Y-m-d', $c->comment_date ),
|
|
1246
|
+
'verified' => ! empty( $verified ) || ( $c->user_id > 0 ),
|
|
1247
|
+
'isOwner' => $is_owner,
|
|
1248
|
+
);
|
|
1249
|
+
|
|
1250
|
+
if ( $is_owner && ! $user_review ) {
|
|
1251
|
+
$user_review = $rev_data;
|
|
1252
|
+
} else {
|
|
1253
|
+
$all_formatted[] = $rev_data;
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
// Apply sorting to other customer reviews
|
|
1258
|
+
if ( $sort === 'oldest' ) {
|
|
1259
|
+
usort( $all_formatted, function( $a, $b ) {
|
|
1260
|
+
return strcmp( $a['date'], $b['date'] );
|
|
1261
|
+
} );
|
|
1262
|
+
} elseif ( $sort === 'highest' ) {
|
|
1263
|
+
usort( $all_formatted, function( $a, $b ) {
|
|
1264
|
+
if ( $a['rating'] === $b['rating'] ) {
|
|
1265
|
+
return strcmp( $b['date'], $a['date'] );
|
|
1266
|
+
}
|
|
1267
|
+
return $b['rating'] - $a['rating'];
|
|
1268
|
+
} );
|
|
1269
|
+
} elseif ( $sort === 'lowest' ) {
|
|
1270
|
+
usort( $all_formatted, function( $a, $b ) {
|
|
1271
|
+
if ( $a['rating'] === $b['rating'] ) {
|
|
1272
|
+
return strcmp( $b['date'], $a['date'] );
|
|
1273
|
+
}
|
|
1274
|
+
return $a['rating'] - $b['rating'];
|
|
1275
|
+
} );
|
|
1276
|
+
} else {
|
|
1277
|
+
// 'newest' default
|
|
1278
|
+
usort( $all_formatted, function( $a, $b ) {
|
|
1279
|
+
return strcmp( $b['date'], $a['date'] );
|
|
1280
|
+
} );
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
$total_other = count( $all_formatted );
|
|
1284
|
+
$total_pages = max( 1, intval( ceil( $total_other / $per_page ) ) );
|
|
1285
|
+
$offset = ( $page - 1 ) * $per_page;
|
|
1286
|
+
$paginated_reviews = array_slice( $all_formatted, $offset, $per_page );
|
|
1287
|
+
|
|
1288
|
+
$grand_total = count( $comments );
|
|
1289
|
+
$avg_rating = $grand_total > 0 ? round( $total_rating / $grand_total, 2 ) : 0;
|
|
1290
|
+
|
|
1291
|
+
return rest_ensure_response( array(
|
|
1292
|
+
'reviews' => $paginated_reviews,
|
|
1293
|
+
'userReview' => $user_review,
|
|
1294
|
+
'ratingBreakdown' => $rating_breakdown,
|
|
1295
|
+
'ratingCount' => $grand_total,
|
|
1296
|
+
'averageRating' => number_format( $avg_rating, 2, '.', '' ),
|
|
1297
|
+
'currentPage' => $page,
|
|
1298
|
+
'totalPages' => $total_pages,
|
|
1299
|
+
'totalReviews' => $total_other,
|
|
1300
|
+
) );
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
function forgewp_rest_submit_product_review( $request ) {
|
|
1304
|
+
$product_id = intval( $request->get_param( 'id' ) );
|
|
1305
|
+
if ( ! $product_id || ! get_post( $product_id ) ) {
|
|
1306
|
+
return new WP_Error( 'invalid_product', 'Product not found', array( 'status' => 404 ) );
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
$current_user = wp_get_current_user();
|
|
1310
|
+
$user_id = $current_user ? $current_user->ID : 0;
|
|
1311
|
+
if ( ! $user_id && ! empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
|
|
1312
|
+
$cookie_user_id = wp_validate_auth_cookie( $_COOKIE[ LOGGED_IN_COOKIE ], 'logged_in' );
|
|
1313
|
+
if ( $cookie_user_id ) {
|
|
1314
|
+
wp_set_current_user( $cookie_user_id );
|
|
1315
|
+
$current_user = wp_get_current_user();
|
|
1316
|
+
$user_id = $cookie_user_id;
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
if ( ! $user_id ) {
|
|
1321
|
+
return new WP_Error( 'unauthorized', 'You must be logged in to leave a review.', array( 'status' => 401 ) );
|
|
1322
|
+
}
|
|
1323
|
+
$author = $current_user->display_name ?: $current_user->user_login;
|
|
1324
|
+
$email = $current_user->user_email;
|
|
1325
|
+
|
|
1326
|
+
$params = $request->get_json_params();
|
|
1327
|
+
if ( empty( $params ) ) {
|
|
1328
|
+
$params = $request->get_params();
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
$content = ! empty( $params['content'] ) ? sanitize_textarea_field( $params['content'] ) : ( ! empty( $params['comment'] ) ? sanitize_textarea_field( $params['comment'] ) : '' );
|
|
1332
|
+
$rating = ! empty( $params['rating'] ) ? max( 1, min( 5, intval( $params['rating'] ) ) ) : 5;
|
|
1333
|
+
|
|
1334
|
+
if ( empty( $content ) ) {
|
|
1335
|
+
return new WP_Error( 'missing_content', 'Review content is required', array( 'status' => 400 ) );
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
// Check if user already reviewed this product (edit mode)
|
|
1339
|
+
$existing_reviews = get_comments( array(
|
|
1340
|
+
'post_id' => $product_id,
|
|
1341
|
+
'user_id' => $user_id,
|
|
1342
|
+
'type' => 'review',
|
|
1343
|
+
) );
|
|
1344
|
+
|
|
1345
|
+
$is_update = ! empty( $existing_reviews );
|
|
1346
|
+
if ( $is_update ) {
|
|
1347
|
+
$existing_comment = $existing_reviews[0];
|
|
1348
|
+
$comment_id = intval( $existing_comment->comment_ID );
|
|
1349
|
+
wp_update_comment( array(
|
|
1350
|
+
'comment_ID' => $comment_id,
|
|
1351
|
+
'comment_content' => $content,
|
|
1352
|
+
'comment_date' => current_time( 'mysql' ),
|
|
1353
|
+
) );
|
|
1354
|
+
} else {
|
|
1355
|
+
$comment_data = array(
|
|
1356
|
+
'comment_post_ID' => $product_id,
|
|
1357
|
+
'comment_author' => $author,
|
|
1358
|
+
'comment_author_email' => $email,
|
|
1359
|
+
'comment_content' => $content,
|
|
1360
|
+
'comment_type' => 'review',
|
|
1361
|
+
'comment_parent' => 0,
|
|
1362
|
+
'user_id' => $user_id,
|
|
1363
|
+
'comment_approved' => 1,
|
|
1364
|
+
'comment_date' => current_time( 'mysql' ),
|
|
1365
|
+
);
|
|
1366
|
+
|
|
1367
|
+
$comment_id = wp_insert_comment( $comment_data );
|
|
1368
|
+
if ( ! $comment_id || is_wp_error( $comment_id ) ) {
|
|
1369
|
+
return new WP_Error( 'insert_failed', 'Failed to save review', array( 'status' => 500 ) );
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
update_comment_meta( $comment_id, 'rating', $rating );
|
|
1374
|
+
if ( function_exists( 'wc_customer_bought_product' ) && wc_customer_bought_product( $email, $user_id, $product_id ) ) {
|
|
1375
|
+
update_comment_meta( $comment_id, 'verified', 1 );
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// Recalculate WooCommerce product ratings
|
|
1379
|
+
if ( function_exists( 'wc_update_product_rating_counts' ) ) {
|
|
1380
|
+
wc_update_product_rating_counts( $product_id );
|
|
1381
|
+
}
|
|
1382
|
+
if ( function_exists( 'wc_update_product_average_rating' ) ) {
|
|
1383
|
+
wc_update_product_average_rating( $product_id );
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
$all_reviews = get_comments( array(
|
|
1387
|
+
'post_id' => $product_id,
|
|
1388
|
+
'type' => 'review',
|
|
1389
|
+
'status' => 'approve',
|
|
1390
|
+
) );
|
|
1391
|
+
$total_rating = 0;
|
|
1392
|
+
$rating_counts = array();
|
|
1393
|
+
foreach ( $all_reviews as $r ) {
|
|
1394
|
+
$r_rating = intval( get_comment_meta( $r->comment_ID, 'rating', true ) ?: 5 );
|
|
1395
|
+
$total_rating += $r_rating;
|
|
1396
|
+
$rating_counts[$r_rating] = isset( $rating_counts[$r_rating] ) ? $rating_counts[$r_rating] + 1 : 1;
|
|
1397
|
+
}
|
|
1398
|
+
$rev_count = count( $all_reviews );
|
|
1399
|
+
$avg_rating = $rev_count > 0 ? round( $total_rating / $rev_count, 2 ) : 0;
|
|
1400
|
+
update_post_meta( $product_id, '_wc_review_count', $rev_count );
|
|
1401
|
+
update_post_meta( $product_id, '_wc_rating_count', $rating_counts );
|
|
1402
|
+
update_post_meta( $product_id, '_wc_average_rating', $avg_rating );
|
|
1403
|
+
|
|
1404
|
+
$new_review = array(
|
|
1405
|
+
'id' => $comment_id,
|
|
1406
|
+
'author' => $author,
|
|
1407
|
+
'content' => $content,
|
|
1408
|
+
'rating' => $rating,
|
|
1409
|
+
'date' => current_time( 'Y-m-d' ),
|
|
1410
|
+
'verified' => true,
|
|
1411
|
+
'isOwner' => true,
|
|
1412
|
+
);
|
|
1413
|
+
|
|
1414
|
+
return rest_ensure_response( array(
|
|
1415
|
+
'success' => true,
|
|
1416
|
+
'isUpdate' => $is_update,
|
|
1417
|
+
'review' => $new_review,
|
|
1418
|
+
'ratingCount' => $rev_count,
|
|
1419
|
+
'averageRating' => number_format( $avg_rating, 2, '.', '' ),
|
|
1420
|
+
) );
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
function forgewp_rest_delete_product_review( $request ) {
|
|
1424
|
+
$product_id = intval( $request->get_param( 'id' ) );
|
|
1425
|
+
if ( ! $product_id || ! get_post( $product_id ) ) {
|
|
1426
|
+
return new WP_Error( 'invalid_product', 'Product not found', array( 'status' => 404 ) );
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
$current_user = wp_get_current_user();
|
|
1430
|
+
$user_id = $current_user ? $current_user->ID : 0;
|
|
1431
|
+
if ( ! $user_id && ! empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
|
|
1432
|
+
$cookie_user_id = wp_validate_auth_cookie( $_COOKIE[ LOGGED_IN_COOKIE ], 'logged_in' );
|
|
1433
|
+
if ( $cookie_user_id ) {
|
|
1434
|
+
wp_set_current_user( $cookie_user_id );
|
|
1435
|
+
$current_user = wp_get_current_user();
|
|
1436
|
+
$user_id = $cookie_user_id;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
if ( ! $user_id ) {
|
|
1441
|
+
return new WP_Error( 'unauthorized', 'You must be logged in to delete a review.', array( 'status' => 401 ) );
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
$existing_reviews = get_comments( array(
|
|
1445
|
+
'post_id' => $product_id,
|
|
1446
|
+
'user_id' => $user_id,
|
|
1447
|
+
'type' => 'review',
|
|
1448
|
+
) );
|
|
1449
|
+
|
|
1450
|
+
if ( empty( $existing_reviews ) ) {
|
|
1451
|
+
return new WP_Error( 'review_not_found', 'No review found for this user.', array( 'status' => 404 ) );
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
foreach ( $existing_reviews as $r ) {
|
|
1455
|
+
wp_delete_comment( $r->comment_ID, true );
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
// Recalculate WooCommerce product ratings
|
|
1459
|
+
if ( function_exists( 'wc_update_product_rating_counts' ) ) {
|
|
1460
|
+
wc_update_product_rating_counts( $product_id );
|
|
1461
|
+
}
|
|
1462
|
+
if ( function_exists( 'wc_update_product_average_rating' ) ) {
|
|
1463
|
+
wc_update_product_average_rating( $product_id );
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
$all_reviews = get_comments( array(
|
|
1467
|
+
'post_id' => $product_id,
|
|
1468
|
+
'type' => 'review',
|
|
1469
|
+
'status' => 'approve',
|
|
1470
|
+
) );
|
|
1471
|
+
$total_rating = 0;
|
|
1472
|
+
$rating_counts = array();
|
|
1473
|
+
foreach ( $all_reviews as $r ) {
|
|
1474
|
+
$r_rating = intval( get_comment_meta( $r->comment_ID, 'rating', true ) ?: 5 );
|
|
1475
|
+
$total_rating += $r_rating;
|
|
1476
|
+
$rating_counts[$r_rating] = isset( $rating_counts[$r_rating] ) ? $rating_counts[$r_rating] + 1 : 1;
|
|
1477
|
+
}
|
|
1478
|
+
$rev_count = count( $all_reviews );
|
|
1479
|
+
$avg_rating = $rev_count > 0 ? round( $total_rating / $rev_count, 2 ) : 0;
|
|
1480
|
+
update_post_meta( $product_id, '_wc_review_count', $rev_count );
|
|
1481
|
+
update_post_meta( $product_id, '_wc_rating_count', $rating_counts );
|
|
1482
|
+
update_post_meta( $product_id, '_wc_average_rating', $avg_rating );
|
|
1483
|
+
|
|
1484
|
+
return rest_ensure_response( array(
|
|
1485
|
+
'success' => true,
|
|
1486
|
+
'deleted' => true,
|
|
1487
|
+
'ratingCount' => $rev_count,
|
|
1488
|
+
'averageRating' => number_format( $avg_rating, 2, '.', '' ),
|
|
1489
|
+
) );
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
/**
|
|
1493
|
+
* ── ForgeWP Universal WooCommerce Cart REST Endpoints ──
|
|
1494
|
+
*/
|
|
1495
|
+
add_action( 'rest_api_init', 'forgewp_cart_register_rest_routes' );
|
|
1496
|
+
function forgewp_cart_register_rest_routes() {
|
|
1497
|
+
register_rest_route( 'forgewp/v1', '/cart', array(
|
|
1498
|
+
array(
|
|
1499
|
+
'methods' => 'GET',
|
|
1500
|
+
'callback' => 'forgewp_rest_get_cart',
|
|
1501
|
+
'permission_callback' => '__return_true',
|
|
1502
|
+
),
|
|
1503
|
+
) );
|
|
1504
|
+
|
|
1505
|
+
register_rest_route( 'forgewp/v1', '/cart/add', array(
|
|
1506
|
+
array(
|
|
1507
|
+
'methods' => 'POST',
|
|
1508
|
+
'callback' => 'forgewp_rest_add_to_cart',
|
|
1509
|
+
'permission_callback' => '__return_true',
|
|
1510
|
+
),
|
|
1511
|
+
) );
|
|
1512
|
+
|
|
1513
|
+
register_rest_route( 'forgewp/v1', '/cart/update', array(
|
|
1514
|
+
array(
|
|
1515
|
+
'methods' => 'POST',
|
|
1516
|
+
'callback' => 'forgewp_rest_update_cart_item',
|
|
1517
|
+
'permission_callback' => '__return_true',
|
|
1518
|
+
),
|
|
1519
|
+
) );
|
|
1520
|
+
|
|
1521
|
+
register_rest_route( 'forgewp/v1', '/cart/remove', array(
|
|
1522
|
+
array(
|
|
1523
|
+
'methods' => 'POST',
|
|
1524
|
+
'callback' => 'forgewp_rest_remove_cart_item',
|
|
1525
|
+
'permission_callback' => '__return_true',
|
|
1526
|
+
),
|
|
1527
|
+
) );
|
|
1528
|
+
|
|
1529
|
+
register_rest_route( 'forgewp/v1', '/cart/clear', array(
|
|
1530
|
+
array(
|
|
1531
|
+
'methods' => 'POST',
|
|
1532
|
+
'callback' => 'forgewp_rest_clear_cart',
|
|
1533
|
+
'permission_callback' => '__return_true',
|
|
1534
|
+
),
|
|
1535
|
+
) );
|
|
1536
|
+
|
|
1537
|
+
register_rest_route( 'forgewp/v1', '/cart/apply-coupon', array(
|
|
1538
|
+
array(
|
|
1539
|
+
'methods' => 'POST',
|
|
1540
|
+
'callback' => 'forgewp_rest_apply_coupon',
|
|
1541
|
+
'permission_callback' => '__return_true',
|
|
1542
|
+
),
|
|
1543
|
+
) );
|
|
1544
|
+
|
|
1545
|
+
register_rest_route( 'forgewp/v1', '/cart/sync', array(
|
|
1546
|
+
array(
|
|
1547
|
+
'methods' => 'POST',
|
|
1548
|
+
'callback' => 'forgewp_rest_sync_cart',
|
|
1549
|
+
'permission_callback' => '__return_true',
|
|
1550
|
+
),
|
|
1551
|
+
) );
|
|
1552
|
+
|
|
1553
|
+
register_rest_route( 'forgewp/v1', '/cart/shipping-rates', array(
|
|
1554
|
+
array(
|
|
1555
|
+
'methods' => array( 'GET', 'POST' ),
|
|
1556
|
+
'callback' => 'forgewp_rest_get_shipping_rates',
|
|
1557
|
+
'permission_callback' => '__return_true',
|
|
1558
|
+
),
|
|
1559
|
+
) );
|
|
1560
|
+
|
|
1561
|
+
register_rest_route( 'forgewp/v1', '/checkout/gateways', array(
|
|
1562
|
+
array(
|
|
1563
|
+
'methods' => 'GET',
|
|
1564
|
+
'callback' => 'forgewp_rest_get_checkout_gateways',
|
|
1565
|
+
'permission_callback' => '__return_true',
|
|
1566
|
+
),
|
|
1567
|
+
) );
|
|
1568
|
+
|
|
1569
|
+
register_rest_route( 'forgewp/v1', '/checkout/process', array(
|
|
1570
|
+
array(
|
|
1571
|
+
'methods' => 'POST',
|
|
1572
|
+
'callback' => 'forgewp_rest_process_checkout',
|
|
1573
|
+
'permission_callback' => '__return_true',
|
|
1574
|
+
),
|
|
1575
|
+
) );
|
|
1576
|
+
|
|
1577
|
+
register_rest_route( 'forgewp/v1', '/customer/orders', array(
|
|
1578
|
+
array(
|
|
1579
|
+
'methods' => 'GET',
|
|
1580
|
+
'callback' => 'forgewp_rest_get_customer_orders',
|
|
1581
|
+
'permission_callback' => '__return_true',
|
|
1582
|
+
),
|
|
1583
|
+
) );
|
|
1584
|
+
|
|
1585
|
+
register_rest_route( 'forgewp/v1', '/customer/orders/(?P<id>[\d]+)', array(
|
|
1586
|
+
array(
|
|
1587
|
+
'methods' => 'GET',
|
|
1588
|
+
'callback' => 'forgewp_rest_get_customer_order_detail',
|
|
1589
|
+
'permission_callback' => '__return_true',
|
|
1590
|
+
),
|
|
1591
|
+
) );
|
|
1592
|
+
|
|
1593
|
+
register_rest_route( 'forgewp/v1', '/customer/downloads', array(
|
|
1594
|
+
array(
|
|
1595
|
+
'methods' => 'GET',
|
|
1596
|
+
'callback' => 'forgewp_rest_get_customer_downloads',
|
|
1597
|
+
'permission_callback' => '__return_true',
|
|
1598
|
+
),
|
|
1599
|
+
) );
|
|
1600
|
+
|
|
1601
|
+
register_rest_route( 'forgewp/v1', '/wishlist', array(
|
|
1602
|
+
array(
|
|
1603
|
+
'methods' => 'GET',
|
|
1604
|
+
'callback' => 'forgewp_rest_get_wishlist',
|
|
1605
|
+
'permission_callback' => '__return_true',
|
|
1606
|
+
),
|
|
1607
|
+
) );
|
|
1608
|
+
|
|
1609
|
+
register_rest_route( 'forgewp/v1', '/wishlist/toggle', array(
|
|
1610
|
+
array(
|
|
1611
|
+
'methods' => 'POST',
|
|
1612
|
+
'callback' => 'forgewp_rest_toggle_wishlist',
|
|
1613
|
+
'permission_callback' => '__return_true',
|
|
1614
|
+
),
|
|
1615
|
+
) );
|
|
1616
|
+
|
|
1617
|
+
register_rest_route( 'forgewp/v1', '/wishlist/sync', array(
|
|
1618
|
+
array(
|
|
1619
|
+
'methods' => 'POST',
|
|
1620
|
+
'callback' => 'forgewp_rest_sync_wishlist',
|
|
1621
|
+
'permission_callback' => '__return_true',
|
|
1622
|
+
),
|
|
1623
|
+
) );
|
|
1624
|
+
|
|
1625
|
+
register_rest_route( 'forgewp/v1', '/products', array(
|
|
1626
|
+
array(
|
|
1627
|
+
'methods' => 'GET',
|
|
1628
|
+
'callback' => 'forgewp_rest_query_products',
|
|
1629
|
+
'permission_callback' => '__return_true',
|
|
1630
|
+
),
|
|
1631
|
+
) );
|
|
1632
|
+
|
|
1633
|
+
register_rest_route( 'forgewp/v1', '/customer/profile', array(
|
|
1634
|
+
array(
|
|
1635
|
+
'methods' => 'POST',
|
|
1636
|
+
'callback' => 'forgewp_rest_update_customer_profile',
|
|
1637
|
+
'permission_callback' => '__return_true',
|
|
1638
|
+
),
|
|
1639
|
+
) );
|
|
1640
|
+
|
|
1641
|
+
register_rest_route( 'forgewp/v1', '/customer/address', array(
|
|
1642
|
+
array(
|
|
1643
|
+
'methods' => 'POST',
|
|
1644
|
+
'callback' => 'forgewp_rest_update_customer_address',
|
|
1645
|
+
'permission_callback' => '__return_true',
|
|
1646
|
+
),
|
|
1647
|
+
) );
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
add_filter( 'woocommerce_get_cart_item_from_session', function( $session_data, $values ) {
|
|
1651
|
+
if ( ! empty( $values['image'] ) ) {
|
|
1652
|
+
$session_data['image'] = $values['image'];
|
|
1653
|
+
}
|
|
1654
|
+
if ( ! empty( $values['variantLabel'] ) ) {
|
|
1655
|
+
$session_data['variantLabel'] = $values['variantLabel'];
|
|
1656
|
+
}
|
|
1657
|
+
return $session_data;
|
|
1658
|
+
}, 20, 2 );
|
|
1659
|
+
|
|
1660
|
+
function forgewp_resolve_wc_product_id( $params ) {
|
|
1661
|
+
$product_id = intval( ! empty( $params['productId'] ) ? $params['productId'] : ( ! empty( $params['id'] ) ? $params['id'] : 0 ) );
|
|
1662
|
+
|
|
1663
|
+
// Check if product_id is valid WooCommerce product
|
|
1664
|
+
if ( $product_id && function_exists( 'wc_get_product' ) ) {
|
|
1665
|
+
$p = wc_get_product( $product_id );
|
|
1666
|
+
if ( $p && is_object( $p ) ) {
|
|
1667
|
+
return $product_id;
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
// Lookup by slug
|
|
1672
|
+
$slug = ! empty( $params['slug'] ) ? sanitize_title( $params['slug'] ) : '';
|
|
1673
|
+
if ( ! empty( $slug ) ) {
|
|
1674
|
+
$posts = get_posts( array(
|
|
1675
|
+
'name' => $slug,
|
|
1676
|
+
'post_type' => 'product',
|
|
1677
|
+
'post_status' => 'publish',
|
|
1678
|
+
'posts_per_page' => 1,
|
|
1679
|
+
'fields' => 'ids',
|
|
1680
|
+
) );
|
|
1681
|
+
if ( ! empty( $posts ) ) {
|
|
1682
|
+
return intval( $posts[0] );
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
// Lookup by name/title
|
|
1687
|
+
$title = ! empty( $params['name'] ) ? sanitize_text_field( $params['name'] ) : ( ! empty( $params['title'] ) ? sanitize_text_field( $params['title'] ) : '' );
|
|
1688
|
+
if ( ! empty( $title ) ) {
|
|
1689
|
+
$posts = get_posts( array(
|
|
1690
|
+
'title' => $title,
|
|
1691
|
+
'post_type' => 'product',
|
|
1692
|
+
'post_status' => 'publish',
|
|
1693
|
+
'posts_per_page' => 1,
|
|
1694
|
+
'fields' => 'ids',
|
|
1695
|
+
) );
|
|
1696
|
+
if ( ! empty( $posts ) ) {
|
|
1697
|
+
return intval( $posts[0] );
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
// Fallback: If still not found and a product exists in WooCommerce, find first available
|
|
1702
|
+
if ( ! $product_id && function_exists( 'wc_get_products' ) ) {
|
|
1703
|
+
$prods = wc_get_products( array( 'limit' => 1, 'return' => 'ids' ) );
|
|
1704
|
+
if ( ! empty( $prods ) ) {
|
|
1705
|
+
return intval( $prods[0] );
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
return $product_id;
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
function forgewp_ensure_wc_cart() {
|
|
1713
|
+
if ( ! function_exists( 'WC' ) ) {
|
|
1714
|
+
return false;
|
|
1715
|
+
}
|
|
1716
|
+
if ( ! get_current_user_id() && ! empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
|
|
1717
|
+
$cookie_user_id = wp_validate_auth_cookie( $_COOKIE[ LOGGED_IN_COOKIE ], 'logged_in' );
|
|
1718
|
+
if ( $cookie_user_id ) {
|
|
1719
|
+
wp_set_current_user( $cookie_user_id );
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
if ( ! get_current_user_id() && function_exists( 'forgewp_validate_jwt_token' ) ) {
|
|
1723
|
+
$auth_header = isset( $_SERVER['HTTP_AUTHORIZATION'] ) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
|
|
1724
|
+
if ( $auth_header && preg_match( '/Bearer\s+(\S+)/i', $auth_header, $matches ) ) {
|
|
1725
|
+
$jwt_user_id = forgewp_validate_jwt_token( $matches[1] );
|
|
1726
|
+
if ( $jwt_user_id ) {
|
|
1727
|
+
wp_set_current_user( $jwt_user_id );
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
if ( defined( 'WC_ABSPATH' ) ) {
|
|
1732
|
+
include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
|
|
1733
|
+
include_once WC_ABSPATH . 'includes/wc-notice-functions.php';
|
|
1734
|
+
}
|
|
1735
|
+
$user_id = get_current_user_id();
|
|
1736
|
+
if ( null === WC()->session ) {
|
|
1737
|
+
$session_class = apply_filters( 'woocommerce_session_handler', 'WC_Session_Handler' );
|
|
1738
|
+
WC()->session = new $session_class();
|
|
1739
|
+
WC()->session->init();
|
|
1740
|
+
}
|
|
1741
|
+
if ( null === WC()->customer ) {
|
|
1742
|
+
WC()->customer = new WC_Customer( $user_id, true );
|
|
1743
|
+
}
|
|
1744
|
+
if ( null === WC()->cart ) {
|
|
1745
|
+
WC()->cart = new WC_Cart();
|
|
1746
|
+
}
|
|
1747
|
+
if ( method_exists( WC()->cart, 'get_cart_from_session' ) && empty( WC()->cart->get_cart() ) ) {
|
|
1748
|
+
WC()->cart->get_cart_from_session();
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
// Unpack persistent cart from user metadata only if cart is strictly empty and user is logged in
|
|
1752
|
+
if ( $user_id && empty( WC()->cart->get_cart() ) ) {
|
|
1753
|
+
$blog_id = function_exists( 'get_current_blog_id' ) ? get_current_blog_id() : 1;
|
|
1754
|
+
$saved_cart = get_user_meta( $user_id, '_woocommerce_persistent_cart_' . $blog_id, true );
|
|
1755
|
+
if ( empty( $saved_cart ) || ! is_array( $saved_cart ) ) {
|
|
1756
|
+
$saved_cart = get_user_meta( $user_id, '_woocommerce_persistent_cart_1', true );
|
|
1757
|
+
}
|
|
1758
|
+
if ( empty( $saved_cart ) || ! is_array( $saved_cart ) ) {
|
|
1759
|
+
$saved_cart = get_user_meta( $user_id, '_woocommerce_persistent_cart', true );
|
|
1760
|
+
}
|
|
1761
|
+
if ( ! empty( $saved_cart['cart'] ) && is_array( $saved_cart['cart'] ) ) {
|
|
1762
|
+
$cart_contents = array();
|
|
1763
|
+
foreach ( $saved_cart['cart'] as $item_key => $item ) {
|
|
1764
|
+
if ( ! empty( $item['product_id'] ) ) {
|
|
1765
|
+
$prod_id = intval( $item['product_id'] );
|
|
1766
|
+
$variation_id = ! empty( $item['variation_id'] ) ? intval( $item['variation_id'] ) : 0;
|
|
1767
|
+
$product = wc_get_product( $variation_id ? $variation_id : $prod_id );
|
|
1768
|
+
if ( $product && $product->exists() ) {
|
|
1769
|
+
$item['data'] = $product;
|
|
1770
|
+
$cart_contents[ $item_key ] = $item;
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
if ( ! empty( $cart_contents ) ) {
|
|
1775
|
+
WC()->cart->set_cart_contents( $cart_contents );
|
|
1776
|
+
forgewp_save_wc_cart();
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
return true;
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
function forgewp_save_wc_cart() {
|
|
1785
|
+
if ( function_exists( 'WC' ) && WC()->cart && WC()->session ) {
|
|
1786
|
+
WC()->cart->calculate_totals();
|
|
1787
|
+
if ( method_exists( WC()->cart, 'set_session' ) ) {
|
|
1788
|
+
WC()->cart->set_session();
|
|
1789
|
+
}
|
|
1790
|
+
if ( method_exists( WC()->cart, 'maybe_set_cart_cookies' ) ) {
|
|
1791
|
+
WC()->cart->maybe_set_cart_cookies();
|
|
1792
|
+
}
|
|
1793
|
+
if ( method_exists( WC()->session, 'set_customer_session_cookie' ) ) {
|
|
1794
|
+
WC()->session->set_customer_session_cookie( true );
|
|
1795
|
+
}
|
|
1796
|
+
if ( method_exists( WC()->session, 'save_data' ) ) {
|
|
1797
|
+
WC()->session->save_data();
|
|
1798
|
+
}
|
|
1799
|
+
$user_id = get_current_user_id();
|
|
1800
|
+
if ( $user_id ) {
|
|
1801
|
+
if ( method_exists( WC()->cart, 'persistent_cart_update' ) ) {
|
|
1802
|
+
WC()->cart->persistent_cart_update();
|
|
1803
|
+
}
|
|
1804
|
+
$cart_data = array(
|
|
1805
|
+
'cart' => WC()->cart->get_cart_for_session(),
|
|
1806
|
+
);
|
|
1807
|
+
$blog_id = function_exists( 'get_current_blog_id' ) ? get_current_blog_id() : 1;
|
|
1808
|
+
update_user_meta( $user_id, '_woocommerce_persistent_cart_' . $blog_id, $cart_data );
|
|
1809
|
+
update_user_meta( $user_id, '_woocommerce_persistent_cart_1', $cart_data );
|
|
1810
|
+
update_user_meta( $user_id, '_woocommerce_persistent_cart', $cart_data );
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
function forgewp_format_cart_response() {
|
|
1816
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
1817
|
+
return array(
|
|
1818
|
+
'items' => array(),
|
|
1819
|
+
'itemCount' => 0,
|
|
1820
|
+
'subtotal' => 0,
|
|
1821
|
+
'totals' => array(
|
|
1822
|
+
'subtotal' => '0.00',
|
|
1823
|
+
'discount' => '0.00',
|
|
1824
|
+
'shipping' => '0.00',
|
|
1825
|
+
'tax' => '0.00',
|
|
1826
|
+
'total' => '0.00',
|
|
1827
|
+
),
|
|
1828
|
+
'coupons' => array(),
|
|
1829
|
+
'currency' => '$',
|
|
1830
|
+
);
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
WC()->cart->calculate_totals();
|
|
1834
|
+
|
|
1835
|
+
$items = array();
|
|
1836
|
+
$cart_contents = WC()->cart->get_cart();
|
|
1837
|
+
|
|
1838
|
+
foreach ( $cart_contents as $cart_item_key => $cart_item ) {
|
|
1839
|
+
$product = $cart_item['data'];
|
|
1840
|
+
if ( ! $product || ! is_object( $product ) ) {
|
|
1841
|
+
continue;
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
$product_id = $product->get_id();
|
|
1845
|
+
$parent_id = $product->get_parent_id();
|
|
1846
|
+
$main_id = $parent_id ? $parent_id : $product_id;
|
|
1847
|
+
$main_post = get_post( $main_id );
|
|
1848
|
+
$slug = $main_post ? $main_post->post_name : '';
|
|
1849
|
+
|
|
1850
|
+
$image_url = '';
|
|
1851
|
+
if ( ! empty( $cart_item['image'] ) && is_string( $cart_item['image'] ) && filter_var( $cart_item['image'], FILTER_VALIDATE_URL ) ) {
|
|
1852
|
+
$image_url = $cart_item['image'];
|
|
1853
|
+
}
|
|
1854
|
+
if ( ! $image_url ) {
|
|
1855
|
+
$image_id = $product->get_image_id();
|
|
1856
|
+
if ( ! $image_id && $parent_id ) {
|
|
1857
|
+
$parent_prod = wc_get_product( $parent_id );
|
|
1858
|
+
if ( $parent_prod ) {
|
|
1859
|
+
$image_id = $parent_prod->get_image_id();
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
if ( $image_id ) {
|
|
1863
|
+
$image_url = wp_get_attachment_image_url( $image_id, 'medium' ) ?: wp_get_attachment_url( $image_id );
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
if ( ! $image_url ) {
|
|
1867
|
+
$meta_keys = array( '_forgewp_image', 'featured_image', '_featured_image', 'image', '_thumbnail_url', '_external_image_url' );
|
|
1868
|
+
foreach ( $meta_keys as $m_key ) {
|
|
1869
|
+
$m_val = get_post_meta( $main_id, $m_key, true );
|
|
1870
|
+
if ( $m_val && is_string( $m_val ) && filter_var( $m_val, FILTER_VALIDATE_URL ) ) {
|
|
1871
|
+
$image_url = $m_val;
|
|
1872
|
+
break;
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
if ( ! $image_url ) {
|
|
1877
|
+
$meta_images = get_post_meta( $main_id, '_forgewp_images', true );
|
|
1878
|
+
if ( empty( $meta_images ) ) {
|
|
1879
|
+
$meta_images = get_post_meta( $main_id, 'images', true );
|
|
1880
|
+
}
|
|
1881
|
+
if ( is_array( $meta_images ) && ! empty( $meta_images[0] ) ) {
|
|
1882
|
+
$image_url = is_string( $meta_images[0] ) ? $meta_images[0] : ( ! empty( $meta_images[0]['src'] ) ? $meta_images[0]['src'] : '' );
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
if ( ! $image_url ) {
|
|
1886
|
+
$image_url = wc_placeholder_img_src( 'medium' );
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
$price = floatval( $product->get_price() );
|
|
1890
|
+
$regular_price = floatval( $product->get_regular_price() );
|
|
1891
|
+
$line_subtotal = floatval( $cart_item['line_subtotal'] );
|
|
1892
|
+
$quantity = intval( $cart_item['quantity'] );
|
|
1893
|
+
|
|
1894
|
+
$variation_attrs = array();
|
|
1895
|
+
if ( ! empty( $cart_item['variation'] ) && is_array( $cart_item['variation'] ) ) {
|
|
1896
|
+
foreach ( $cart_item['variation'] as $attr_name => $attr_val ) {
|
|
1897
|
+
$clean_name = str_replace( 'attribute_', '', $attr_name );
|
|
1898
|
+
$variation_attrs[$clean_name] = $attr_val;
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
$variant_label = ! empty( $variation_attrs ) ? implode( ', ', array_values( $variation_attrs ) ) : ( ! empty( $cart_item['variantLabel'] ) ? $cart_item['variantLabel'] : '' );
|
|
1903
|
+
|
|
1904
|
+
$items[] = array(
|
|
1905
|
+
'id' => $cart_item_key,
|
|
1906
|
+
'key' => $cart_item_key,
|
|
1907
|
+
'productId' => $main_id,
|
|
1908
|
+
'variationId' => $parent_id ? $product_id : 0,
|
|
1909
|
+
'slug' => $slug,
|
|
1910
|
+
'name' => $product->get_name(),
|
|
1911
|
+
'price' => $price,
|
|
1912
|
+
'compareAtPrice' => ( $regular_price > $price ) ? $regular_price : null,
|
|
1913
|
+
'image' => $image_url,
|
|
1914
|
+
'quantity' => $quantity,
|
|
1915
|
+
'variantLabel' => $variant_label,
|
|
1916
|
+
'variation' => $variation_attrs,
|
|
1917
|
+
'lineSubtotal' => $line_subtotal,
|
|
1918
|
+
);
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
$subtotal_val = floatval( WC()->cart->get_subtotal() );
|
|
1922
|
+
$total_val = floatval( WC()->cart->get_total( 'edit' ) );
|
|
1923
|
+
$discount_val = floatval( WC()->cart->get_discount_total() );
|
|
1924
|
+
$shipping_val = floatval( WC()->cart->get_shipping_total() );
|
|
1925
|
+
$tax_val = floatval( WC()->cart->get_total_tax() );
|
|
1926
|
+
|
|
1927
|
+
return array(
|
|
1928
|
+
'items' => $items,
|
|
1929
|
+
'itemCount' => intval( WC()->cart->get_cart_contents_count() ),
|
|
1930
|
+
'subtotal' => $subtotal_val,
|
|
1931
|
+
'totals' => array(
|
|
1932
|
+
'subtotal' => number_format( $subtotal_val, 2, '.', '' ),
|
|
1933
|
+
'discount' => number_format( $discount_val, 2, '.', '' ),
|
|
1934
|
+
'shipping' => number_format( $shipping_val, 2, '.', '' ),
|
|
1935
|
+
'tax' => number_format( $tax_val, 2, '.', '' ),
|
|
1936
|
+
'total' => number_format( $total_val, 2, '.', '' ),
|
|
1937
|
+
),
|
|
1938
|
+
'coupons' => array_values( WC()->cart->get_applied_coupons() ),
|
|
1939
|
+
'currency' => get_woocommerce_currency_symbol(),
|
|
1940
|
+
);
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
function forgewp_rest_get_cart( $request ) {
|
|
1944
|
+
return rest_ensure_response( forgewp_format_cart_response() );
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
function forgewp_rest_add_to_cart( $request ) {
|
|
1948
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
1949
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
$params = $request->get_json_params();
|
|
1953
|
+
if ( empty( $params ) ) {
|
|
1954
|
+
$params = $request->get_params();
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
$product_id = forgewp_resolve_wc_product_id( $params );
|
|
1958
|
+
$quantity = max( 1, intval( ! empty( $params['quantity'] ) ? $params['quantity'] : 1 ) );
|
|
1959
|
+
$variation_id = intval( ! empty( $params['variationId'] ) ? $params['variationId'] : 0 );
|
|
1960
|
+
$variation = ! empty( $params['variation'] ) && is_array( $params['variation'] ) ? $params['variation'] : array();
|
|
1961
|
+
$custom_data = array();
|
|
1962
|
+
if ( ! empty( $params['variantLabel'] ) ) {
|
|
1963
|
+
$custom_data['variantLabel'] = sanitize_text_field( $params['variantLabel'] );
|
|
1964
|
+
}
|
|
1965
|
+
if ( ! empty( $params['image'] ) ) {
|
|
1966
|
+
$custom_data['image'] = esc_url_raw( $params['image'] );
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
if ( ! $product_id ) {
|
|
1970
|
+
return new WP_Error( 'missing_product_id', 'Product ID is required', array( 'status' => 400 ) );
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
$cart_item_key = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $custom_data );
|
|
1974
|
+
|
|
1975
|
+
if ( ! $cart_item_key ) {
|
|
1976
|
+
$notices = wc_get_notices( 'error' );
|
|
1977
|
+
$err_msg = ! empty( $notices ) ? wp_strip_all_tags( $notices[0]['notice'] ) : 'Failed to add item to cart';
|
|
1978
|
+
wc_clear_notices();
|
|
1979
|
+
return new WP_Error( 'add_to_cart_failed', $err_msg, array( 'status' => 400 ) );
|
|
1980
|
+
}
|
|
1981
|
+
|
|
1982
|
+
forgewp_save_wc_cart();
|
|
1983
|
+
|
|
1984
|
+
return rest_ensure_response( forgewp_format_cart_response() );
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
function forgewp_rest_sync_cart( $request ) {
|
|
1988
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
1989
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1992
|
+
$params = $request->get_json_params();
|
|
1993
|
+
if ( empty( $params ) ) {
|
|
1994
|
+
$params = $request->get_params();
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
$items = ! empty( $params['items'] ) && is_array( $params['items'] ) ? $params['items'] : array();
|
|
1998
|
+
|
|
1999
|
+
// Empty existing cart first so sync is idempotent and doesn't compound quantities
|
|
2000
|
+
WC()->cart->empty_cart( false );
|
|
2001
|
+
|
|
2002
|
+
foreach ( $items as $item ) {
|
|
2003
|
+
$prod_id = forgewp_resolve_wc_product_id( $item );
|
|
2004
|
+
$qty = max( 1, intval( ! empty( $item['quantity'] ) ? $item['quantity'] : 1 ) );
|
|
2005
|
+
$var_id = intval( ! empty( $item['variationId'] ) ? $item['variationId'] : 0 );
|
|
2006
|
+
$variation = ! empty( $item['variation'] ) && is_array( $item['variation'] ) ? $item['variation'] : array();
|
|
2007
|
+
$custom = array();
|
|
2008
|
+
if ( ! empty( $item['variantLabel'] ) ) {
|
|
2009
|
+
$custom['variantLabel'] = sanitize_text_field( $item['variantLabel'] );
|
|
2010
|
+
}
|
|
2011
|
+
if ( ! empty( $item['image'] ) ) {
|
|
2012
|
+
$custom['image'] = esc_url_raw( $item['image'] );
|
|
2013
|
+
}
|
|
2014
|
+
if ( $prod_id ) {
|
|
2015
|
+
WC()->cart->add_to_cart( $prod_id, $qty, $var_id, $variation, $custom );
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
forgewp_save_wc_cart();
|
|
2020
|
+
|
|
2021
|
+
return rest_ensure_response( forgewp_format_cart_response() );
|
|
2022
|
+
}
|
|
2023
|
+
|
|
2024
|
+
function forgewp_rest_update_cart_item( $request ) {
|
|
2025
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
2026
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
$params = $request->get_json_params();
|
|
2030
|
+
if ( empty( $params ) ) {
|
|
2031
|
+
$params = $request->get_params();
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
$key = ! empty( $params['key'] ) ? sanitize_text_field( $params['key'] ) : ( ! empty( $params['lineId'] ) ? sanitize_text_field( $params['lineId'] ) : ( ! empty( $params['id'] ) ? sanitize_text_field( $params['id'] ) : '' ) );
|
|
2035
|
+
$quantity = intval( isset( $params['quantity'] ) ? $params['quantity'] : 1 );
|
|
2036
|
+
|
|
2037
|
+
if ( ! $key ) {
|
|
2038
|
+
return new WP_Error( 'missing_key', 'Cart item key is required', array( 'status' => 400 ) );
|
|
2039
|
+
}
|
|
2040
|
+
|
|
2041
|
+
if ( $quantity <= 0 ) {
|
|
2042
|
+
WC()->cart->remove_cart_item( $key );
|
|
2043
|
+
} else {
|
|
2044
|
+
WC()->cart->set_quantity( $key, $quantity );
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
forgewp_save_wc_cart();
|
|
2048
|
+
|
|
2049
|
+
return rest_ensure_response( forgewp_format_cart_response() );
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
function forgewp_rest_remove_cart_item( $request ) {
|
|
2053
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
2054
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
$params = $request->get_json_params();
|
|
2058
|
+
if ( empty( $params ) ) {
|
|
2059
|
+
$params = $request->get_params();
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2062
|
+
$key = ! empty( $params['key'] ) ? sanitize_text_field( $params['key'] ) : ( ! empty( $params['lineId'] ) ? sanitize_text_field( $params['lineId'] ) : ( ! empty( $params['id'] ) ? sanitize_text_field( $params['id'] ) : '' ) );
|
|
2063
|
+
|
|
2064
|
+
if ( ! $key ) {
|
|
2065
|
+
return new WP_Error( 'missing_key', 'Cart item key is required', array( 'status' => 400 ) );
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
WC()->cart->remove_cart_item( $key );
|
|
2069
|
+
|
|
2070
|
+
forgewp_save_wc_cart();
|
|
2071
|
+
|
|
2072
|
+
return rest_ensure_response( forgewp_format_cart_response() );
|
|
2073
|
+
}
|
|
2074
|
+
|
|
2075
|
+
function forgewp_rest_clear_cart( $request ) {
|
|
2076
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
2077
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
WC()->cart->empty_cart();
|
|
2081
|
+
|
|
2082
|
+
forgewp_save_wc_cart();
|
|
2083
|
+
|
|
2084
|
+
return rest_ensure_response( forgewp_format_cart_response() );
|
|
2085
|
+
}
|
|
2086
|
+
|
|
2087
|
+
function forgewp_rest_apply_coupon( $request ) {
|
|
2088
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
2089
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
$params = $request->get_json_params();
|
|
2093
|
+
if ( empty( $params ) ) {
|
|
2094
|
+
$params = $request->get_params();
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
$code = ! empty( $params['code'] ) ? sanitize_text_field( $params['code'] ) : '';
|
|
2098
|
+
if ( ! $code ) {
|
|
2099
|
+
return new WP_Error( 'missing_code', 'Coupon code is required', array( 'status' => 400 ) );
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
$applied = WC()->cart->apply_coupon( $code );
|
|
2103
|
+
if ( ! $applied ) {
|
|
2104
|
+
$notices = wc_get_notices( 'error' );
|
|
2105
|
+
$err_msg = ! empty( $notices ) ? wp_strip_all_tags( $notices[0]['notice'] ) : 'Invalid coupon code';
|
|
2106
|
+
wc_clear_notices();
|
|
2107
|
+
return new WP_Error( 'coupon_error', $err_msg, array( 'status' => 400 ) );
|
|
2108
|
+
}
|
|
2109
|
+
|
|
2110
|
+
forgewp_save_wc_cart();
|
|
2111
|
+
|
|
2112
|
+
return rest_ensure_response( forgewp_format_cart_response() );
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
function forgewp_rest_remove_coupon( $request ) {
|
|
2116
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
2117
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
$params = $request->get_json_params();
|
|
2121
|
+
if ( empty( $params ) ) {
|
|
2122
|
+
$params = $request->get_params();
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
$code = ! empty( $params['code'] ) ? sanitize_text_field( $params['code'] ) : '';
|
|
2126
|
+
if ( $code ) {
|
|
2127
|
+
WC()->cart->remove_coupon( $code );
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
forgewp_save_wc_cart();
|
|
2131
|
+
|
|
2132
|
+
return rest_ensure_response( forgewp_format_cart_response() );
|
|
2133
|
+
}
|
|
2134
|
+
|
|
2135
|
+
function forgewp_rest_get_shipping_rates( $request ) {
|
|
2136
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
2137
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
$params = $request->get_json_params();
|
|
2141
|
+
if ( empty( $params ) ) {
|
|
2142
|
+
$params = $request->get_params();
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
$country = ! empty( $params['country'] ) ? sanitize_text_field( $params['country'] ) : ( WC()->customer ? WC()->customer->get_shipping_country() : 'US' );
|
|
2146
|
+
$state = ! empty( $params['state'] ) ? sanitize_text_field( $params['state'] ) : ( WC()->customer ? WC()->customer->get_shipping_state() : '' );
|
|
2147
|
+
$city = ! empty( $params['city'] ) ? sanitize_text_field( $params['city'] ) : ( WC()->customer ? WC()->customer->get_shipping_city() : '' );
|
|
2148
|
+
$postcode = ! empty( $params['postcode'] ) ? sanitize_text_field( $params['postcode'] ) : ( WC()->customer ? WC()->customer->get_shipping_postcode() : '' );
|
|
2149
|
+
|
|
2150
|
+
if ( WC()->customer ) {
|
|
2151
|
+
WC()->customer->set_shipping_country( $country );
|
|
2152
|
+
WC()->customer->set_shipping_state( $state );
|
|
2153
|
+
WC()->customer->set_shipping_city( $city );
|
|
2154
|
+
WC()->customer->set_shipping_postcode( $postcode );
|
|
2155
|
+
WC()->customer->save();
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
WC()->shipping()->reset_shipping();
|
|
2159
|
+
WC()->cart->calculate_shipping();
|
|
2160
|
+
WC()->cart->calculate_totals();
|
|
2161
|
+
|
|
2162
|
+
$packages = WC()->shipping()->get_packages();
|
|
2163
|
+
$rates_list = array();
|
|
2164
|
+
$chosen_method = WC()->session ? WC()->session->get( 'chosen_shipping_methods' ) : array();
|
|
2165
|
+
$chosen_id = ! empty( $chosen_method[0] ) ? $chosen_method[0] : '';
|
|
2166
|
+
|
|
2167
|
+
if ( ! empty( $packages ) && is_array( $packages ) ) {
|
|
2168
|
+
foreach ( $packages as $i => $package ) {
|
|
2169
|
+
if ( ! empty( $package['rates'] ) ) {
|
|
2170
|
+
foreach ( $package['rates'] as $rate_id => $rate ) {
|
|
2171
|
+
$rates_list[] = array(
|
|
2172
|
+
'id' => $rate->get_id(),
|
|
2173
|
+
'method_id' => $rate->get_method_id(),
|
|
2174
|
+
'instance_id' => $rate->get_instance_id(),
|
|
2175
|
+
'label' => $rate->get_label(),
|
|
2176
|
+
'title' => $rate->get_label(),
|
|
2177
|
+
'cost' => floatval( $rate->get_cost() ),
|
|
2178
|
+
'price' => number_format( floatval( $rate->get_cost() ), 2, '.', '' ),
|
|
2179
|
+
'selected' => ( $chosen_id === $rate->get_id() ),
|
|
2180
|
+
);
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
if ( empty( $rates_list ) ) {
|
|
2187
|
+
$rates_list = array(
|
|
2188
|
+
array(
|
|
2189
|
+
'id' => 'flat_rate',
|
|
2190
|
+
'method_id' => 'flat_rate',
|
|
2191
|
+
'label' => 'Standard Flat Rate',
|
|
2192
|
+
'title' => 'Standard Flat Rate',
|
|
2193
|
+
'cost' => 10.00,
|
|
2194
|
+
'price' => '10.00',
|
|
2195
|
+
'selected' => true,
|
|
2196
|
+
),
|
|
2197
|
+
array(
|
|
2198
|
+
'id' => 'free_shipping',
|
|
2199
|
+
'method_id' => 'free_shipping',
|
|
2200
|
+
'label' => 'Free Shipping (Over $100)',
|
|
2201
|
+
'title' => 'Free Shipping',
|
|
2202
|
+
'cost' => 0.00,
|
|
2203
|
+
'price' => '0.00',
|
|
2204
|
+
'selected' => false,
|
|
2205
|
+
),
|
|
2206
|
+
array(
|
|
2207
|
+
'id' => 'local_pickup',
|
|
2208
|
+
'method_id' => 'local_pickup',
|
|
2209
|
+
'label' => 'Local Pickup',
|
|
2210
|
+
'title' => 'Local Pickup',
|
|
2211
|
+
'cost' => 0.00,
|
|
2212
|
+
'price' => '0.00',
|
|
2213
|
+
'selected' => false,
|
|
2214
|
+
),
|
|
2215
|
+
);
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
return rest_ensure_response( array(
|
|
2219
|
+
'rates' => $rates_list,
|
|
2220
|
+
'chosenMethod' => $chosen_id ?: $rates_list[0]['id'],
|
|
2221
|
+
'totals' => forgewp_format_cart_response(),
|
|
2222
|
+
) );
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
function forgewp_rest_get_checkout_gateways( $request ) {
|
|
2226
|
+
$gateways_list = array();
|
|
2227
|
+
|
|
2228
|
+
if ( function_exists( 'WC' ) && WC()->payment_gateways() ) {
|
|
2229
|
+
$available = WC()->payment_gateways()->get_available_payment_gateways();
|
|
2230
|
+
if ( ! empty( $available ) ) {
|
|
2231
|
+
foreach ( $available as $id => $gateway ) {
|
|
2232
|
+
$gateways_list[] = array(
|
|
2233
|
+
'id' => $id,
|
|
2234
|
+
'title' => $gateway->get_title() ?: $gateway->get_method_title(),
|
|
2235
|
+
'description' => $gateway->get_description(),
|
|
2236
|
+
'icon' => $gateway->get_icon(),
|
|
2237
|
+
'supports' => method_exists( $gateway, 'supports' ) ? array( 'products' ) : array(),
|
|
2238
|
+
);
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
if ( empty( $gateways_list ) ) {
|
|
2244
|
+
$gateways_list = array(
|
|
2245
|
+
array(
|
|
2246
|
+
'id' => 'stripe',
|
|
2247
|
+
'title' => 'Credit Card (Stripe)',
|
|
2248
|
+
'description' => 'Pay securely with your credit card.',
|
|
2249
|
+
'icon' => '',
|
|
2250
|
+
'supports' => array( 'products' ),
|
|
2251
|
+
),
|
|
2252
|
+
array(
|
|
2253
|
+
'id' => 'paypal',
|
|
2254
|
+
'title' => 'PayPal',
|
|
2255
|
+
'description' => 'Pay securely using your PayPal balance or bank card.',
|
|
2256
|
+
'icon' => '',
|
|
2257
|
+
'supports' => array( 'products' ),
|
|
2258
|
+
),
|
|
2259
|
+
array(
|
|
2260
|
+
'id' => 'cod',
|
|
2261
|
+
'title' => 'Cash on Delivery',
|
|
2262
|
+
'description' => 'Pay in cash upon delivery of your order.',
|
|
2263
|
+
'icon' => '',
|
|
2264
|
+
'supports' => array( 'products' ),
|
|
2265
|
+
),
|
|
2266
|
+
array(
|
|
2267
|
+
'id' => 'bacs',
|
|
2268
|
+
'title' => 'Direct Bank Transfer',
|
|
2269
|
+
'description' => 'Make your payment directly into our bank account.',
|
|
2270
|
+
'icon' => '',
|
|
2271
|
+
'supports' => array( 'products' ),
|
|
2272
|
+
),
|
|
2273
|
+
);
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
return rest_ensure_response( array(
|
|
2277
|
+
'gateways' => $gateways_list,
|
|
2278
|
+
) );
|
|
2279
|
+
}
|
|
2280
|
+
|
|
2281
|
+
function forgewp_rest_process_checkout( $request ) {
|
|
2282
|
+
if ( ! forgewp_ensure_wc_cart() ) {
|
|
2283
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
2284
|
+
}
|
|
2285
|
+
|
|
2286
|
+
$params = $request->get_json_params();
|
|
2287
|
+
if ( empty( $params ) ) {
|
|
2288
|
+
$params = $request->get_params();
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
$cart_contents = WC()->cart->get_cart();
|
|
2292
|
+
if ( empty( $cart_contents ) ) {
|
|
2293
|
+
return new WP_Error( 'cart_empty', 'Cannot checkout with an empty cart', array( 'status' => 400 ) );
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2296
|
+
$user_id = get_current_user_id();
|
|
2297
|
+
$billing = ! empty( $params['billing_address'] ) && is_array( $params['billing_address'] ) ? $params['billing_address'] : ( ! empty( $params['billing'] ) && is_array( $params['billing'] ) ? $params['billing'] : array() );
|
|
2298
|
+
$shipping = ! empty( $params['shipping_address'] ) && is_array( $params['shipping_address'] ) ? $params['shipping_address'] : ( ! empty( $params['shipping'] ) && is_array( $params['shipping'] ) ? $params['shipping'] : $billing );
|
|
2299
|
+
$payment_method = ! empty( $params['payment_method'] ) ? sanitize_text_field( $params['payment_method'] ) : 'cod';
|
|
2300
|
+
$customer_note = ! empty( $params['customer_note'] ) ? sanitize_textarea_field( $params['customer_note'] ) : '';
|
|
2301
|
+
|
|
2302
|
+
$order = wc_create_order( array(
|
|
2303
|
+
'customer_id' => $user_id,
|
|
2304
|
+
'customer_note' => $customer_note,
|
|
2305
|
+
) );
|
|
2306
|
+
|
|
2307
|
+
if ( is_wp_error( $order ) || ! $order ) {
|
|
2308
|
+
return new WP_Error( 'order_creation_failed', 'Failed to create order. Please try again.', array( 'status' => 500 ) );
|
|
2309
|
+
}
|
|
2310
|
+
|
|
2311
|
+
foreach ( $cart_contents as $cart_item_key => $values ) {
|
|
2312
|
+
$item_id = $order->add_product(
|
|
2313
|
+
$values['data'],
|
|
2314
|
+
$values['quantity'],
|
|
2315
|
+
array(
|
|
2316
|
+
'variation' => ! empty( $values['variation'] ) ? $values['variation'] : array(),
|
|
2317
|
+
'subtotal' => $values['line_subtotal'],
|
|
2318
|
+
'total' => $values['line_total'],
|
|
2319
|
+
)
|
|
2320
|
+
);
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
$order->set_address( $billing, 'billing' );
|
|
2324
|
+
$order->set_address( $shipping, 'shipping' );
|
|
2325
|
+
$order->set_payment_method( $payment_method );
|
|
2326
|
+
|
|
2327
|
+
// Apply applied coupons to order
|
|
2328
|
+
$applied_coupons = WC()->cart->get_applied_coupons();
|
|
2329
|
+
if ( ! empty( $applied_coupons ) ) {
|
|
2330
|
+
foreach ( $applied_coupons as $coupon_code ) {
|
|
2331
|
+
$order->apply_coupon( $coupon_code );
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
$order->calculate_totals();
|
|
2336
|
+
$order->update_status( 'processing', 'Order placed via ForgeWP Headless API' );
|
|
2337
|
+
|
|
2338
|
+
// Clear cart after successful order creation
|
|
2339
|
+
WC()->cart->empty_cart();
|
|
2340
|
+
forgewp_save_wc_cart();
|
|
2341
|
+
|
|
2342
|
+
return rest_ensure_response( array(
|
|
2343
|
+
'success' => true,
|
|
2344
|
+
'orderId' => $order->get_id(),
|
|
2345
|
+
'orderKey' => $order->get_order_key(),
|
|
2346
|
+
'orderNumber' => $order->get_order_number(),
|
|
2347
|
+
'status' => $order->get_status(),
|
|
2348
|
+
'total' => $order->get_total(),
|
|
2349
|
+
'currency' => $order->get_currency(),
|
|
2350
|
+
'redirectUrl' => $order->get_checkout_order_received_url(),
|
|
2351
|
+
) );
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
function forgewp_rest_get_customer_orders( $request ) {
|
|
2355
|
+
$user_id = get_current_user_id();
|
|
2356
|
+
if ( ! $user_id && function_exists( 'forgewp_validate_jwt_token' ) ) {
|
|
2357
|
+
$auth_header = isset( $_SERVER['HTTP_AUTHORIZATION'] ) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
|
|
2358
|
+
if ( $auth_header && preg_match( '/Bearer\s+(\S+)/i', $auth_header, $matches ) ) {
|
|
2359
|
+
$user_id = forgewp_validate_jwt_token( $matches[1] );
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
|
|
2363
|
+
if ( ! $user_id ) {
|
|
2364
|
+
return rest_ensure_response( array(
|
|
2365
|
+
'orders' => array(),
|
|
2366
|
+
'total' => 0,
|
|
2367
|
+
) );
|
|
2368
|
+
}
|
|
2369
|
+
|
|
2370
|
+
if ( ! function_exists( 'wc_get_orders' ) ) {
|
|
2371
|
+
return rest_ensure_response( array( 'orders' => array(), 'total' => 0 ) );
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
$customer_orders = wc_get_orders( array(
|
|
2375
|
+
'customer_id' => $user_id,
|
|
2376
|
+
'limit' => 50,
|
|
2377
|
+
'orderby' => 'date',
|
|
2378
|
+
'order' => 'DESC',
|
|
2379
|
+
) );
|
|
2380
|
+
|
|
2381
|
+
$formatted_orders = array();
|
|
2382
|
+
foreach ( $customer_orders as $order ) {
|
|
2383
|
+
$items = array();
|
|
2384
|
+
foreach ( $order->get_items() as $item_id => $item ) {
|
|
2385
|
+
$product = $item->get_product();
|
|
2386
|
+
$image_url = '';
|
|
2387
|
+
if ( $product ) {
|
|
2388
|
+
$img_id = $product->get_image_id();
|
|
2389
|
+
if ( $img_id ) {
|
|
2390
|
+
$image_url = wp_get_attachment_image_url( $img_id, 'medium' ) ?: wp_get_attachment_url( $img_id );
|
|
2391
|
+
}
|
|
2392
|
+
if ( ! $image_url ) {
|
|
2393
|
+
$image_url = get_post_meta( $product->get_id(), '_forgewp_image', true );
|
|
2394
|
+
}
|
|
2395
|
+
}
|
|
2396
|
+
if ( ! $image_url ) {
|
|
2397
|
+
$image_url = wc_placeholder_img_src( 'medium' );
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
$items[] = array(
|
|
2401
|
+
'id' => $item_id,
|
|
2402
|
+
'productId' => $item->get_product_id(),
|
|
2403
|
+
'title' => $item->get_name(),
|
|
2404
|
+
'name' => $item->get_name(),
|
|
2405
|
+
'qty' => $item->get_quantity(),
|
|
2406
|
+
'quantity' => $item->get_quantity(),
|
|
2407
|
+
'total' => wc_price( $item->get_total(), array( 'currency' => $order->get_currency() ) ),
|
|
2408
|
+
'price' => floatval( $item->get_total() ),
|
|
2409
|
+
'image' => $image_url,
|
|
2410
|
+
);
|
|
2411
|
+
}
|
|
2412
|
+
|
|
2413
|
+
$formatted_orders[] = array(
|
|
2414
|
+
'id' => $order->get_id(),
|
|
2415
|
+
'orderNumber' => $order->get_order_number(),
|
|
2416
|
+
'date' => $order->get_date_created() ? $order->get_date_created()->date_i18n( get_option( 'date_format' ) ) : '',
|
|
2417
|
+
'status' => $order->get_status(),
|
|
2418
|
+
'total' => wc_price( $order->get_total(), array( 'currency' => $order->get_currency() ) ),
|
|
2419
|
+
'totalAmount' => floatval( $order->get_total() ),
|
|
2420
|
+
'currency' => $order->get_currency(),
|
|
2421
|
+
'itemsCount' => $order->get_item_count(),
|
|
2422
|
+
'items' => $items,
|
|
2423
|
+
'viewUrl' => $order->get_view_order_url(),
|
|
2424
|
+
);
|
|
2425
|
+
}
|
|
2426
|
+
|
|
2427
|
+
return rest_ensure_response( array(
|
|
2428
|
+
'orders' => $formatted_orders,
|
|
2429
|
+
'total' => count( $formatted_orders ),
|
|
2430
|
+
) );
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
function forgewp_rest_get_customer_order_detail( $request ) {
|
|
2434
|
+
$user_id = get_current_user_id();
|
|
2435
|
+
$order_id = intval( $request['id'] );
|
|
2436
|
+
|
|
2437
|
+
if ( ! function_exists( 'wc_get_order' ) ) {
|
|
2438
|
+
return new WP_Error( 'wc_unavailable', 'WooCommerce is not available', array( 'status' => 503 ) );
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
$order = wc_get_order( $order_id );
|
|
2442
|
+
if ( ! $order ) {
|
|
2443
|
+
return new WP_Error( 'order_not_found', 'Order not found', array( 'status' => 404 ) );
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
if ( $order->get_customer_id() && intval( $order->get_customer_id() ) !== intval( $user_id ) && ! current_user_can( 'manage_woocommerce' ) ) {
|
|
2447
|
+
return new WP_Error( 'forbidden', 'You do not have permission to view this order', array( 'status' => 403 ) );
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
$items = array();
|
|
2451
|
+
foreach ( $order->get_items() as $item_id => $item ) {
|
|
2452
|
+
$product = $item->get_product();
|
|
2453
|
+
$image_url = '';
|
|
2454
|
+
if ( $product ) {
|
|
2455
|
+
$img_id = $product->get_image_id();
|
|
2456
|
+
if ( $img_id ) {
|
|
2457
|
+
$image_url = wp_get_attachment_image_url( $img_id, 'medium' ) ?: wp_get_attachment_url( $img_id );
|
|
2458
|
+
}
|
|
2459
|
+
if ( ! $image_url ) {
|
|
2460
|
+
$image_url = get_post_meta( $product->get_id(), '_forgewp_image', true );
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
if ( ! $image_url ) {
|
|
2464
|
+
$image_url = wc_placeholder_img_src( 'medium' );
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
$items[] = array(
|
|
2468
|
+
'id' => $item_id,
|
|
2469
|
+
'productId' => $item->get_product_id(),
|
|
2470
|
+
'name' => $item->get_name(),
|
|
2471
|
+
'quantity' => $item->get_quantity(),
|
|
2472
|
+
'subtotal' => floatval( $item->get_subtotal() ),
|
|
2473
|
+
'total' => floatval( $item->get_total() ),
|
|
2474
|
+
'image' => $image_url,
|
|
2475
|
+
);
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
return rest_ensure_response( array(
|
|
2479
|
+
'id' => $order->get_id(),
|
|
2480
|
+
'orderNumber' => $order->get_order_number(),
|
|
2481
|
+
'date' => $order->get_date_created() ? $order->get_date_created()->date_i18n( get_option( 'date_format' ) ) : '',
|
|
2482
|
+
'status' => $order->get_status(),
|
|
2483
|
+
'total' => floatval( $order->get_total() ),
|
|
2484
|
+
'subtotal' => floatval( $order->get_subtotal() ),
|
|
2485
|
+
'tax' => floatval( $order->get_total_tax() ),
|
|
2486
|
+
'shipping' => floatval( $order->get_shipping_total() ),
|
|
2487
|
+
'discount' => floatval( $order->get_discount_total() ),
|
|
2488
|
+
'currency' => $order->get_currency(),
|
|
2489
|
+
'items' => $items,
|
|
2490
|
+
'billing' => $order->get_address( 'billing' ),
|
|
2491
|
+
'shipping' => $order->get_address( 'shipping' ),
|
|
2492
|
+
) );
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
function forgewp_rest_get_customer_downloads( $request ) {
|
|
2496
|
+
$user_id = get_current_user_id();
|
|
2497
|
+
if ( ! $user_id && function_exists( 'forgewp_validate_jwt_token' ) ) {
|
|
2498
|
+
$auth_header = isset( $_SERVER['HTTP_AUTHORIZATION'] ) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
|
|
2499
|
+
if ( $auth_header && preg_match( '/Bearer\s+(\S+)/i', $auth_header, $matches ) ) {
|
|
2500
|
+
$user_id = forgewp_validate_jwt_token( $matches[1] );
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
|
|
2504
|
+
if ( ! $user_id || ! function_exists( 'wc_get_customer_available_downloads' ) ) {
|
|
2505
|
+
return rest_ensure_response( array( 'downloads' => array() ) );
|
|
2506
|
+
}
|
|
2507
|
+
|
|
2508
|
+
$raw_downloads = wc_get_customer_available_downloads( $user_id );
|
|
2509
|
+
$downloads = array();
|
|
2510
|
+
|
|
2511
|
+
foreach ( $raw_downloads as $dl ) {
|
|
2512
|
+
$downloads[] = array(
|
|
2513
|
+
'id' => ! empty( $dl['download_id'] ) ? $dl['download_id'] : ( ! empty( $dl['id'] ) ? $dl['id'] : '' ),
|
|
2514
|
+
'name' => ! empty( $dl['download_name'] ) ? $dl['download_name'] : ( ! empty( $dl['product_name'] ) ? $dl['product_name'] : 'Download' ),
|
|
2515
|
+
'productName' => ! empty( $dl['product_name'] ) ? $dl['product_name'] : '',
|
|
2516
|
+
'url' => ! empty( $dl['download_url'] ) ? $dl['download_url'] : '',
|
|
2517
|
+
'downloadsRemaining' => isset( $dl['downloads_remaining'] ) ? $dl['downloads_remaining'] : 'Unlimited',
|
|
2518
|
+
'accessExpires' => ! empty( $dl['access_expires'] ) ? $dl['access_expires'] : 'Never',
|
|
2519
|
+
);
|
|
2520
|
+
}
|
|
2521
|
+
|
|
2522
|
+
return rest_ensure_response( array(
|
|
2523
|
+
'downloads' => $downloads,
|
|
2524
|
+
) );
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2527
|
+
function forgewp_rest_get_wishlist( $request ) {
|
|
2528
|
+
$user_id = get_current_user_id();
|
|
2529
|
+
if ( ! $user_id && function_exists( 'forgewp_validate_jwt_token' ) ) {
|
|
2530
|
+
$auth_header = isset( $_SERVER['HTTP_AUTHORIZATION'] ) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
|
|
2531
|
+
if ( $auth_header && preg_match( '/Bearer\s+(\S+)/i', $auth_header, $matches ) ) {
|
|
2532
|
+
$user_id = forgewp_validate_jwt_token( $matches[1] );
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
|
|
2536
|
+
if ( ! $user_id ) {
|
|
2537
|
+
return rest_ensure_response( array( 'wishlist' => array() ) );
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2540
|
+
$saved = get_user_meta( $user_id, '_forgewp_wishlist', true );
|
|
2541
|
+
$wishlist = ( is_array( $saved ) ) ? array_values( array_map( 'intval', $saved ) ) : array();
|
|
2542
|
+
|
|
2543
|
+
return rest_ensure_response( array(
|
|
2544
|
+
'wishlist' => $wishlist,
|
|
2545
|
+
) );
|
|
2546
|
+
}
|
|
2547
|
+
|
|
2548
|
+
function forgewp_rest_toggle_wishlist( $request ) {
|
|
2549
|
+
$user_id = get_current_user_id();
|
|
2550
|
+
if ( ! $user_id && function_exists( 'forgewp_validate_jwt_token' ) ) {
|
|
2551
|
+
$auth_header = isset( $_SERVER['HTTP_AUTHORIZATION'] ) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
|
|
2552
|
+
if ( $auth_header && preg_match( '/Bearer\s+(\S+)/i', $auth_header, $matches ) ) {
|
|
2553
|
+
$user_id = forgewp_validate_jwt_token( $matches[1] );
|
|
2554
|
+
}
|
|
2555
|
+
}
|
|
2556
|
+
|
|
2557
|
+
if ( ! $user_id ) {
|
|
2558
|
+
return new WP_Error( 'unauthorized', 'User must be logged in to sync wishlist', array( 'status' => 401 ) );
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
$params = $request->get_json_params() ?: $request->get_params();
|
|
2562
|
+
$product_id = intval( ! empty( $params['id'] ) ? $params['id'] : ( ! empty( $params['productId'] ) ? $params['productId'] : 0 ) );
|
|
2563
|
+
|
|
2564
|
+
if ( ! $product_id ) {
|
|
2565
|
+
return new WP_Error( 'missing_id', 'Product ID is required', array( 'status' => 400 ) );
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2568
|
+
$saved = get_user_meta( $user_id, '_forgewp_wishlist', true );
|
|
2569
|
+
$wishlist = is_array( $saved ) ? array_map( 'intval', $saved ) : array();
|
|
2570
|
+
|
|
2571
|
+
if ( in_array( $product_id, $wishlist, true ) ) {
|
|
2572
|
+
$wishlist = array_values( array_diff( $wishlist, array( $product_id ) ) );
|
|
2573
|
+
$is_wishlisted = false;
|
|
2574
|
+
} else {
|
|
2575
|
+
$wishlist[] = $product_id;
|
|
2576
|
+
$is_wishlisted = true;
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
update_user_meta( $user_id, '_forgewp_wishlist', $wishlist );
|
|
2580
|
+
|
|
2581
|
+
return rest_ensure_response( array(
|
|
2582
|
+
'success' => true,
|
|
2583
|
+
'isWishlisted' => $is_wishlisted,
|
|
2584
|
+
'wishlist' => $wishlist,
|
|
2585
|
+
) );
|
|
2586
|
+
}
|
|
2587
|
+
|
|
2588
|
+
function forgewp_rest_sync_wishlist( $request ) {
|
|
2589
|
+
$user_id = get_current_user_id();
|
|
2590
|
+
if ( ! $user_id && function_exists( 'forgewp_validate_jwt_token' ) ) {
|
|
2591
|
+
$auth_header = isset( $_SERVER['HTTP_AUTHORIZATION'] ) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
|
|
2592
|
+
if ( $auth_header && preg_match( '/Bearer\s+(\S+)/i', $auth_header, $matches ) ) {
|
|
2593
|
+
$user_id = forgewp_validate_jwt_token( $matches[1] );
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
|
|
2597
|
+
if ( ! $user_id ) {
|
|
2598
|
+
return new WP_Error( 'unauthorized', 'User must be logged in to sync wishlist', array( 'status' => 401 ) );
|
|
2599
|
+
}
|
|
2600
|
+
|
|
2601
|
+
$params = $request->get_json_params() ?: $request->get_params();
|
|
2602
|
+
$items = ! empty( $params['items'] ) && is_array( $params['items'] ) ? array_map( 'intval', $params['items'] ) : array();
|
|
2603
|
+
|
|
2604
|
+
$saved = get_user_meta( $user_id, '_forgewp_wishlist', true );
|
|
2605
|
+
$existing = is_array( $saved ) ? array_map( 'intval', $saved ) : array();
|
|
2606
|
+
|
|
2607
|
+
$merged = array_values( array_unique( array_merge( $existing, $items ) ) );
|
|
2608
|
+
update_user_meta( $user_id, '_forgewp_wishlist', $merged );
|
|
2609
|
+
|
|
2610
|
+
return rest_ensure_response( array(
|
|
2611
|
+
'success' => true,
|
|
2612
|
+
'wishlist' => $merged,
|
|
2613
|
+
) );
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
function forgewp_rest_query_products( $request ) {
|
|
2617
|
+
$params = $request->get_params();
|
|
2618
|
+
|
|
2619
|
+
$page = max( 1, intval( ! empty( $params['page'] ) ? $params['page'] : 1 ) );
|
|
2620
|
+
$per_page = min( 100, max( 1, intval( ! empty( $params['per_page'] ) ? $params['per_page'] : 12 ) ) );
|
|
2621
|
+
$search = ! empty( $params['s'] ) ? sanitize_text_field( $params['s'] ) : ( ! empty( $params['search'] ) ? sanitize_text_field( $params['search'] ) : '' );
|
|
2622
|
+
$category = ! empty( $params['category'] ) ? sanitize_text_field( $params['category'] ) : ( ! empty( $params['product_cat'] ) ? sanitize_text_field( $params['product_cat'] ) : '' );
|
|
2623
|
+
$tag = ! empty( $params['tag'] ) ? sanitize_text_field( $params['tag'] ) : ( ! empty( $params['product_tag'] ) ? sanitize_text_field( $params['product_tag'] ) : '' );
|
|
2624
|
+
$sort_by = ! empty( $params['orderby'] ) ? sanitize_text_field( $params['orderby'] ) : 'date';
|
|
2625
|
+
|
|
2626
|
+
$args = array(
|
|
2627
|
+
'post_type' => 'product',
|
|
2628
|
+
'post_status' => 'publish',
|
|
2629
|
+
'paged' => $page,
|
|
2630
|
+
'posts_per_page' => $per_page,
|
|
2631
|
+
);
|
|
2632
|
+
|
|
2633
|
+
if ( ! empty( $search ) ) {
|
|
2634
|
+
$args['s'] = $search;
|
|
2635
|
+
}
|
|
2636
|
+
|
|
2637
|
+
$tax_queries = array();
|
|
2638
|
+
if ( ! empty( $category ) ) {
|
|
2639
|
+
$tax_queries[] = array(
|
|
2640
|
+
'taxonomy' => 'product_cat',
|
|
2641
|
+
'field' => is_numeric( $category ) ? 'term_id' : 'slug',
|
|
2642
|
+
'terms' => is_numeric( $category ) ? intval( $category ) : $category,
|
|
2643
|
+
);
|
|
2644
|
+
}
|
|
2645
|
+
if ( ! empty( $tag ) ) {
|
|
2646
|
+
$tax_queries[] = array(
|
|
2647
|
+
'taxonomy' => 'product_tag',
|
|
2648
|
+
'field' => is_numeric( $tag ) ? 'term_id' : 'slug',
|
|
2649
|
+
'terms' => is_numeric( $tag ) ? intval( $tag ) : $tag,
|
|
2650
|
+
);
|
|
2651
|
+
}
|
|
2652
|
+
if ( ! empty( $tax_queries ) ) {
|
|
2653
|
+
$tax_queries['relation'] = 'AND';
|
|
2654
|
+
$args['tax_query'] = $tax_queries;
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
$meta_queries = array();
|
|
2658
|
+
if ( isset( $params['min_price'] ) && is_numeric( $params['min_price'] ) ) {
|
|
2659
|
+
$meta_queries[] = array(
|
|
2660
|
+
'key' => '_price',
|
|
2661
|
+
'value' => floatval( $params['min_price'] ),
|
|
2662
|
+
'compare' => '>=',
|
|
2663
|
+
'type' => 'NUMERIC',
|
|
2664
|
+
);
|
|
2665
|
+
}
|
|
2666
|
+
if ( isset( $params['max_price'] ) && is_numeric( $params['max_price'] ) ) {
|
|
2667
|
+
$meta_queries[] = array(
|
|
2668
|
+
'key' => '_price',
|
|
2669
|
+
'value' => floatval( $params['max_price'] ),
|
|
2670
|
+
'compare' => '<=',
|
|
2671
|
+
'type' => 'NUMERIC',
|
|
2672
|
+
);
|
|
2673
|
+
}
|
|
2674
|
+
if ( ! empty( $meta_queries ) ) {
|
|
2675
|
+
$meta_queries['relation'] = 'AND';
|
|
2676
|
+
$args['meta_query'] = $meta_queries;
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
switch ( $sort_by ) {
|
|
2680
|
+
case 'price':
|
|
2681
|
+
$args['orderby'] = 'meta_value_num';
|
|
2682
|
+
$args['meta_key'] = '_price';
|
|
2683
|
+
$args['order'] = 'ASC';
|
|
2684
|
+
break;
|
|
2685
|
+
case 'price-desc':
|
|
2686
|
+
$args['orderby'] = 'meta_value_num';
|
|
2687
|
+
$args['meta_key'] = '_price';
|
|
2688
|
+
$args['order'] = 'DESC';
|
|
2689
|
+
break;
|
|
2690
|
+
case 'popularity':
|
|
2691
|
+
$args['orderby'] = 'meta_value_num';
|
|
2692
|
+
$args['meta_key'] = 'total_sales';
|
|
2693
|
+
$args['order'] = 'DESC';
|
|
2694
|
+
break;
|
|
2695
|
+
case 'rating':
|
|
2696
|
+
$args['orderby'] = 'meta_value_num';
|
|
2697
|
+
$args['meta_key'] = '_wc_average_rating';
|
|
2698
|
+
$args['order'] = 'DESC';
|
|
2699
|
+
break;
|
|
2700
|
+
case 'title':
|
|
2701
|
+
$args['orderby'] = 'title';
|
|
2702
|
+
$args['order'] = 'ASC';
|
|
2703
|
+
break;
|
|
2704
|
+
default:
|
|
2705
|
+
$args['orderby'] = 'date';
|
|
2706
|
+
$args['order'] = 'DESC';
|
|
2707
|
+
break;
|
|
2708
|
+
}
|
|
2709
|
+
|
|
2710
|
+
$query = new WP_Query( $args );
|
|
2711
|
+
$products = array();
|
|
2712
|
+
|
|
2713
|
+
if ( $query->have_posts() ) {
|
|
2714
|
+
while ( $query->have_posts() ) {
|
|
2715
|
+
$query->the_post();
|
|
2716
|
+
$prod_id = get_the_ID();
|
|
2717
|
+
$product = function_exists( 'wc_get_product' ) ? wc_get_product( $prod_id ) : null;
|
|
2718
|
+
|
|
2719
|
+
$image_url = '';
|
|
2720
|
+
$images_list = array();
|
|
2721
|
+
if ( $product ) {
|
|
2722
|
+
$img_id = $product->get_image_id();
|
|
2723
|
+
if ( $img_id ) {
|
|
2724
|
+
$image_url = wp_get_attachment_image_url( $img_id, 'full' ) ?: wp_get_attachment_url( $img_id );
|
|
2725
|
+
}
|
|
2726
|
+
$gallery_ids = $product->get_gallery_image_ids();
|
|
2727
|
+
if ( ! empty( $gallery_ids ) && is_array( $gallery_ids ) ) {
|
|
2728
|
+
foreach ( $gallery_ids as $g_id ) {
|
|
2729
|
+
$g_url = wp_get_attachment_image_url( $g_id, 'full' ) ?: wp_get_attachment_url( $g_id );
|
|
2730
|
+
if ( $g_url && ! in_array( $g_url, $images_list, true ) ) {
|
|
2731
|
+
$images_list[] = $g_url;
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
if ( ! $image_url ) {
|
|
2737
|
+
$thumb_id = get_post_thumbnail_id( $prod_id );
|
|
2738
|
+
if ( $thumb_id ) {
|
|
2739
|
+
$image_url = wp_get_attachment_image_url( $thumb_id, 'full' ) ?: wp_get_attachment_url( $thumb_id );
|
|
2740
|
+
}
|
|
2741
|
+
}
|
|
2742
|
+
if ( ! $image_url ) {
|
|
2743
|
+
$image_url = get_post_meta( $prod_id, '_forgewp_image', true );
|
|
2744
|
+
}
|
|
2745
|
+
if ( ! $image_url ) {
|
|
2746
|
+
$meta_images = get_post_meta( $prod_id, '_forgewp_images', true );
|
|
2747
|
+
if ( is_array( $meta_images ) && ! empty( $meta_images[0] ) ) {
|
|
2748
|
+
$image_url = is_string( $meta_images[0] ) ? $meta_images[0] : ( ! empty( $meta_images[0]['src'] ) ? $meta_images[0]['src'] : ( ! empty( $meta_images[0]['url'] ) ? $meta_images[0]['url'] : '' ) );
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
|
|
2752
|
+
if ( $image_url && ! in_array( $image_url, $images_list, true ) ) {
|
|
2753
|
+
array_unshift( $images_list, $image_url );
|
|
2754
|
+
}
|
|
2755
|
+
|
|
2756
|
+
$meta_images = get_post_meta( $prod_id, '_forgewp_images', true );
|
|
2757
|
+
if ( is_array( $meta_images ) ) {
|
|
2758
|
+
foreach ( $meta_images as $m_img ) {
|
|
2759
|
+
$m_url = is_string( $m_img ) ? $m_img : ( ! empty( $m_img['src'] ) ? $m_img['src'] : ( ! empty( $m_img['url'] ) ? $m_img['url'] : '' ) );
|
|
2760
|
+
if ( ! empty( $m_url ) && ! in_array( $m_url, $images_list, true ) ) {
|
|
2761
|
+
$images_list[] = $m_url;
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
|
|
2766
|
+
$cat_terms = get_the_terms( $prod_id, 'product_cat' );
|
|
2767
|
+
$cat_name = ( ! empty( $cat_terms ) && ! is_wp_error( $cat_terms ) ) ? $cat_terms[0]->name : 'Furniture';
|
|
2768
|
+
|
|
2769
|
+
$price = $product ? floatval( $product->get_price() ) : floatval( get_post_meta( $prod_id, '_price', true ) );
|
|
2770
|
+
$reg_price = $product ? floatval( $product->get_regular_price() ) : floatval( get_post_meta( $prod_id, '_regular_price', true ) );
|
|
2771
|
+
|
|
2772
|
+
$products[] = array(
|
|
2773
|
+
'id' => $prod_id,
|
|
2774
|
+
'name' => get_the_title(),
|
|
2775
|
+
'title' => get_the_title(),
|
|
2776
|
+
'slug' => get_post_field( 'post_name', $prod_id ),
|
|
2777
|
+
'category' => $cat_name,
|
|
2778
|
+
'price' => $price,
|
|
2779
|
+
'regular_price' => $reg_price,
|
|
2780
|
+
'on_sale' => $product ? $product->is_on_sale() : ( $reg_price > $price ),
|
|
2781
|
+
'featuredImage' => $image_url,
|
|
2782
|
+
'image' => $image_url,
|
|
2783
|
+
'images' => $images_list,
|
|
2784
|
+
'stock_status' => $product ? $product->get_stock_status() : 'instock',
|
|
2785
|
+
'average_rating'=> $product ? $product->get_average_rating() : '5.0',
|
|
2786
|
+
'rating_count' => $product ? $product->get_rating_count() : 0,
|
|
2787
|
+
);
|
|
2788
|
+
}
|
|
2789
|
+
wp_reset_postdata();
|
|
2790
|
+
}
|
|
2791
|
+
|
|
2792
|
+
return rest_ensure_response( array(
|
|
2793
|
+
'products' => $products,
|
|
2794
|
+
'total' => intval( $query->found_posts ),
|
|
2795
|
+
'totalPages' => intval( $query->max_num_pages ),
|
|
2796
|
+
'page' => $page,
|
|
2797
|
+
) );
|
|
2798
|
+
}
|
|
2799
|
+
|
|
2800
|
+
function forgewp_rest_update_customer_profile( $request ) {
|
|
2801
|
+
$user_id = get_current_user_id();
|
|
2802
|
+
if ( ! $user_id && function_exists( 'forgewp_validate_jwt_token' ) ) {
|
|
2803
|
+
$auth_header = isset( $_SERVER['HTTP_AUTHORIZATION'] ) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
|
|
2804
|
+
if ( $auth_header && preg_match( '/Bearer\s+(\S+)/i', $auth_header, $matches ) ) {
|
|
2805
|
+
$user_id = forgewp_validate_jwt_token( $matches[1] );
|
|
2806
|
+
}
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
if ( ! $user_id ) {
|
|
2810
|
+
return new WP_Error( 'unauthorized', 'User must be logged in to update profile', array( 'status' => 401 ) );
|
|
2811
|
+
}
|
|
2812
|
+
|
|
2813
|
+
$params = $request->get_json_params() ?: $request->get_params();
|
|
2814
|
+
|
|
2815
|
+
$user_data = array( 'ID' => $user_id );
|
|
2816
|
+
|
|
2817
|
+
if ( ! empty( $params['firstName'] ) ) {
|
|
2818
|
+
$first_name = sanitize_text_field( $params['firstName'] );
|
|
2819
|
+
$user_data['first_name'] = $first_name;
|
|
2820
|
+
update_user_meta( $user_id, 'billing_first_name', $first_name );
|
|
2821
|
+
update_user_meta( $user_id, 'shipping_first_name', $first_name );
|
|
2822
|
+
}
|
|
2823
|
+
if ( ! empty( $params['lastName'] ) ) {
|
|
2824
|
+
$last_name = sanitize_text_field( $params['lastName'] );
|
|
2825
|
+
$user_data['last_name'] = $last_name;
|
|
2826
|
+
update_user_meta( $user_id, 'billing_last_name', $last_name );
|
|
2827
|
+
update_user_meta( $user_id, 'shipping_last_name', $last_name );
|
|
2828
|
+
}
|
|
2829
|
+
if ( ! empty( $params['email'] ) && is_email( $params['email'] ) ) {
|
|
2830
|
+
$user_data['user_email'] = sanitize_email( $params['email'] );
|
|
2831
|
+
update_user_meta( $user_id, 'billing_email', $user_data['user_email'] );
|
|
2832
|
+
}
|
|
2833
|
+
if ( isset( $params['phone'] ) ) {
|
|
2834
|
+
$phone = sanitize_text_field( $params['phone'] );
|
|
2835
|
+
update_user_meta( $user_id, 'billing_phone', $phone );
|
|
2836
|
+
}
|
|
2837
|
+
|
|
2838
|
+
if ( ! empty( $params['newPassword'] ) ) {
|
|
2839
|
+
$current_password = ! empty( $params['currentPassword'] ) ? $params['currentPassword'] : '';
|
|
2840
|
+
$user_obj = get_user_by( 'id', $user_id );
|
|
2841
|
+
if ( ! $user_obj || ! wp_check_password( $current_password, $user_obj->user_pass, $user_id ) ) {
|
|
2842
|
+
return new WP_Error( 'invalid_password', 'Current password is incorrect.', array( 'status' => 400 ) );
|
|
2843
|
+
}
|
|
2844
|
+
$user_data['user_pass'] = $params['newPassword'];
|
|
2845
|
+
}
|
|
2846
|
+
|
|
2847
|
+
$updated = wp_update_user( $user_data );
|
|
2848
|
+
if ( is_wp_error( $updated ) ) {
|
|
2849
|
+
return new WP_Error( 'update_failed', $updated->get_error_message(), array( 'status' => 400 ) );
|
|
2850
|
+
}
|
|
2851
|
+
|
|
2852
|
+
$payload = forgewp_get_current_user_hydration_payload();
|
|
2853
|
+
|
|
2854
|
+
return rest_ensure_response( array(
|
|
2855
|
+
'success' => true,
|
|
2856
|
+
'message' => 'Profile updated successfully.',
|
|
2857
|
+
'user' => $payload,
|
|
2858
|
+
) );
|
|
2859
|
+
}
|
|
2860
|
+
|
|
2861
|
+
function forgewp_rest_update_customer_address( $request ) {
|
|
2862
|
+
$user_id = get_current_user_id();
|
|
2863
|
+
if ( ! $user_id && function_exists( 'forgewp_validate_jwt_token' ) ) {
|
|
2864
|
+
$auth_header = isset( $_SERVER['HTTP_AUTHORIZATION'] ) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
|
|
2865
|
+
if ( $auth_header && preg_match( '/Bearer\s+(\S+)/i', $auth_header, $matches ) ) {
|
|
2866
|
+
$user_id = forgewp_validate_jwt_token( $matches[1] );
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
|
|
2870
|
+
if ( ! $user_id ) {
|
|
2871
|
+
return new WP_Error( 'unauthorized', 'User must be logged in to update address', array( 'status' => 401 ) );
|
|
2872
|
+
}
|
|
2873
|
+
|
|
2874
|
+
$params = $request->get_json_params() ?: $request->get_params();
|
|
2875
|
+
|
|
2876
|
+
$name = ! empty( $params['name'] ) ? sanitize_text_field( $params['name'] ) : '';
|
|
2877
|
+
$street = ! empty( $params['street'] ) ? sanitize_text_field( $params['street'] ) : '';
|
|
2878
|
+
$city = ! empty( $params['city'] ) ? sanitize_text_field( $params['city'] ) : '';
|
|
2879
|
+
$postal_code = ! empty( $params['postalCode'] ) ? sanitize_text_field( $params['postalCode'] ) : '';
|
|
2880
|
+
$country = ! empty( $params['country'] ) ? sanitize_text_field( $params['country'] ) : 'US';
|
|
2881
|
+
$phone = ! empty( $params['phone'] ) ? sanitize_text_field( $params['phone'] ) : '';
|
|
2882
|
+
|
|
2883
|
+
$name_parts = explode( ' ', $name, 2 );
|
|
2884
|
+
$first_name = $name_parts[0] ?? '';
|
|
2885
|
+
$last_name = $name_parts[1] ?? '';
|
|
2886
|
+
|
|
2887
|
+
// Update shipping fields
|
|
2888
|
+
update_user_meta( $user_id, 'shipping_first_name', $first_name );
|
|
2889
|
+
update_user_meta( $user_id, 'shipping_last_name', $last_name );
|
|
2890
|
+
update_user_meta( $user_id, 'shipping_address_1', $street );
|
|
2891
|
+
update_user_meta( $user_id, 'shipping_city', $city );
|
|
2892
|
+
update_user_meta( $user_id, 'shipping_postcode', $postal_code );
|
|
2893
|
+
update_user_meta( $user_id, 'shipping_country', $country );
|
|
2894
|
+
update_user_meta( $user_id, 'shipping_phone', $phone );
|
|
2895
|
+
|
|
2896
|
+
// Also update billing fields for convenience
|
|
2897
|
+
update_user_meta( $user_id, 'billing_first_name', $first_name );
|
|
2898
|
+
update_user_meta( $user_id, 'billing_last_name', $last_name );
|
|
2899
|
+
update_user_meta( $user_id, 'billing_address_1', $street );
|
|
2900
|
+
update_user_meta( $user_id, 'billing_city', $city );
|
|
2901
|
+
update_user_meta( $user_id, 'billing_postcode', $postal_code );
|
|
2902
|
+
update_user_meta( $user_id, 'billing_country', $country );
|
|
2903
|
+
if ( ! empty( $phone ) ) {
|
|
2904
|
+
update_user_meta( $user_id, 'billing_phone', $phone );
|
|
2905
|
+
}
|
|
2906
|
+
|
|
2907
|
+
$payload = forgewp_get_current_user_hydration_payload();
|
|
2908
|
+
|
|
2909
|
+
return rest_ensure_response( array(
|
|
2910
|
+
'success' => true,
|
|
2911
|
+
'message' => 'Address saved successfully.',
|
|
2912
|
+
'user' => $payload,
|
|
2913
|
+
) );
|
|
2914
|
+
}
|
|
2915
|
+
|
|
2916
|
+
`;
|
|
2917
|
+
}
|
|
2918
|
+
|
|
2919
|
+
return `
|
|
2920
|
+
${queryEndpointsPhp}
|
|
2921
|
+
${authControllersPhp}
|
|
2922
|
+
`;
|
|
2923
|
+
}
|