@wp-operations/wp-ops 0.2.0 → 0.3.1

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.
Files changed (122) hide show
  1. package/README.md +30 -27
  2. package/bin/wp-app.js +2 -0
  3. package/bin/wp-code.js +2 -0
  4. package/bin/wp-ide.js +2 -0
  5. package/package.json +12 -3
  6. package/src/commands/platform.js +16 -2
  7. package/src/commands/sandbox.js +3 -3
  8. package/src/main.js +10 -4
  9. package/wp-operations/CHANGELOG.md +14 -0
  10. package/wp-operations/README.md +39 -0
  11. package/wp-operations/agents/builder/AGENT.md +15 -0
  12. package/wp-operations/assets/admin.css +631 -0
  13. package/wp-operations/assets/admin.js +614 -0
  14. package/wp-operations/assets/app/app.css +1 -0
  15. package/wp-operations/assets/app/app.js +70 -0
  16. package/wp-operations/assets/app/fonts/inter-medium.woff +0 -0
  17. package/wp-operations/assets/app/fonts/inter-regular.woff +0 -0
  18. package/wp-operations/assets/app/fonts/inter-semibold.woff +0 -0
  19. package/wp-operations/assets/app/login.css +42 -0
  20. package/wp-operations/assets/brand/icon.svg +20 -0
  21. package/wp-operations/assets/brand/mark.svg +19 -0
  22. package/wp-operations/assets/editors/audiobook.css +311 -0
  23. package/wp-operations/assets/editors/audiofile.css +286 -0
  24. package/wp-operations/assets/editors/course.css +701 -0
  25. package/wp-operations/assets/editors/course.js +698 -0
  26. package/wp-operations/assets/editors/faq.css +258 -0
  27. package/wp-operations/assets/editors/faq.js +196 -0
  28. package/wp-operations/assets/editors/interactive.css +220 -0
  29. package/wp-operations/assets/editors/interactive.js +378 -0
  30. package/wp-operations/assets/editors/media-sources.css +3 -0
  31. package/wp-operations/assets/editors/media-sources.js +40 -0
  32. package/wp-operations/assets/editors/open-media.css +114 -0
  33. package/wp-operations/assets/editors/open-media.js +182 -0
  34. package/wp-operations/assets/editors/thumbnails.css +335 -0
  35. package/wp-operations/assets/editors/thumbnails.js +447 -0
  36. package/wp-operations/assets/editors/translator.css +818 -0
  37. package/wp-operations/functions.php +24 -0
  38. package/wp-operations/index.php +14 -0
  39. package/wp-operations/platform.json +1836 -0
  40. package/wp-operations/skills/ai-development-guardrails/SKILL.md +49 -0
  41. package/wp-operations/skills/gutenberg-reference/SKILL.md +45 -0
  42. package/wp-operations/skills/js-tooling-for-themes/SKILL.md +51 -0
  43. package/wp-operations/skills/tailwind-for-wp/SKILL.md +62 -0
  44. package/wp-operations/skills/wp-clean-classic-themes/SKILL.md +112 -0
  45. package/wp-operations/skills/wp-psr4-plugins/SKILL.md +2043 -0
  46. package/wp-operations/skills/wp-security/SKILL.md +90 -0
  47. package/wp-operations/src/Admin.php +78 -0
  48. package/wp-operations/src/App/Access.php +57 -0
  49. package/wp-operations/src/App/Admin.php +442 -0
  50. package/wp-operations/src/App/App.php +157 -0
  51. package/wp-operations/src/App/Apps.php +379 -0
  52. package/wp-operations/src/App/Bundle.php +111 -0
  53. package/wp-operations/src/App/Contents.php +676 -0
  54. package/wp-operations/src/App/Engine.php +554 -0
  55. package/wp-operations/src/App/Github.php +308 -0
  56. package/wp-operations/src/App/Module.php +23 -0
  57. package/wp-operations/src/App/Ops.php +470 -0
  58. package/wp-operations/src/App/Packages.php +289 -0
  59. package/wp-operations/src/App/Rest.php +539 -0
  60. package/wp-operations/src/App/Sandboxes.php +206 -0
  61. package/wp-operations/src/App/Store.php +104 -0
  62. package/wp-operations/src/App/Usage.php +268 -0
  63. package/wp-operations/src/Config.php +249 -0
  64. package/wp-operations/src/Content/Editor.php +223 -0
  65. package/wp-operations/src/Content/Fields.php +681 -0
  66. package/wp-operations/src/Content/Scoring.php +253 -0
  67. package/wp-operations/src/Content/Structure.php +293 -0
  68. package/wp-operations/src/Content/Types.php +150 -0
  69. package/wp-operations/src/Content/Uploads.php +50 -0
  70. package/wp-operations/src/Editors/AudiobookAuthor.php +61 -0
  71. package/wp-operations/src/Editors/AudiobookChapters.php +632 -0
  72. package/wp-operations/src/Editors/AudiobookCover.php +235 -0
  73. package/wp-operations/src/Editors/Audiofile.php +462 -0
  74. package/wp-operations/src/Editors/Course.php +784 -0
  75. package/wp-operations/src/Editors/Ebook.php +242 -0
  76. package/wp-operations/src/Editors/Editors.php +44 -0
  77. package/wp-operations/src/Editors/Faq.php +237 -0
  78. package/wp-operations/src/Editors/Files.php +139 -0
  79. package/wp-operations/src/Editors/Interactive/Builder.php +103 -0
  80. package/wp-operations/src/Editors/Interactive/Card.php +76 -0
  81. package/wp-operations/src/Editors/Interactive/Editor.php +42 -0
  82. package/wp-operations/src/Editors/Interactive/Field.php +272 -0
  83. package/wp-operations/src/Editors/Interactive/Map.php +84 -0
  84. package/wp-operations/src/Editors/Interactive/Models.php +227 -0
  85. package/wp-operations/src/Editors/Interactive/Report.php +59 -0
  86. package/wp-operations/src/Editors/Interactive/Save.php +323 -0
  87. package/wp-operations/src/Editors/Interactive/Scoring.php +244 -0
  88. package/wp-operations/src/Editors/Interactive/Structure.php +195 -0
  89. package/wp-operations/src/Editors/Legal.php +235 -0
  90. package/wp-operations/src/Editors/OpenMedia.php +140 -0
  91. package/wp-operations/src/Editors/OriginalTitle.php +112 -0
  92. package/wp-operations/src/Editors/Sources.php +28 -0
  93. package/wp-operations/src/Editors/Thumbnails/Admin.php +306 -0
  94. package/wp-operations/src/Editors/Thumbnails/Ajax.php +163 -0
  95. package/wp-operations/src/Editors/Thumbnails/Box.php +188 -0
  96. package/wp-operations/src/Editors/Thumbnails/Storage.php +228 -0
  97. package/wp-operations/src/Editors/Translator/Admin.php +913 -0
  98. package/wp-operations/src/Editors/Translator/Api.php +63 -0
  99. package/wp-operations/src/Editors/Translator/Bar.php +83 -0
  100. package/wp-operations/src/Editors/Translator/Fields.php +273 -0
  101. package/wp-operations/src/Editors/Translator/Storage.php +131 -0
  102. package/wp-operations/src/Editors/Translator/Thumbnail.php +215 -0
  103. package/wp-operations/src/Identity.php +104 -0
  104. package/wp-operations/src/Languages.php +45 -0
  105. package/wp-operations/src/Lockdown.php +85 -0
  106. package/wp-operations/src/Modules/Apps/Admin.php +472 -0
  107. package/wp-operations/src/Modules/Apps/Api.php +193 -0
  108. package/wp-operations/src/Modules/Apps/Apps.php +279 -0
  109. package/wp-operations/src/Modules/Apps/Formatters.php +478 -0
  110. package/wp-operations/src/Modules/Apps/Schemes.php +248 -0
  111. package/wp-operations/src/Modules/Apps/Table.php +101 -0
  112. package/wp-operations/src/Modules/Thumbnails.php +68 -0
  113. package/wp-operations/src/Modules/Translations.php +133 -0
  114. package/wp-operations/src/Platform.php +59 -0
  115. package/wp-operations/src/Setup.php +273 -0
  116. package/wp-operations/src/Status.php +99 -0
  117. package/wp-operations/src/Storage/Client.php +168 -0
  118. package/wp-operations/src/Storage/Offload.php +120 -0
  119. package/wp-operations/src/Storage/Settings.php +166 -0
  120. package/wp-operations/src/Storage/Storage.php +35 -0
  121. package/wp-operations/src/Updates.php +151 -0
  122. package/wp-operations/style.css +11 -0
@@ -0,0 +1,206 @@
1
+ <?php
2
+ namespace Platform\App;
3
+
4
+ use Platform\Modules\Apps\Apps as Registry;
5
+
6
+ defined( 'ABSPATH' ) || exit;
7
+
8
+ final class Sandboxes {
9
+
10
+ const LEASES = 'platform_sandbox_leases';
11
+ const TTL = 15 * MINUTE_IN_SECONDS;
12
+
13
+ public static function all(): array {
14
+ return array_values( array_map( [ __CLASS__, 'normalize' ], (array) Ops::settings()['sandboxes'] ) );
15
+ }
16
+
17
+ private static function normalize( $sandbox ): array {
18
+ $sandbox = (array) $sandbox;
19
+
20
+ return [
21
+ 'key' => sanitize_key( (string) ( $sandbox['key'] ?? '' ) ),
22
+ 'label' => (string) ( $sandbox['label'] ?? '' ),
23
+ 'url' => untrailingslashit( (string) ( $sandbox['url'] ?? '' ) ),
24
+ 'health' => '/' . ltrim( (string) ( $sandbox['health'] ?? '/' ), '/' ),
25
+ 'preview' => '/' . ltrim( (string) ( $sandbox['preview'] ?? '/{kind}/{slug}/' ), '/' ),
26
+ 'token_constant' => preg_replace( '/[^A-Z0-9_]/', '', strtoupper( (string) ( $sandbox['token_constant'] ?? '' ) ) ),
27
+ 'enabled' => ! empty( $sandbox['enabled'] ),
28
+ ];
29
+ }
30
+
31
+ public static function save( array $input ) {
32
+ $sandbox = self::normalize( $input );
33
+ $url = esc_url_raw( $sandbox['url'], [ 'https', 'http' ] );
34
+
35
+ if ( '' === $url || '' === trim( $sandbox['label'] ) ) {
36
+ return new \WP_Error( 'sandbox', 'A sandbox needs a name and a runtime URL.' );
37
+ }
38
+
39
+ $sandbox['label'] = sanitize_text_field( $sandbox['label'] );
40
+ $sandbox['url'] = untrailingslashit( $url );
41
+ $sandbox['key'] = $sandbox['key'] ?: sanitize_key( sanitize_title( $sandbox['label'] ) );
42
+ $settings = Ops::settings();
43
+ $list = self::all();
44
+ $found = false;
45
+
46
+ foreach ( $list as $index => $item ) {
47
+ if ( $item['key'] === $sandbox['key'] ) {
48
+ $list[ $index ] = $sandbox;
49
+ $found = true;
50
+ }
51
+ }
52
+
53
+ if ( ! $found ) {
54
+ $list[] = $sandbox;
55
+ }
56
+
57
+ $settings['sandboxes'] = $list;
58
+ update_option( Ops::OPTION, $settings, false );
59
+ delete_transient( 'platform_sandbox_health_' . $sandbox['key'] );
60
+
61
+ return $sandbox;
62
+ }
63
+
64
+ public static function remove( string $key ) {
65
+ $settings = Ops::settings();
66
+ $settings['sandboxes'] = array_values( array_filter( self::all(), static fn( array $s ): bool => $s['key'] !== $key ) );
67
+ update_option( Ops::OPTION, $settings, false );
68
+
69
+ $leases = self::leases();
70
+ unset( $leases[ $key ] );
71
+ update_option( self::LEASES, $leases, false );
72
+
73
+ return [ 'ok' => true ];
74
+ }
75
+
76
+ private static function leases(): array {
77
+ $now = time();
78
+
79
+ return array_filter( (array) get_option( self::LEASES, [] ), static fn( $lease ): bool => is_array( $lease ) && (int) ( $lease['until'] ?? 0 ) > $now );
80
+ }
81
+
82
+ public static function check( array $sandbox, bool $fresh = false ): array {
83
+ $key = 'platform_sandbox_health_' . $sandbox['key'];
84
+ $cached = $fresh ? false : get_transient( $key );
85
+
86
+ if ( is_array( $cached ) ) {
87
+ return $cached;
88
+ }
89
+
90
+ $headers = [ 'User-Agent' => 'wp-operations' ];
91
+
92
+ if ( '' !== $sandbox['token_constant'] && defined( $sandbox['token_constant'] ) ) {
93
+ $headers['Authorization'] = 'Bearer ' . (string) constant( $sandbox['token_constant'] );
94
+ }
95
+
96
+ $response = wp_remote_get( $sandbox['url'] . $sandbox['health'], [ 'timeout' => 4, 'redirection' => 2, 'headers' => $headers ] );
97
+ $code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
98
+ $state = [
99
+ 'up' => $code >= 200 && $code < 400,
100
+ 'error' => is_wp_error( $response ) ? $response->get_error_message() : ( $code >= 400 ? 'HTTP ' . $code : '' ),
101
+ 'at' => time(),
102
+ ];
103
+
104
+ set_transient( $key, $state, $state['up'] ? 30 : 15 );
105
+
106
+ return $state;
107
+ }
108
+
109
+ public static function health(): array {
110
+ $leases = self::leases();
111
+ $result = [];
112
+
113
+ foreach ( self::all() as $sandbox ) {
114
+ $state = self::check( $sandbox );
115
+ $app = isset( $leases[ $sandbox['key'] ] ) ? Registry::get( (int) $leases[ $sandbox['key'] ]['app'] ) : null;
116
+
117
+ $result[ $sandbox['key'] ] = $state + [ 'app' => $app ? (string) $app['name'] : '' ];
118
+ }
119
+
120
+ return $result;
121
+ }
122
+
123
+ private static function url( array $sandbox, array $mapping ): string {
124
+ return $sandbox['url'] . strtr(
125
+ $sandbox['preview'],
126
+ [
127
+ '{kind}' => rawurlencode( $mapping['kind'] ),
128
+ '{slug}' => rawurlencode( $mapping['slug'] ),
129
+ '{path}' => implode( '/', array_map( 'rawurlencode', explode( '/', $mapping['path'] ) ) ),
130
+ '{branch}' => rawurlencode( Ops::settings()['branch'] ?: 'main' ),
131
+ ]
132
+ );
133
+ }
134
+
135
+ public static function acquire( int $app_id ) {
136
+ $app = Registry::get( $app_id );
137
+
138
+ if ( ! $app ) {
139
+ return new \WP_Error( 'not_found', 'App not found.', [ 'status' => 404 ] );
140
+ }
141
+
142
+ $list = array_values( array_filter( self::all(), static fn( array $s ): bool => $s['enabled'] ) );
143
+
144
+ if ( ! $list ) {
145
+ return new \WP_Error( 'no_sandbox', 'No sandboxes are set up yet. Add one in Settings → Operations → Sandboxes.', [ 'status' => 409 ] );
146
+ }
147
+
148
+ $mapping = Ops::mapping( $app_id, (string) $app['name'] );
149
+ $leases = self::leases();
150
+ $order = [];
151
+
152
+ foreach ( $list as $sandbox ) {
153
+ $lease = $leases[ $sandbox['key'] ] ?? null;
154
+
155
+ if ( $lease && (int) $lease['app'] === $app_id ) {
156
+ array_unshift( $order, $sandbox );
157
+ } elseif ( ! $lease ) {
158
+ $order[] = $sandbox;
159
+ }
160
+ }
161
+
162
+ $tried = [];
163
+
164
+ foreach ( $order as $sandbox ) {
165
+ $state = self::check( $sandbox );
166
+
167
+ if ( ! $state['up'] ) {
168
+ $tried[] = $sandbox['label'] . ': ' . ( $state['error'] ?: 'offline' );
169
+ continue;
170
+ }
171
+
172
+ $leases[ $sandbox['key'] ] = [ 'app' => $app_id, 'user' => get_current_user_id(), 'until' => time() + self::TTL ];
173
+ update_option( self::LEASES, $leases, false );
174
+
175
+ return [
176
+ 'sandbox' => $sandbox['key'],
177
+ 'label' => $sandbox['label'],
178
+ 'url' => self::url( $sandbox, $mapping ),
179
+ 'until' => gmdate( 'c', time() + self::TTL ),
180
+ 'path' => $mapping['path'],
181
+ ];
182
+ }
183
+
184
+ $busy = count( $list ) - count( $order );
185
+
186
+ return new \WP_Error(
187
+ 'no_sandbox',
188
+ trim( sprintf( 'No sandbox is free right now. %s', $busy ? sprintf( '%d in use by other apps.', $busy ) : '' ) . ( $tried ? ' Offline: ' . implode( '; ', $tried ) . '.' : '' ) ),
189
+ [ 'status' => 503 ]
190
+ );
191
+ }
192
+
193
+ public static function release( int $app_id ): array {
194
+ $leases = self::leases();
195
+
196
+ foreach ( $leases as $key => $lease ) {
197
+ if ( (int) $lease['app'] === $app_id ) {
198
+ unset( $leases[ $key ] );
199
+ }
200
+ }
201
+
202
+ update_option( self::LEASES, $leases, false );
203
+
204
+ return [ 'ok' => true ];
205
+ }
206
+ }
@@ -0,0 +1,104 @@
1
+ <?php
2
+ namespace Platform\App;
3
+
4
+ defined( 'ABSPATH' ) || exit;
5
+
6
+ final class Store {
7
+
8
+ const SHARED = [ 'docs', 'skills', 'agents', 'folders' ];
9
+ const PERSONAL = [ 'connectors', 'recent', 'preferences' ];
10
+ const RICH = [ 'body', 'instructions', 'content' ];
11
+ const SECRET = [ 'token', 'secret', 'auth' ];
12
+
13
+ public static function visible( string $collection ): array {
14
+ return array_map(
15
+ static function ( array $item ): array {
16
+ foreach ( self::SECRET as $key ) {
17
+ if ( ! empty( $item[ $key ] ) ) {
18
+ $item[ $key ] = '•••• ' . substr( (string) $item[ $key ], -4 );
19
+ }
20
+ }
21
+ return $item;
22
+ },
23
+ self::all( $collection )
24
+ );
25
+ }
26
+
27
+ public static function exists( string $collection ): bool {
28
+ return in_array( $collection, array_merge( self::SHARED, self::PERSONAL ), true );
29
+ }
30
+
31
+ public static function all( string $collection ): array {
32
+ $items = in_array( $collection, self::SHARED, true )
33
+ ? get_option( 'platform_' . $collection, [] )
34
+ : get_user_meta( get_current_user_id(), 'platform_' . $collection, true );
35
+
36
+ return is_array( $items ) ? array_values( $items ) : [];
37
+ }
38
+
39
+ public static function put( string $collection, array $item ): array {
40
+ $items = self::all( $collection );
41
+ $item = self::clean( $item );
42
+ $now = current_time( 'mysql', true );
43
+ $id = sanitize_key( (string) ( $item['id'] ?? '' ) );
44
+ $found = false;
45
+
46
+ foreach ( $items as $i => $existing ) {
47
+ if ( $id && ( $existing['id'] ?? '' ) === $id ) {
48
+ foreach ( self::SECRET as $key ) {
49
+ if ( isset( $item[ $key ] ) && 0 === strpos( (string) $item[ $key ], '••••' ) ) {
50
+ unset( $item[ $key ] );
51
+ }
52
+ }
53
+ $items[ $i ] = array_merge( $existing, $item, [ 'id' => $id, 'updated' => $now ] );
54
+ $item = $items[ $i ];
55
+ $found = true;
56
+ }
57
+ }
58
+
59
+ if ( ! $found ) {
60
+ $item = array_merge( $item, [ 'id' => $id ?: strtolower( wp_generate_password( 10, false ) ), 'created' => $now, 'updated' => $now, 'author' => get_current_user_id() ] );
61
+ array_unshift( $items, $item );
62
+ }
63
+
64
+ self::write( $collection, $items );
65
+
66
+ return $item;
67
+ }
68
+
69
+ public static function remove( string $collection, string $id ): void {
70
+ self::write( $collection, array_values( array_filter( self::all( $collection ), static fn( array $item ): bool => ( $item['id'] ?? '' ) !== $id ) ) );
71
+ }
72
+
73
+ public static function replace( string $collection, array $items ): void {
74
+ self::write( $collection, $items );
75
+ }
76
+
77
+ private static function write( string $collection, array $items ): void {
78
+ $items = array_slice( $items, 0, 500 );
79
+
80
+ in_array( $collection, self::SHARED, true )
81
+ ? update_option( 'platform_' . $collection, $items, false )
82
+ : update_user_meta( get_current_user_id(), 'platform_' . $collection, $items );
83
+ }
84
+
85
+ private static function clean( array $data, int $depth = 0 ): array {
86
+ $out = [];
87
+
88
+ foreach ( $data as $key => $value ) {
89
+ $key = is_int( $key ) ? $key : sanitize_key( (string) $key );
90
+
91
+ if ( is_array( $value ) ) {
92
+ $out[ $key ] = $depth < 4 ? self::clean( $value, $depth + 1 ) : [];
93
+ } elseif ( is_bool( $value ) || is_int( $value ) || is_float( $value ) || null === $value ) {
94
+ $out[ $key ] = $value;
95
+ } elseif ( in_array( $key, self::RICH, true ) ) {
96
+ $out[ $key ] = wp_kses_post( (string) $value );
97
+ } else {
98
+ $out[ $key ] = sanitize_textarea_field( (string) $value );
99
+ }
100
+ }
101
+
102
+ return $out;
103
+ }
104
+ }
@@ -0,0 +1,268 @@
1
+ <?php
2
+ namespace Platform\App;
3
+
4
+ use Platform\Platform;
5
+ use Platform\Setup;
6
+
7
+ defined( 'ABSPATH' ) || exit;
8
+
9
+ final class Usage {
10
+
11
+ const PAGE = 'prompt-users';
12
+ const LIMIT = 'platform_limit';
13
+ const ALERT = 'platform_alerted';
14
+ const ALERTS = 'platform_alerts';
15
+
16
+ public static function table(): string {
17
+ return Setup::table( 'prompts' );
18
+ }
19
+
20
+ public static function log( array $entry ): int {
21
+ global $wpdb;
22
+
23
+ $row = [
24
+ 'user_id' => (int) ( $entry['user_id'] ?? get_current_user_id() ),
25
+ 'app_id' => (int) ( $entry['app_id'] ?? 0 ),
26
+ 'kind' => sanitize_key( (string) ( $entry['kind'] ?? 'chat' ) ),
27
+ 'mode' => sanitize_key( (string) ( $entry['mode'] ?? '' ) ),
28
+ 'prompt' => (string) ( $entry['prompt'] ?? '' ),
29
+ 'response' => (string) ( $entry['response'] ?? '' ),
30
+ 'status' => sanitize_key( (string) ( $entry['status'] ?? 'ok' ) ),
31
+ 'error' => substr( (string) ( $entry['error'] ?? '' ), 0, 255 ),
32
+ 'credits' => (float) ( $entry['credits'] ?? 0 ),
33
+ 'tokens_in' => (int) ( $entry['tokens_in'] ?? 0 ),
34
+ 'tokens_out' => (int) ( $entry['tokens_out'] ?? 0 ),
35
+ 'created_at' => current_time( 'mysql', true ),
36
+ ];
37
+
38
+ $wpdb->insert( self::table(), $row );
39
+ $id = (int) $wpdb->insert_id;
40
+
41
+ self::maybe_alert( $row['user_id'] );
42
+
43
+ return $id;
44
+ }
45
+
46
+ public static function find( int $id ): ?array {
47
+ global $wpdb;
48
+
49
+ $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::table() . ' WHERE id = %d', $id ), ARRAY_A );
50
+
51
+ return is_array( $row ) ? $row : null;
52
+ }
53
+
54
+ public static function update( int $id, array $fields ): void {
55
+ global $wpdb;
56
+
57
+ $wpdb->update( self::table(), array_intersect_key( $fields, array_flip( [ 'response', 'status', 'error' ] ) ), [ 'id' => $id ] );
58
+ }
59
+
60
+ public static function month_start(): string {
61
+ return gmdate( 'Y-m-01 00:00:00' );
62
+ }
63
+
64
+ public static function used( int $user_id ): array {
65
+ global $wpdb;
66
+
67
+ $row = $wpdb->get_row(
68
+ $wpdb->prepare( 'SELECT COUNT(*) AS prompts, COALESCE(SUM(credits),0) AS credits, SUM(status = %s) AS errors FROM ' . self::table() . ' WHERE user_id = %d AND created_at >= %s', 'error', $user_id, self::month_start() ),
69
+ ARRAY_A
70
+ );
71
+
72
+ return [
73
+ 'prompts' => (int) ( $row['prompts'] ?? 0 ),
74
+ 'credits' => (float) ( $row['credits'] ?? 0 ),
75
+ 'errors' => (int) ( $row['errors'] ?? 0 ),
76
+ ];
77
+ }
78
+
79
+ public static function limit( int $user_id ): int {
80
+ $value = get_user_meta( $user_id, self::LIMIT, true );
81
+
82
+ return '' === $value ? (int) Module::config( 'usage.monthly_credits', 0 ) : max( 0, (int) $value );
83
+ }
84
+
85
+ public static function cost(): float {
86
+ return (float) Module::config( 'usage.credits_per_prompt', 1 );
87
+ }
88
+
89
+ public static function check( int $user_id ) {
90
+ $limit = self::limit( $user_id );
91
+
92
+ if ( $limit > 0 && self::used( $user_id )['credits'] + self::cost() > $limit ) {
93
+ return new \WP_Error( 'limit_reached', sprintf( 'You have used your %d credits for this month.', $limit ), [ 'status' => 429 ] );
94
+ }
95
+
96
+ return true;
97
+ }
98
+
99
+ public static function summary( int $user_id ): array {
100
+ $used = self::used( $user_id );
101
+ $limit = self::limit( $user_id );
102
+
103
+ return $used + [
104
+ 'limit' => $limit,
105
+ 'percent' => $limit > 0 ? min( 100, round( $used['credits'] / $limit * 100, 1 ) ) : 0,
106
+ 'alert' => (int) Module::config( 'usage.alert_at', 80 ),
107
+ 'resets' => gmdate( 'Y-m-01', strtotime( '+1 month', strtotime( self::month_start() ) ) ),
108
+ ];
109
+ }
110
+
111
+ public static function series( int $days = 30, int $user_id = 0 ): array {
112
+ global $wpdb;
113
+
114
+ $since = gmdate( 'Y-m-d 00:00:00', strtotime( '-' . ( $days - 1 ) . ' days' ) );
115
+ $where = $user_id ? $wpdb->prepare( ' AND user_id = %d', $user_id ) : '';
116
+ $rows = $wpdb->get_results(
117
+ $wpdb->prepare( 'SELECT DATE(created_at) AS day, COUNT(*) AS prompts, COALESCE(SUM(credits),0) AS credits, SUM(status = %s) AS errors FROM ' . self::table() . ' WHERE created_at >= %s' . $where . ' GROUP BY DATE(created_at)', 'error', $since ),
118
+ ARRAY_A
119
+ );
120
+ $by = array_column( (array) $rows, null, 'day' );
121
+ $out = [];
122
+
123
+ for ( $i = $days - 1; $i >= 0; $i-- ) {
124
+ $day = gmdate( 'Y-m-d', strtotime( '-' . $i . ' days' ) );
125
+ $out[] = [
126
+ 'day' => $day,
127
+ 'prompts' => (int) ( $by[ $day ]['prompts'] ?? 0 ),
128
+ 'credits' => (float) ( $by[ $day ]['credits'] ?? 0 ),
129
+ 'errors' => (int) ( $by[ $day ]['errors'] ?? 0 ),
130
+ ];
131
+ }
132
+
133
+ return $out;
134
+ }
135
+
136
+ public static function history( int $app_id, int $user_id, int $limit = 200 ): array {
137
+ global $wpdb;
138
+
139
+ $rows = $wpdb->get_results(
140
+ $wpdb->prepare( 'SELECT id, user_id, kind, mode, prompt, response, status, error, created_at FROM ' . self::table() . ' WHERE app_id = %d AND user_id = %d AND kind = %s ORDER BY id DESC LIMIT %d', $app_id, $user_id, 'chat', $limit ),
141
+ ARRAY_A
142
+ );
143
+
144
+ return array_reverse( (array) $rows );
145
+ }
146
+
147
+ private static function maybe_alert( int $user_id ): void {
148
+ $summary = self::summary( $user_id );
149
+ $month = gmdate( 'Y-m' );
150
+
151
+ if ( $summary['limit'] <= 0 || $summary['percent'] < $summary['alert'] || get_user_meta( $user_id, self::ALERT, true ) === $month ) {
152
+ return;
153
+ }
154
+
155
+ update_user_meta( $user_id, self::ALERT, $month );
156
+
157
+ $user = get_userdata( $user_id );
158
+ $alerts = (array) get_option( self::ALERTS, [] );
159
+ $message = sprintf( '%s has used %s%% of %d monthly credits.', $user ? $user->display_name : '#' . $user_id, $summary['percent'], $summary['limit'] );
160
+
161
+ array_unshift( $alerts, [ 'user_id' => $user_id, 'message' => $message, 'at' => current_time( 'mysql', true ) ] );
162
+ update_option( self::ALERTS, array_slice( $alerts, 0, 50 ), false );
163
+
164
+ if ( Module::config( 'usage.alert_email', true ) ) {
165
+ wp_mail( (string) get_option( 'admin_email' ), 'Prompt usage alert', $message );
166
+ }
167
+ }
168
+
169
+ public static function users(): array {
170
+ $rows = [];
171
+
172
+ foreach ( get_users( [ 'orderby' => 'display_name', 'number' => 500 ] ) as $user ) {
173
+ $override = Access::override( $user->ID );
174
+ $by_role = Access::by_role( $user );
175
+
176
+ if ( ! $by_role && 'allow' !== $override && ! get_user_meta( $user->ID, self::LIMIT, true ) && 'deny' !== $override ) {
177
+ continue;
178
+ }
179
+
180
+ $rows[] = [
181
+ 'user' => $user,
182
+ 'override' => $override,
183
+ 'by_role' => $by_role,
184
+ 'allowed' => Access::allowed( $user ),
185
+ 'limit_raw' => (string) get_user_meta( $user->ID, self::LIMIT, true ),
186
+ 'summary' => self::summary( $user->ID ),
187
+ 'last' => self::last( $user->ID ),
188
+ ];
189
+ }
190
+
191
+ return $rows;
192
+ }
193
+
194
+ private static function last( int $user_id ): string {
195
+ global $wpdb;
196
+
197
+ return (string) $wpdb->get_var( $wpdb->prepare( 'SELECT MAX(created_at) FROM ' . self::table() . ' WHERE user_id = %d', $user_id ) );
198
+ }
199
+
200
+
201
+ public static function admin(): array {
202
+ $series = self::series( 30 );
203
+ $users = [];
204
+ $listed = [];
205
+
206
+ foreach ( self::users() as $row ) {
207
+ $user = $row['user'];
208
+ $listed[] = (int) $user->ID;
209
+ $users[] = [
210
+ 'id' => (int) $user->ID,
211
+ 'name' => (string) $user->display_name,
212
+ 'email' => (string) $user->user_email,
213
+ 'avatar' => (string) get_avatar_url( $user->ID, [ 'size' => 64 ] ),
214
+ 'roles' => array_values( (array) $user->roles ),
215
+ 'by_role' => (bool) $row['by_role'],
216
+ 'override' => (string) $row['override'],
217
+ 'allowed' => (bool) $row['allowed'],
218
+ 'limit' => (string) $row['limit_raw'],
219
+ 'usage' => $row['summary'],
220
+ 'last' => (string) $row['last'],
221
+ ];
222
+ }
223
+
224
+ $candidates = [];
225
+
226
+ foreach ( get_users( [ 'orderby' => 'display_name', 'number' => 500, 'exclude' => $listed ] ) as $user ) {
227
+ $candidates[] = [ 'id' => (int) $user->ID, 'name' => (string) $user->display_name, 'email' => (string) $user->user_email ];
228
+ }
229
+
230
+ return [
231
+ 'series' => $series,
232
+ 'totals' => [
233
+ 'prompts' => array_sum( array_column( $series, 'prompts' ) ),
234
+ 'credits' => array_sum( array_column( $series, 'credits' ) ),
235
+ 'users' => count( array_filter( $users, static fn( array $u ): bool => $u['allowed'] ) ),
236
+ ],
237
+ 'users' => $users,
238
+ 'candidates' => $candidates,
239
+ 'alerts' => array_slice( (array) get_option( self::ALERTS, [] ), 0, 20 ),
240
+ 'rules' => [
241
+ 'capability' => Access::cap(),
242
+ 'include' => array_values( array_filter( (array) Module::config( 'access.include_roles', [] ) ) ?: [ 'administrator', 'editor' ] ),
243
+ 'exclude' => array_values( (array) Module::config( 'access.exclude_roles', [] ) ),
244
+ 'monthly' => (int) Module::config( 'usage.monthly_credits', 0 ),
245
+ 'per_prompt' => self::cost(),
246
+ 'alert_at' => (int) Module::config( 'usage.alert_at', 80 ),
247
+ ],
248
+ ];
249
+ }
250
+
251
+ public static function set( int $user_id, array $input ) {
252
+ if ( ! current_user_can( 'edit_users' ) || ! get_userdata( $user_id ) ) {
253
+ return new \WP_Error( 'forbidden', 'You cannot change this user.', [ 'status' => 403 ] );
254
+ }
255
+
256
+ if ( array_key_exists( 'access', $input ) ) {
257
+ $value = sanitize_key( (string) $input['access'] );
258
+ in_array( $value, [ 'allow', 'deny' ], true ) ? update_user_meta( $user_id, Access::OVERRIDE, $value ) : delete_user_meta( $user_id, Access::OVERRIDE );
259
+ }
260
+
261
+ if ( array_key_exists( 'limit', $input ) ) {
262
+ '' === trim( (string) $input['limit'] ) ? delete_user_meta( $user_id, self::LIMIT ) : update_user_meta( $user_id, self::LIMIT, max( 0, (int) $input['limit'] ) );
263
+ }
264
+
265
+ return self::admin();
266
+ }
267
+
268
+ }