+                                        <th>KPI</th>
47 48
                                     </tr>
48 49
                                 </thead>
49 50
                                 <tfoot>
@@ -56,6 +57,7 @@
56 57
                                         <th>Close date</th>
57 58
                                         <th>SOC Ticket</th>
58 59
                                         <th>Opening user</th>
60
+                                        <th>KPI</th>
59 61
                                     </tr>
60 62
                                 </tfoot>
61 63
                             </table>

+ 6 - 0
iris-web/source/app/templates/includes/sidenav.html

@@ -101,6 +101,12 @@
101 101
 								<span>DIM Tasks</span>
102 102
 							</a>
103 103
 						</li>
104
+						<li class="nav-item">
105
+							<a href="/kpi-dashboard">
106
+								<i class="fas fa-tachometer-alt"></i>
107
+								<span>KPI Dashboard</span>
108
+							</a>
109
+						</li>
104 110
 
105 111
 
106 112
 						<li class="nav-section nav-advanced">

+ 3 - 0
iris-web/source/app/views.py

@@ -97,6 +97,7 @@ from app.blueprints.rest.search_routes import search_rest_blueprint
97 97
 from app.blueprints.graphql.graphql_route import graphql_blueprint
98 98
 
99 99
 from app.blueprints.rest.v2 import rest_v2_blueprint
100
+from app.blueprints.pages.kpi_dashboard.kpi_dashboard_routes import kpi_dashboard_blueprint
100 101
 from app.models.authorization import User
101 102
 
102 103
 def register_blusprints(app):
@@ -183,6 +184,8 @@ def register_blusprints(app):
183 184
 
184 185
     app.register_blueprint(rest_v2_blueprint)
185 186
 
187
+    app.register_blueprint(kpi_dashboard_blueprint)
188
+
186 189
 
187 190
 
188 191
 # provide login manager with load_user callback

+ 199 - 91
iris-web/ui/package-lock.json

@@ -21,6 +21,7 @@
21 21
         "jquery.scrollbar": "^0.2.10",
22 22
         "jqvmap": "^1.5.1",
23 23
         "moment": "^2.22.2",
24
+        "rollup": "^4.59.0",
24 25
         "showdown": "^1.9.0",
25 26
         "socket.io": "^4.3.2",
26 27
         "sortablejs": "^1.7.0",
@@ -842,13 +843,12 @@
842 843
       }
843 844
     },
844 845
     "node_modules/@rollup/rollup-android-arm-eabi": {
845
-      "version": "4.22.5",
846
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.22.5.tgz",
847
-      "integrity": "sha512-SU5cvamg0Eyu/F+kLeMXS7GoahL+OoizlclVFX3l5Ql6yNlywJJ0OuqTzUx0v+aHhPHEB/56CT06GQrRrGNYww==",
846
+      "version": "4.59.0",
847
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",
848
+      "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==",
848 849
       "cpu": [
849 850
         "arm"
850 851
       ],
851
-      "dev": true,
852 852
       "license": "MIT",
853 853
       "optional": true,
854 854
       "os": [
@@ -856,13 +856,12 @@
856 856
       ]
857 857
     },
858 858
     "node_modules/@rollup/rollup-android-arm64": {
859
-      "version": "4.22.5",
860
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.22.5.tgz",
861
-      "integrity": "sha512-S4pit5BP6E5R5C8S6tgU/drvgjtYW76FBuG6+ibG3tMvlD1h9LHVF9KmlmaUBQ8Obou7hEyS+0w+IR/VtxwNMQ==",
859
+      "version": "4.59.0",
860
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz",
861
+      "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==",
862 862
       "cpu": [
863 863
         "arm64"
864 864
       ],
865
-      "dev": true,
866 865
       "license": "MIT",
867 866
       "optional": true,
868 867
       "os": [
@@ -870,13 +869,12 @@
870 869
       ]
871 870
     },
872 871
     "node_modules/@rollup/rollup-darwin-arm64": {
873
-      "version": "4.22.5",
874
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.22.5.tgz",
875
-      "integrity": "sha512-250ZGg4ipTL0TGvLlfACkIxS9+KLtIbn7BCZjsZj88zSg2Lvu3Xdw6dhAhfe/FjjXPVNCtcSp+WZjVsD3a/Zlw==",
872
+      "version": "4.59.0",
873
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz",
874
+      "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==",
876 875
       "cpu": [
877 876
         "arm64"
878 877
       ],
879
-      "dev": true,
880 878
       "license": "MIT",
881 879
       "optional": true,
882 880
       "os": [
@@ -884,27 +882,51 @@
884 882
       ]
885 883
     },
886 884
     "node_modules/@rollup/rollup-darwin-x64": {
887
-      "version": "4.22.5",
888
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.22.5.tgz",
889
-      "integrity": "sha512-D8brJEFg5D+QxFcW6jYANu+Rr9SlKtTenmsX5hOSzNYVrK5oLAEMTUgKWYJP+wdKyCdeSwnapLsn+OVRFycuQg==",
885
+      "version": "4.59.0",
886
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz",
887
+      "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==",
890 888
       "cpu": [
891 889
         "x64"
892 890
       ],
893
-      "dev": true,
894 891
       "license": "MIT",
895 892
       "optional": true,
896 893
       "os": [
897 894
         "darwin"
898 895
       ]
899 896
     },
897
+    "node_modules/@rollup/rollup-freebsd-arm64": {
898
+      "version": "4.59.0",
899
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz",
900
+      "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==",
901
+      "cpu": [
902
+        "arm64"
903
+      ],
904
+      "license": "MIT",
905
+      "optional": true,
906
+      "os": [
907
+        "freebsd"
908
+      ]
909
+    },
910
+    "node_modules/@rollup/rollup-freebsd-x64": {
911
+      "version": "4.59.0",
912
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz",
913
+      "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==",
914
+      "cpu": [
915
+        "x64"
916
+      ],
917
+      "license": "MIT",
918
+      "optional": true,
919
+      "os": [
920
+        "freebsd"
921
+      ]
922
+    },
900 923
     "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
901
-      "version": "4.22.5",
902
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.22.5.tgz",
903
-      "integrity": "sha512-PNqXYmdNFyWNg0ma5LdY8wP+eQfdvyaBAojAXgO7/gs0Q/6TQJVXAXe8gwW9URjbS0YAammur0fynYGiWsKlXw==",
924
+      "version": "4.59.0",
925
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz",
926
+      "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==",
904 927
       "cpu": [
905 928
         "arm"
906 929
       ],
907
-      "dev": true,
908 930
       "license": "MIT",
909 931
       "optional": true,
910 932
       "os": [
@@ -912,13 +934,12 @@
912 934
       ]
913 935
     },
914 936
     "node_modules/@rollup/rollup-linux-arm-musleabihf": {
915
-      "version": "4.22.5",
916
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.22.5.tgz",
917
-      "integrity": "sha512-kSSCZOKz3HqlrEuwKd9TYv7vxPYD77vHSUvM2y0YaTGnFc8AdI5TTQRrM1yIp3tXCKrSL9A7JLoILjtad5t8pQ==",
937
+      "version": "4.59.0",
938
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz",
939
+      "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==",
918 940
       "cpu": [
919 941
         "arm"
920 942
       ],
921
-      "dev": true,
922 943
       "license": "MIT",
923 944
       "optional": true,
924 945
       "os": [
@@ -926,13 +947,12 @@
926 947
       ]
927 948
     },
928 949
     "node_modules/@rollup/rollup-linux-arm64-gnu": {
929
-      "version": "4.22.5",
930
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.22.5.tgz",
931
-      "integrity": "sha512-oTXQeJHRbOnwRnRffb6bmqmUugz0glXaPyspp4gbQOPVApdpRrY/j7KP3lr7M8kTfQTyrBUzFjj5EuHAhqH4/w==",
950
+      "version": "4.59.0",
951
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz",
952
+      "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==",
932 953
       "cpu": [
933 954
         "arm64"
934 955
       ],
935
-      "dev": true,
936 956
       "license": "MIT",
937 957
       "optional": true,
938 958
       "os": [
@@ -940,27 +960,64 @@
940 960
       ]
941 961
     },
942 962
     "node_modules/@rollup/rollup-linux-arm64-musl": {
943
-      "version": "4.22.5",
944
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.22.5.tgz",
945
-      "integrity": "sha512-qnOTIIs6tIGFKCHdhYitgC2XQ2X25InIbZFor5wh+mALH84qnFHvc+vmWUpyX97B0hNvwNUL4B+MB8vJvH65Fw==",
963
+      "version": "4.59.0",
964
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz",
965
+      "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==",
946 966
       "cpu": [
947 967
         "arm64"
948 968
       ],
949
-      "dev": true,
950 969
       "license": "MIT",
951 970
       "optional": true,
952 971
       "os": [
953 972
         "linux"
954 973
       ]
955 974
     },
956
-    "node_modules/@rollup/rollup-linux-powerpc64le-gnu": {
957
-      "version": "4.22.5",
958
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.22.5.tgz",
959
-      "integrity": "sha512-TMYu+DUdNlgBXING13rHSfUc3Ky5nLPbWs4bFnT+R6Vu3OvXkTkixvvBKk8uO4MT5Ab6lC3U7x8S8El2q5o56w==",
975
+    "node_modules/@rollup/rollup-linux-loong64-gnu": {
976
+      "version": "4.59.0",
977
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz",
978
+      "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==",
979
+      "cpu": [
980
+        "loong64"
981
+      ],
982
+      "license": "MIT",
983
+      "optional": true,
984
+      "os": [
985
+        "linux"
986
+      ]
987
+    },
988
+    "node_modules/@rollup/rollup-linux-loong64-musl": {
989
+      "version": "4.59.0",
990
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz",
991
+      "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==",
992
+      "cpu": [
993
+        "loong64"
994
+      ],
995
+      "license": "MIT",
996
+      "optional": true,
997
+      "os": [
998
+        "linux"
999
+      ]
1000
+    },
1001
+    "node_modules/@rollup/rollup-linux-ppc64-gnu": {
1002
+      "version": "4.59.0",
1003
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz",
1004
+      "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==",
1005
+      "cpu": [
1006
+        "ppc64"
1007
+      ],
1008
+      "license": "MIT",
1009
+      "optional": true,
1010
+      "os": [
1011
+        "linux"
1012
+      ]
1013
+    },
1014
+    "node_modules/@rollup/rollup-linux-ppc64-musl": {
1015
+      "version": "4.59.0",
1016
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz",
1017
+      "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==",
960 1018
       "cpu": [
961 1019
         "ppc64"
962 1020
       ],
963
-      "dev": true,
964 1021
       "license": "MIT",
965 1022
       "optional": true,
966 1023
       "os": [
@@ -968,13 +1025,25 @@
968 1025
       ]
969 1026
     },
970 1027
     "node_modules/@rollup/rollup-linux-riscv64-gnu": {
971
-      "version": "4.22.5",
972
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.22.5.tgz",
973
-      "integrity": "sha512-PTQq1Kz22ZRvuhr3uURH+U/Q/a0pbxJoICGSprNLAoBEkyD3Sh9qP5I0Asn0y0wejXQBbsVMRZRxlbGFD9OK4A==",
1028
+      "version": "4.59.0",
1029
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz",
1030
+      "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==",
1031
+      "cpu": [
1032
+        "riscv64"
1033
+      ],
1034
+      "license": "MIT",
1035
+      "optional": true,
1036
+      "os": [
1037
+        "linux"
1038
+      ]
1039
+    },
1040
+    "node_modules/@rollup/rollup-linux-riscv64-musl": {
1041
+      "version": "4.59.0",
1042
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz",
1043
+      "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==",
974 1044
       "cpu": [
975 1045
         "riscv64"
976 1046
       ],
977
-      "dev": true,
978 1047
       "license": "MIT",
979 1048
       "optional": true,
980 1049
       "os": [
@@ -982,13 +1051,12 @@
982 1051
       ]
983 1052
     },
984 1053
     "node_modules/@rollup/rollup-linux-s390x-gnu": {
985
-      "version": "4.22.5",
986
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.22.5.tgz",
987
-      "integrity": "sha512-bR5nCojtpuMss6TDEmf/jnBnzlo+6n1UhgwqUvRoe4VIotC7FG1IKkyJbwsT7JDsF2jxR+NTnuOwiGv0hLyDoQ==",
1054
+      "version": "4.59.0",
1055
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz",
1056
+      "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==",
988 1057
       "cpu": [
989 1058
         "s390x"
990 1059
       ],
991
-      "dev": true,
992 1060
       "license": "MIT",
993 1061
       "optional": true,
994 1062
       "os": [
@@ -996,13 +1064,12 @@
996 1064
       ]
997 1065
     },
998 1066
     "node_modules/@rollup/rollup-linux-x64-gnu": {
999
-      "version": "4.22.5",
1000
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.22.5.tgz",
1001
-      "integrity": "sha512-N0jPPhHjGShcB9/XXZQWuWBKZQnC1F36Ce3sDqWpujsGjDz/CQtOL9LgTrJ+rJC8MJeesMWrMWVLKKNR/tMOCA==",
1067
+      "version": "4.59.0",
1068
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz",
1069
+      "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==",
1002 1070
       "cpu": [
1003 1071
         "x64"
1004 1072
       ],
1005
-      "dev": true,
1006 1073
       "license": "MIT",
1007 1074
       "optional": true,
1008 1075
       "os": [
@@ -1010,27 +1077,51 @@
1010 1077
       ]
1011 1078
     },
1012 1079
     "node_modules/@rollup/rollup-linux-x64-musl": {
1013
-      "version": "4.22.5",
1014
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.22.5.tgz",
1015
-      "integrity": "sha512-uBa2e28ohzNNwjr6Uxm4XyaA1M/8aTgfF2T7UIlElLaeXkgpmIJ2EitVNQxjO9xLLLy60YqAgKn/AqSpCUkE9g==",
1080
+      "version": "4.59.0",
1081
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz",
1082
+      "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==",
1016 1083
       "cpu": [
1017 1084
         "x64"
1018 1085
       ],
1019
-      "dev": true,
1020 1086
       "license": "MIT",
1021 1087
       "optional": true,
1022 1088
       "os": [
1023 1089
         "linux"
1024 1090
       ]
1025 1091
     },
1092
+    "node_modules/@rollup/rollup-openbsd-x64": {
1093
+      "version": "4.59.0",
1094
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz",
1095
+      "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==",
1096
+      "cpu": [
1097
+        "x64"
1098
+      ],
1099
+      "license": "MIT",
1100
+      "optional": true,
1101
+      "os": [
1102
+        "openbsd"
1103
+      ]
1104
+    },
1105
+    "node_modules/@rollup/rollup-openharmony-arm64": {
1106
+      "version": "4.59.0",
1107
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz",
1108
+      "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==",
1109
+      "cpu": [
1110
+        "arm64"
1111
+      ],
1112
+      "license": "MIT",
1113
+      "optional": true,
1114
+      "os": [
1115
+        "openharmony"
1116
+      ]
1117
+    },
1026 1118
     "node_modules/@rollup/rollup-win32-arm64-msvc": {
1027
-      "version": "4.22.5",
1028
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.22.5.tgz",
1029
-      "integrity": "sha512-RXT8S1HP8AFN/Kr3tg4fuYrNxZ/pZf1HemC5Tsddc6HzgGnJm0+Lh5rAHJkDuW3StI0ynNXukidROMXYl6ew8w==",
1119
+      "version": "4.59.0",
1120
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz",
1121
+      "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==",
1030 1122
       "cpu": [
1031 1123
         "arm64"
1032 1124
       ],
1033
-      "dev": true,
1034 1125
       "license": "MIT",
1035 1126
       "optional": true,
1036 1127
       "os": [
@@ -1038,13 +1129,25 @@
1038 1129
       ]
1039 1130
     },
1040 1131
     "node_modules/@rollup/rollup-win32-ia32-msvc": {
1041
-      "version": "4.22.5",
1042
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.22.5.tgz",
1043
-      "integrity": "sha512-ElTYOh50InL8kzyUD6XsnPit7jYCKrphmddKAe1/Ytt74apOxDq5YEcbsiKs0fR3vff3jEneMM+3I7jbqaMyBg==",
1132
+      "version": "4.59.0",
1133
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz",
1134
+      "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==",
1044 1135
       "cpu": [
1045 1136
         "ia32"
1046 1137
       ],
1047
-      "dev": true,
1138
+      "license": "MIT",
1139
+      "optional": true,
1140
+      "os": [
1141
+        "win32"
1142
+      ]
1143
+    },
1144
+    "node_modules/@rollup/rollup-win32-x64-gnu": {
1145
+      "version": "4.59.0",
1146
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz",
1147
+      "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==",
1148
+      "cpu": [
1149
+        "x64"
1150
+      ],
1048 1151
       "license": "MIT",
1049 1152
       "optional": true,
1050 1153
       "os": [
@@ -1052,13 +1155,12 @@
1052 1155
       ]
1053 1156
     },
1054 1157
     "node_modules/@rollup/rollup-win32-x64-msvc": {
1055
-      "version": "4.22.5",
1056
-      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.22.5.tgz",
1057
-      "integrity": "sha512-+lvL/4mQxSV8MukpkKyyvfwhH266COcWlXE/1qxwN08ajovta3459zrjLghYMgDerlzNwLAcFpvU+WWE5y6nAQ==",
1158
+      "version": "4.59.0",
1159
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz",
1160
+      "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==",
1058 1161
       "cpu": [
1059 1162
         "x64"
1060 1163
       ],
1061
-      "dev": true,
1062 1164
       "license": "MIT",
1063 1165
       "optional": true,
1064 1166
       "os": [
@@ -1122,10 +1224,9 @@
1122 1224
       }
1123 1225
     },
1124 1226
     "node_modules/@types/estree": {
1125
-      "version": "1.0.6",
1126
-      "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz",
1127
-      "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==",
1128
-      "dev": true,
1227
+      "version": "1.0.8",
1228
+      "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
1229
+      "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
1129 1230
       "license": "MIT"
1130 1231
     },
1131 1232
     "node_modules/@types/jquery": {
@@ -2341,7 +2442,6 @@
2341 2442
       "version": "2.3.3",
2342 2443
       "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
2343 2444
       "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
2344
-      "dev": true,
2345 2445
       "hasInstallScript": true,
2346 2446
       "license": "MIT",
2347 2447
       "optional": true,
@@ -3553,13 +3653,12 @@
3553 3653
       }
3554 3654
     },
3555 3655
     "node_modules/rollup": {
3556
-      "version": "4.22.5",
3557
-      "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.22.5.tgz",
3558
-      "integrity": "sha512-WoinX7GeQOFMGznEcWA1WrTQCd/tpEbMkc3nuMs9BT0CPjMdSjPMTVClwWd4pgSQwJdP65SK9mTCNvItlr5o7w==",
3559
-      "dev": true,
3656
+      "version": "4.59.0",
3657
+      "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz",
3658
+      "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==",
3560 3659
       "license": "MIT",
3561 3660
       "dependencies": {
3562
-        "@types/estree": "1.0.6"
3661
+        "@types/estree": "1.0.8"
3563 3662
       },
3564 3663
       "bin": {
3565 3664
         "rollup": "dist/bin/rollup"
@@ -3569,22 +3668,31 @@
3569 3668
         "npm": ">=8.0.0"
3570 3669
       },
3571 3670
       "optionalDependencies": {
3572
-        "@rollup/rollup-android-arm-eabi": "4.22.5",
3573
-        "@rollup/rollup-android-arm64": "4.22.5",
3574
-        "@rollup/rollup-darwin-arm64": "4.22.5",
3575
-        "@rollup/rollup-darwin-x64": "4.22.5",
3576
-        "@rollup/rollup-linux-arm-gnueabihf": "4.22.5",
3577
-        "@rollup/rollup-linux-arm-musleabihf": "4.22.5",
3578
-        "@rollup/rollup-linux-arm64-gnu": "4.22.5",
3579
-        "@rollup/rollup-linux-arm64-musl": "4.22.5",
3580
-        "@rollup/rollup-linux-powerpc64le-gnu": "4.22.5",
3581
-        "@rollup/rollup-linux-riscv64-gnu": "4.22.5",
3582
-        "@rollup/rollup-linux-s390x-gnu": "4.22.5",
3583
-        "@rollup/rollup-linux-x64-gnu": "4.22.5",
3584
-        "@rollup/rollup-linux-x64-musl": "4.22.5",
3585
-        "@rollup/rollup-win32-arm64-msvc": "4.22.5",
3586
-        "@rollup/rollup-win32-ia32-msvc": "4.22.5",
3587
-        "@rollup/rollup-win32-x64-msvc": "4.22.5",
3671
+        "@rollup/rollup-android-arm-eabi": "4.59.0",
3672
+        "@rollup/rollup-android-arm64": "4.59.0",
3673
+        "@rollup/rollup-darwin-arm64": "4.59.0",
3674
+        "@rollup/rollup-darwin-x64": "4.59.0",
3675
+        "@rollup/rollup-freebsd-arm64": "4.59.0",
3676
+        "@rollup/rollup-freebsd-x64": "4.59.0",
3677
+        "@rollup/rollup-linux-arm-gnueabihf": "4.59.0",
3678
+        "@rollup/rollup-linux-arm-musleabihf": "4.59.0",
3679
+        "@rollup/rollup-linux-arm64-gnu": "4.59.0",
3680
+        "@rollup/rollup-linux-arm64-musl": "4.59.0",
3681
+        "@rollup/rollup-linux-loong64-gnu": "4.59.0",
3682
+        "@rollup/rollup-linux-loong64-musl": "4.59.0",
3683
+        "@rollup/rollup-linux-ppc64-gnu": "4.59.0",
3684
+        "@rollup/rollup-linux-ppc64-musl": "4.59.0",
3685
+        "@rollup/rollup-linux-riscv64-gnu": "4.59.0",
3686
+        "@rollup/rollup-linux-riscv64-musl": "4.59.0",
3687
+        "@rollup/rollup-linux-s390x-gnu": "4.59.0",
3688
+        "@rollup/rollup-linux-x64-gnu": "4.59.0",
3689
+        "@rollup/rollup-linux-x64-musl": "4.59.0",
3690
+        "@rollup/rollup-openbsd-x64": "4.59.0",
3691
+        "@rollup/rollup-openharmony-arm64": "4.59.0",
3692
+        "@rollup/rollup-win32-arm64-msvc": "4.59.0",
3693
+        "@rollup/rollup-win32-ia32-msvc": "4.59.0",
3694
+        "@rollup/rollup-win32-x64-gnu": "4.59.0",
3695
+        "@rollup/rollup-win32-x64-msvc": "4.59.0",
3588 3696
         "fsevents": "~2.3.2"
3589 3697
       }
3590 3698
     },

+ 1 - 0
iris-web/ui/package.json

@@ -37,6 +37,7 @@
37 37
     "jquery.scrollbar": "^0.2.10",
38 38
     "jqvmap": "^1.5.1",
39 39
     "moment": "^2.22.2",
40
+    "rollup": "^4.59.0",
40 41
     "showdown": "^1.9.0",
41 42
     "socket.io": "^4.3.2",
42 43
     "sortablejs": "^1.7.0",

+ 25 - 0
iris-web/ui/src/css/kpi_dashboard.css

@@ -0,0 +1,25 @@
1
+/* KPI Alert Dashboard — styles */
2
+
3
+/* KPI bar — 4 segments */
4
+.kpi-bar-wrap  { display:flex; flex-direction:column; gap:3px; min-width:120px; }
5
+.kpi-segs      { display:flex; gap:4px; }
6
+.kpi-seg       { width:26px; height:10px; border-radius:3px; }
7
+
8
+/* Scaled fill bar (width = kpi_pct%) */
9
+.kpi-track     { width:100px; height:6px; background:#e5e7eb; border-radius:3px; overflow:hidden; }
10
+.kpi-fill      { height:6px; border-radius:3px; transition:width 0.4s ease; }
11
+.kpi-pct-label { font-size:10px; color:#6b7280; }
12
+
13
+/* Severity badges */
14
+.badge-high    { background:#fed7aa; color:#c2410c; font-size:10px; padding:1px 6px; border-radius:999px; display:inline-block; }
15
+.badge-medium  { background:#fef9c3; color:#854d0e; font-size:10px; padding:1px 6px; border-radius:999px; display:inline-block; }
16
+.badge-low     { background:#d1fae5; color:#065f46; font-size:10px; padding:1px 6px; border-radius:999px; display:inline-block; }
17
+
18
+/* Status dot */
19
+.status-dot    { width:10px; height:10px; border-radius:50%; display:inline-block; }
20
+.dot-open      { background:#ef4444; }
21
+.dot-closed    { background:#22c55e; }
22
+
23
+/* Sortable column headers */
24
+.sortable      { cursor:pointer; user-select:none; }
25
+.sortable:hover { background:#f1f5f9; }

+ 37 - 5
iris-web/ui/src/pages/alerts.js

@@ -1,6 +1,32 @@
1 1
 let sortOrder ;
2 2
 let editor = null;
3 3
 
4
+// ---------------------------------------------------------------------------
5
+// KPI — fetch from soc-integrator, injected into alert objects before render
6
+// ---------------------------------------------------------------------------
7
+async function _fetchAlertKpi(alertId) {
8
+  try {
9
+    const res = await fetch(`/kpi-dashboard/api/alerts/${alertId}`);
10
+    if (!res.ok) return null;
11
+    const json = await res.json();
12
+    return json.data?.alert?.kpi ?? null;
13
+  } catch { return null; }
14
+}
15
+
16
+function _renderAlertKpiBar(alert) {
17
+  const kpi = alert.kpi;
18
+  if (!kpi) return '';
19
+  const segs = kpi.segments.map(s =>
20
+    `<div style="width:20px;height:8px;border-radius:3px;background:${s.active ? s.color : '#e5e7eb'}" title="${s.label}"></div>`
21
+  ).join('');
22
+  return `
23
+    <span title="KPI: ${kpi.status} — ${kpi.elapsed_pct}% elapsed" class="ml-3 d-inline-flex align-items-center" style="gap:4px">
24
+      <b><i class="fa-solid fa-gauge-high"></i></b>
25
+      <span style="display:flex;gap:3px">${segs}</span>
26
+      <small class="text-muted ml-1">${kpi.status}</small>
27
+    </span>`;
28
+}
29
+
4 30
 function objectToQueryString(obj) {
5 31
   return Object.keys(obj)
6 32
     .filter(key => obj[key] !== undefined && obj[key] !== null && obj[key] !== '')
@@ -1239,6 +1265,7 @@ function renderAlert(alert, expanded=false, modulesOptionsAlertReq,
1239 1265
                 <small class="text-muted ml-1">${formatTime(alert.alert_source_event_time)}</small></span>
1240 1266
                 <span title="Alert severity"><b class="ml-3"><i class="fa-solid fa-bolt"></i></b>
1241 1267
                   <small class="text-muted ml-1" id="alertSeverity-${alert.alert_id}" data-severity-id="${alert.severity.severity_id}">${alert.severity.severity_name}</small></span>
1268
+                ${_renderAlertKpiBar(alert)}
1242 1269
                 <span title="Alert source"><b class="ml-3"><i class="fa-solid fa-cloud-arrow-down"></i></b>
1243 1270
                   <small class="text-muted ml-1">${filterXSS(alert.alert_source) || 'Unspecified'}</small></span>
1244 1271
                 <span title="Alert client"><b class="ml-3"><i class="fa-regular fa-circle-user"></i></b>
@@ -1300,6 +1327,7 @@ async function showAlertHistory(alertId) {
1300 1327
 }
1301 1328
 
1302 1329
 async function refreshAlert(alertId, alertData, expanded=false) {
1330
+    const kpiFetch = _fetchAlertKpi(alertId);
1303 1331
     if (alertData === undefined) {
1304 1332
         const alertDataReq = await fetchAlert(alertId);
1305 1333
         if (api_request_failed(alertDataReq)) {
@@ -1307,6 +1335,8 @@ async function refreshAlert(alertId, alertData, expanded=false) {
1307 1335
         }
1308 1336
         alertData = alertDataReq.data;
1309 1337
     }
1338
+    const kpi = await kpiFetch;
1339
+    if (kpi) alertData.kpi = kpi;
1310 1340
 
1311 1341
       if (modulesOptionsAlertReq === null) {
1312 1342
     modulesOptionsAlertReq = await fetchModulesOptionsAlert();
@@ -1359,12 +1389,14 @@ async function updateAlerts(page, per_page, filters = {}, paging=false){
1359 1389
 
1360 1390
   const filterString = objectToQueryString(filters);
1361 1391
   const data = await fetchAlerts(page, per_page, filterString, sortOrder).catch((error) => {
1362
-        notify_error('Failed to fetch alerts');
1363
-        alertsContainer.html('<h4 class="ml-auto mr-auto">Oops error loading the alerts - Check logs</h4>');
1364
-        console.error(error);
1365
-    });
1392
+      notify_error('Failed to fetch alerts');
1393
+      alertsContainer.html('<h4 class="ml-auto mr-auto">Oops error loading the alerts - Check logs</h4>');
1394
+      console.error(error);
1395
+  });
1396
+  if (!data) return;
1366 1397
 
1367
-  const alerts = data.data;
1398
+  const kpiResults = await Promise.all(data.data.map(a => _fetchAlertKpi(a.alert_id)));
1399
+  const alerts = data.data.map((a, i) => ({ ...a, kpi: kpiResults[i] ?? null }));
1368 1400
 
1369 1401
   if (modulesOptionsAlertReq === null) {
1370 1402
     modulesOptionsAlertReq = await fetchModulesOptionsAlert();

+ 314 - 0
iris-web/ui/src/pages/kpi_dashboard.js

@@ -0,0 +1,314 @@
1
+// KPI Alert Dashboard — vanilla JS, compiled by Vite into /static/assets/js/iris/kpi_dashboard.js
2
+import '../css/kpi_dashboard.css';
3
+
4
+const API_BASE = '/kpi-dashboard/api';
5
+
6
+const state = {
7
+  page: 1,
8
+  perPage: 20,
9
+  sortBy: 'alert_id',
10
+  sortDir: 'desc',
11
+  filterTitle: '',
12
+  filterOwner: '',
13
+  total: 0,
14
+  selected: new Set(),
15
+};
16
+
17
+// Debounce helper for filter inputs
18
+let _debounceTimer = null;
19
+function debouncedLoad() {
20
+  clearTimeout(_debounceTimer);
21
+  _debounceTimer = setTimeout(() => {
22
+    state.page = 1;
23
+    loadAlerts();
24
+  }, 350);
25
+}
26
+
27
+async function loadAlerts() {
28
+  state.filterTitle = document.getElementById('filter-title').value;
29
+  state.filterOwner = document.getElementById('filter-owner').value;
30
+
31
+  const params = new URLSearchParams({
32
+    page: state.page,
33
+    per_page: state.perPage,
34
+    sort_by: state.sortBy,
35
+    sort_dir: state.sortDir,
36
+  });
37
+  if (state.filterTitle) params.set('filter_title', state.filterTitle);
38
+  if (state.filterOwner) params.set('filter_owner', state.filterOwner);
39
+
40
+  const body = document.getElementById('alerts-body');
41
+  body.innerHTML = '<tr><td colspan="12" class="text-center text-muted py-4">Loading...</td></tr>';
42
+
43
+  try {
44
+    const res = await fetch(`${API_BASE}/alerts?${params}`);
45
+    if (!res.ok) throw new Error(`HTTP ${res.status}`);
46
+    const json = await res.json();
47
+    const alertsData = json.data?.alerts ?? {};
48
+    const alerts = alertsData.data ?? [];
49
+    state.total = alertsData.total ?? alerts.length;
50
+    renderTable(alerts);
51
+    updatePageInfo();
52
+    updateSelectionLabel();
53
+  } catch (err) {
54
+    body.innerHTML = `<tr><td colspan="12" class="text-center text-danger py-4">Error: ${err.message}</td></tr>`;
55
+  }
56
+}
57
+
58
+function renderKpiBar(kpi) {
59
+  if (!kpi) return '<span class="text-muted">—</span>';
60
+  const containerW = 100;
61
+  const fillW = Math.round((kpi.elapsed_pct / 100) * containerW);
62
+  const fillColor = kpi.resolved ? '#6b7280'
63
+    : kpi.elapsed_pct >= 75 ? '#ef4444'
64
+    : kpi.elapsed_pct >= 50 ? '#f97316'
65
+    : kpi.elapsed_pct >= 25 ? '#eab308'
66
+    : '#22c55e';
67
+
68
+  const segs = (kpi.segments || []).map(s =>
69
+    `<div class="kpi-seg" style="background:${s.active ? s.color : '#e5e7eb'}" title="${s.label}: ${s.active ? 'active' : 'inactive'}"></div>`
70
+  ).join('');
71
+
72
+  return `
73
+    <div class="kpi-bar-wrap" title="${kpi.status} — ${kpi.elapsed_pct}% elapsed">
74
+      <div class="kpi-segs">${segs}</div>
75
+      <div class="kpi-track">
76
+        <div class="kpi-fill" style="width:${fillW}px;background:${fillColor}"></div>
77
+      </div>
78
+      <span class="kpi-pct-label">${kpi.status}</span>
79
+    </div>`;
80
+}
81
+
82
+function severityBadge(severity) {
83
+  if (!severity) return '';
84
+  const name = (severity.severity_name || '').toLowerCase();
85
+  const cls = name === 'high' ? 'badge-high' : name === 'medium' ? 'badge-medium' : 'badge-low';
86
+  return `<span class="${cls}">${severity.severity_name || ''}</span>`;
87
+}
88
+
89
+function statusDot(status) {
90
+  if (!status) return '';
91
+  const name = (status.status_name || '').toLowerCase();
92
+  const cls = name === 'closed' ? 'dot-closed' : 'dot-open';
93
+  return `<span class="status-dot ${cls}" title="${status.status_name || ''}"></span>`;
94
+}
95
+
96
+function fmtDate(str) {
97
+  if (!str) return '—';
98
+  try {
99
+    return new Date(str).toLocaleString();
100
+  } catch {
101
+    return str;
102
+  }
103
+}
104
+
105
+function renderTable(alerts) {
106
+  const body = document.getElementById('alerts-body');
107
+  if (!alerts.length) {
108
+    body.innerHTML = '<tr><td colspan="12" class="text-center text-muted py-4">No alerts found.</td></tr>';
109
+    return;
110
+  }
111
+
112
+  body.innerHTML = alerts.map(alert => {
113
+    const id = alert.alert_id ?? '';
114
+    const checked = state.selected.has(id) ? 'checked' : '';
115
+    const owner = (alert.owner || {}).user_name || '—';
116
+    const classification = (alert.classification || {}).name || '—';
117
+    const closedAt = alert.alert_close_timestamp ? fmtDate(alert.alert_close_timestamp) : '—';
118
+    return `
119
+      <tr class="alert-row" style="cursor:pointer" onclick="openAlertDetail(${id}, event)">
120
+        <td><input type="checkbox" class="row-chk" data-id="${id}" ${checked} onchange="toggleRow(this)"></td>
121
+        <td>${statusDot(alert.status)}</td>
122
+        <td>${owner}</td>
123
+        <td>${id}</td>
124
+        <td>${alert.alert_title || '—'}</td>
125
+        <td>${classification}</td>
126
+        <td>${severityBadge(alert.severity)}</td>
127
+        <td>${fmtDate(alert.alert_creation_time)}</td>
128
+        <td>${renderKpiBar(alert.kpi)}</td>
129
+        <td>${fmtDate(alert.alert_source_event_time)}</td>
130
+        <td>${closedAt}</td>
131
+        <td>—</td>
132
+      </tr>`;
133
+  }).join('');
134
+}
135
+
136
+function toggleAll(chk) {
137
+  document.querySelectorAll('.row-chk').forEach(el => {
138
+    el.checked = chk.checked;
139
+    const id = Number(el.dataset.id);
140
+    if (chk.checked) state.selected.add(id);
141
+    else state.selected.delete(id);
142
+  });
143
+  updateSelectionLabel();
144
+}
145
+
146
+function toggleRow(el) {
147
+  const id = Number(el.dataset.id);
148
+  if (el.checked) state.selected.add(id);
149
+  else state.selected.delete(id);
150
+  updateSelectionLabel();
151
+}
152
+
153
+function updateSelectionLabel() {
154
+  // selection label removed from UI
155
+}
156
+
157
+function updatePageInfo() {
158
+  const el = document.getElementById('page-info');
159
+  if (el) {
160
+    const totalPages = Math.max(1, Math.ceil(state.total / state.perPage));
161
+    el.textContent = `Page ${state.page} of ${totalPages} (${state.total} total)`;
162
+  }
163
+}
164
+
165
+function prevPage() {
166
+  if (state.page > 1) {
167
+    state.page--;
168
+    refreshActive();
169
+  }
170
+}
171
+
172
+function nextPage() {
173
+  const totalPages = Math.ceil(state.total / state.perPage);
174
+  if (state.page < totalPages) {
175
+    state.page++;
176
+    refreshActive();
177
+  }
178
+}
179
+
180
+function sortBy(col) {
181
+  if (state.sortBy === col) {
182
+    state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';
183
+  } else {
184
+    state.sortBy = col;
185
+    state.sortDir = 'desc';
186
+  }
187
+  state.page = 1;
188
+  loadAlerts();
189
+}
190
+
191
+async function assignSelected() {
192
+  if (!state.selected.size) {
193
+    alert('No alerts selected.');
194
+    return;
195
+  }
196
+  const ownerIdStr = prompt('Enter owner user ID to assign:');
197
+  if (!ownerIdStr) return;
198
+  const ownerId = parseInt(ownerIdStr, 10);
199
+  if (isNaN(ownerId)) {
200
+    alert('Invalid owner ID.');
201
+    return;
202
+  }
203
+  const ids = Array.from(state.selected);
204
+  try {
205
+    await Promise.all(ids.map(id =>
206
+      fetch(`${API_BASE}/alerts/${id}/assign`, {
207
+        method: 'POST',
208
+        headers: { 'Content-Type': 'application/json' },
209
+        body: JSON.stringify({ owner_id: ownerId }),
210
+      })
211
+    ));
212
+    state.selected.clear();
213
+    loadAlerts();
214
+  } catch (err) {
215
+    alert(`Assignment failed: ${err.message}`);
216
+  }
217
+}
218
+
219
+function exportCsv() {
220
+  const params = new URLSearchParams({
221
+    sort_by: state.sortBy,
222
+    sort_dir: state.sortDir,
223
+  });
224
+  if (state.filterTitle) params.set('filter_title', state.filterTitle);
225
+  if (state.filterOwner) params.set('filter_owner', state.filterOwner);
226
+  window.location.href = `${API_BASE}/alerts/export-csv?${params}`;
227
+}
228
+
229
+let activeTab = 'alerts';
230
+
231
+function switchTab(tab) {
232
+  activeTab = tab;
233
+  document.getElementById('tab-alerts').classList.toggle('active', tab === 'alerts');
234
+  document.getElementById('tab-cases').classList.toggle('active', tab === 'cases');
235
+  state.page = 1;
236
+  activeTab === 'alerts' ? loadAlerts() : loadCases();
237
+}
238
+
239
+async function loadCases() {
240
+  const params = new URLSearchParams({
241
+    page: state.page,
242
+    per_page: state.perPage,
243
+    sort_by: state.sortBy,
244
+    sort_dir: state.sortDir,
245
+  });
246
+  const body = document.getElementById('alerts-body');
247
+  body.innerHTML = '<tr><td colspan="12" class="text-center text-muted py-4">Loading...</td></tr>';
248
+  try {
249
+    const res = await fetch(`${API_BASE}/cases?${params}`);
250
+    if (!res.ok) throw new Error(`HTTP ${res.status}`);
251
+    const json = await res.json();
252
+    const casesData = json.data?.cases ?? {};
253
+    const cases = casesData.data ?? [];
254
+    state.total = casesData.total ?? cases.length;
255
+    renderCasesTable(cases);
256
+    updatePageInfo();
257
+  } catch (err) {
258
+    body.innerHTML = `<tr><td colspan="12" class="text-center text-danger py-4">Error: ${err.message}</td></tr>`;
259
+  }
260
+}
261
+
262
+function renderCasesTable(cases) {
263
+  const body = document.getElementById('alerts-body');
264
+  if (!cases.length) {
265
+    body.innerHTML = '<tr><td colspan="12" class="text-center text-muted py-4">No cases found.</td></tr>';
266
+    return;
267
+  }
268
+  body.innerHTML = cases.map(c => {
269
+    const owner = (c.owner || {}).user_name || '—';
270
+    const stateName = (c.state || {}).state_name || '—';
271
+    const closed = c.close_date ? fmtDate(c.close_date) : '—';
272
+    return `<tr>
273
+      <td></td>
274
+      <td>${statusDot({status_name: stateName})}</td>
275
+      <td>${owner}</td>
276
+      <td>${c.case_id ?? ''}</td>
277
+      <td>${c.case_name || '—'}</td>
278
+      <td>${c.case_soc_id || '—'}</td>
279
+      <td>—</td>
280
+      <td>${fmtDate(c.open_date)}</td>
281
+      <td>${renderKpiBar(c.kpi)}</td>
282
+      <td>—</td>
283
+      <td>${closed}</td>
284
+      <td>—</td>
285
+    </tr>`;
286
+  }).join('');
287
+}
288
+
289
+function openAlertDetail(alertId, event) {
290
+  // Don't navigate when clicking the checkbox
291
+  if (event && event.target.type === 'checkbox') return;
292
+  window.location.href = `/alerts?alert_ids=${alertId}&cid=1`;
293
+}
294
+
295
+function refreshActive() {
296
+  activeTab === 'alerts' ? loadAlerts() : loadCases();
297
+}
298
+
299
+// Auto-load on page ready
300
+document.addEventListener('DOMContentLoaded', loadAlerts);
301
+setInterval(refreshActive, 60_000);
302
+
303
+// Expose for inline onclick handlers
304
+window.debouncedLoad = debouncedLoad;
305
+window.loadAlerts = loadAlerts;
306
+window.toggleAll = toggleAll;
307
+window.toggleRow = toggleRow;
308
+window.assignSelected = assignSelected;
309
+window.exportCsv = exportCsv;
310
+window.prevPage = prevPage;
311
+window.nextPage = nextPage;
312
+window.sortBy = sortBy;
313
+window.switchTab = switchTab;
314
+window.openAlertDetail = openAlertDetail;

+ 46 - 2
iris-web/ui/src/pages/manage.cases.js

@@ -26,7 +26,31 @@ $('#classification_id').prepend(new Option('', ''));
26 26
 
27 27
 
28 28
  /*************************
29
- *  Case list section 
29
+ *  KPI helpers
30
+ *************************/
31
+async function _fetchCaseKpi(caseId) {
32
+  try {
33
+    const res = await fetch(`/kpi-dashboard/api/cases/${caseId}`);
34
+    if (!res.ok) return null;
35
+    const json = await res.json();
36
+    return json.data?.case?.kpi ?? null;
37
+  } catch { return null; }
38
+}
39
+
40
+function _renderCaseKpiBar(kpi) {
41
+  if (!kpi) return '<span class="text-muted">—</span>';
42
+  const segs = (kpi.segments || []).map(s =>
43
+    `<div style="width:18px;height:8px;border-radius:3px;background:${s.active ? s.color : '#e5e7eb'}" title="${s.label}"></div>`
44
+  ).join('');
45
+  return `<span title="KPI: ${kpi.status} — ${kpi.elapsed_pct}% elapsed" style="display:inline-flex;align-items:center;gap:4px">
46
+    <b><i class="fa-solid fa-gauge-high"></i></b>
47
+    <span style="display:flex;gap:3px">${segs}</span>
48
+    <small class="text-muted">${kpi.status}</small>
49
+  </span>`;
50
+}
51
+
52
+ /*************************
53
+ *  Case list section
30 54
  *************************/
31 55
 /* case table creation */
32 56
 $.each($.find("table"), function(index, element){
@@ -112,6 +136,17 @@ $('#cases_table').dataTable({
112 136
             if (type === 'display') { data = sanitizeHTML(data);}
113 137
             return data;
114 138
           }
139
+        },
140
+        {
141
+            "data": "case_id",
142
+            "orderable": false,
143
+            "searchable": false,
144
+            "render": function (data, type, row) {
145
+                if (type === 'display') {
146
+                    return `<span id="case-kpi-${data}"><small class="text-muted">…</small></span>`;
147
+                }
148
+                return data;
149
+            }
115 150
         }
116 151
     ],
117 152
     dom: '<"container-fluid"<"row"<"col"l><"col"f>>>rt<"container-fluid"<"row"<"col"i><"col"p>>>',
@@ -133,7 +168,16 @@ $('#cases_table').dataTable({
133 168
     },
134 169
     initComplete: function () {
135 170
             tableFiltering(this.api(), 'cases_table');
136
-        }
171
+        },
172
+    drawCallback: function () {
173
+        const api = this.api();
174
+        api.rows({ page: 'current' }).data().each(function (row) {
175
+            const caseId = row.case_id;
176
+            _fetchCaseKpi(caseId).then(kpi => {
177
+                $(`#case-kpi-${caseId}`).html(_renderCaseKpiBar(kpi));
178
+            });
179
+        });
180
+    }
137 181
     }
138 182
 );
139 183
 

+ 1 - 1
run-combined-stack.sh

@@ -101,7 +101,7 @@ run_iris() {
101 101
   docker compose \
102 102
     --project-name iris-web \
103 103
     --project-directory "${ROOT_DIR}/iris-web" \
104
-    -f "${ROOT_DIR}/iris-web/docker-compose.yml" \
104
+    -f "${ROOT_DIR}/iris-web/docker-compose.dev.yml" \
105 105
     -f "${ROOT_DIR}/compose-overrides/iris.shared-network.yml" \
106 106
     "${COMMAND}" ${ARGS[@]+"${ARGS[@]}"}
107 107
 }

+ 358 - 0
scripts/seed-kpi-test-data.py

@@ -0,0 +1,358 @@
1
+#!/usr/bin/env python3
2
+"""
3
+seed-kpi-test-data.py — Create test IRIS alerts and cases for KPI dashboard UI testing.
4
+
5
+Creates a spread of records covering every KPI state:
6
+  On Track | Watch | Warning | Urgent | Critical | Breached | Resolved
7
+
8
+Usage:
9
+  python3 scripts/seed-kpi-test-data.py [--alerts-only] [--cases-only] [--dry-run]
10
+
11
+Env vars (override defaults):
12
+  IRIS_BASE_URL   default: https://localhost:8443
13
+  IRIS_API_KEY    required
14
+"""
15
+import argparse
16
+import json
17
+import os
18
+import ssl
19
+import sys
20
+import urllib.request
21
+from datetime import datetime, timedelta, timezone
22
+from pathlib import Path
23
+
24
+# ---------------------------------------------------------------------------
25
+# Config
26
+# ---------------------------------------------------------------------------
27
+
28
+def _read_env_file(path: str, key: str) -> str:
29
+    p = Path(path)
30
+    if not p.exists():
31
+        return ""
32
+    for line in p.read_text().splitlines():
33
+        if line.startswith(f"{key}="):
34
+            return line[len(key) + 1:].strip()
35
+    return ""
36
+
37
+BASE_DIR = Path(__file__).parent.parent
38
+ENV_FILE = BASE_DIR / "soc-integrator" / ".env"
39
+
40
+IRIS_BASE_URL = (
41
+    os.environ.get("IRIS_BASE_URL")
42
+    or _read_env_file(str(ENV_FILE), "IRIS_BASE_URL")
43
+    or "https://localhost:8443"
44
+).rstrip("/").replace("iriswebapp_nginx", "localhost")
45
+
46
+IRIS_API_KEY = (
47
+    os.environ.get("IRIS_API_KEY")
48
+    or _read_env_file(str(ENV_FILE), "IRIS_API_KEY")
49
+    or ""
50
+)
51
+
52
+if not IRIS_API_KEY:
53
+    sys.exit("error: IRIS_API_KEY not set. Export it or add it to soc-integrator/.env")
54
+
55
+# ---------------------------------------------------------------------------
56
+# HTTP helpers (no extra deps)
57
+# ---------------------------------------------------------------------------
58
+
59
+_ssl_ctx = ssl.create_default_context()
60
+_ssl_ctx.check_hostname = False
61
+_ssl_ctx.verify_mode = ssl.CERT_NONE
62
+
63
+
64
+def _req(method: str, path: str, body: dict | None = None) -> dict:
65
+    url = f"{IRIS_BASE_URL}{path}"
66
+    data = json.dumps(body).encode() if body else None
67
+    headers = {
68
+        "Authorization": f"Bearer {IRIS_API_KEY}",
69
+        "Content-Type": "application/json",
70
+    }
71
+    req = urllib.request.Request(url, data=data, headers=headers, method=method)
72
+    with urllib.request.urlopen(req, context=_ssl_ctx, timeout=15) as r:
73
+        return json.loads(r.read())
74
+
75
+
76
+def get(path: str) -> dict:
77
+    return _req("GET", path)
78
+
79
+
80
+def post(path: str, body: dict) -> dict:
81
+    return _req("POST", path, body)
82
+
83
+
84
+def put(path: str, body: dict) -> dict:
85
+    return _req("PUT", path, body)
86
+
87
+
88
+# ---------------------------------------------------------------------------
89
+# Lookup tables
90
+# ---------------------------------------------------------------------------
91
+
92
+def _get_severity_ids() -> dict[str, int]:
93
+    """Return name→id map for alert severities."""
94
+    data = get("/manage/severities/list")
95
+    items = (data.get("data") or [])
96
+    return {s["severity_name"].lower(): s["severity_id"] for s in items if "severity_name" in s}
97
+
98
+
99
+def _get_alert_status_ids() -> dict[str, int]:
100
+    data = get("/manage/alert-status/list")
101
+    items = data.get("data") or []
102
+    return {s["status_name"].lower(): s["status_id"] for s in items if "status_name" in s}
103
+
104
+
105
+def _get_resolution_status_ids() -> dict[str, int]:
106
+    try:
107
+        data = get("/manage/alert-resolutions/list")
108
+        items = data.get("data") or []
109
+        return {s["resolution_status_name"].lower(): s["resolution_status_id"]
110
+                for s in items if "resolution_status_name" in s}
111
+    except Exception:
112
+        return {}
113
+
114
+
115
+def _get_customer_id() -> int:
116
+    try:
117
+        data = get("/api/v2/customers")
118
+        items = (data.get("data") or {}).get("customers") or []
119
+        if items:
120
+            return items[0].get("customer_id", 1)
121
+    except Exception:
122
+        pass
123
+    return 1
124
+
125
+
126
+# ---------------------------------------------------------------------------
127
+# Alert scenarios
128
+# ---------------------------------------------------------------------------
129
+
130
+def _ts(offset_hours: float) -> str:
131
+    """ISO timestamp offset_hours ago (UTC, naive — what IRIS expects)."""
132
+    dt = datetime.now(timezone.utc) - timedelta(hours=offset_hours)
133
+    return dt.strftime("%Y-%m-%dT%H:%M:%S")
134
+
135
+
136
+def _date(offset_hours: float) -> str:
137
+    """Date string (YYYY-MM-DD) offset_hours ago — for case close_date."""
138
+    dt = datetime.now(timezone.utc) - timedelta(hours=offset_hours)
139
+    return dt.strftime("%Y-%m-%d")
140
+
141
+
142
+# Each tuple: (label, severity, created_hours_ago, resolved_hours_after_creation_or_None)
143
+# SLA: High=4h  Medium=8h  Low=24h
144
+ALERT_SCENARIOS = [
145
+    # --- High severity (4h SLA) ---
146
+    ("High / On Track (1h old)",       "High",   1.0,   None),   # 75% remaining
147
+    ("High / Watch (2.5h old)",        "High",   2.5,   None),   # ~37% remaining → Watch
148
+    ("High / Warning (3h old)",        "High",   3.0,   None),   # 25% remaining
149
+    ("High / Breached (6h old)",       "High",   6.0,   None),   # 0%
150
+    ("High / Resolved in SLA (2h)",    "High",   4.0,   2.0),    # resolved 2h after open → 50% KPI frozen
151
+    ("High / Resolved breached (5h)",  "High",   7.0,   5.0),    # resolved after SLA breach → Resolved/0%
152
+    # --- Medium severity (8h SLA) ---
153
+    ("Medium / On Track (1h old)",     "Medium", 1.0,   None),
154
+    ("Medium / Watch (3h old)",        "Medium", 3.0,   None),
155
+    ("Medium / Warning (5h old)",      "Medium", 5.0,   None),
156
+    ("Medium / Urgent (7h old)",       "Medium", 7.0,   None),
157
+    ("Medium / Critical (7.8h old)",   "Medium", 7.8,   None),
158
+    ("Medium / Breached (10h old)",    "Medium", 10.0,  None),
159
+    ("Medium / Resolved in SLA (4h)",  "Medium", 9.0,   4.0),
160
+    # --- Low severity (24h SLA) ---
161
+    ("Low / On Track (2h old)",        "Low",    2.0,   None),
162
+    ("Low / Warning (14h old)",        "Low",    14.0,  None),
163
+    ("Low / Breached (30h old)",       "Low",    30.0,  None),
164
+    ("Low / Resolved in SLA (12h)",    "Low",    25.0,  12.0),
165
+]
166
+
167
+# Case scenarios: (label, tags, created_hours_ago, close_hours_after_creation_or_None)
168
+CASE_SCENARIOS = [
169
+    ("High / Open On Track",           "High,wazuh",         1.0,   None),
170
+    ("High / Open Watch",              "High,brute-force",   2.5,   None),
171
+    ("High / Breached",                "High,lateral-movement", 6.0, None),
172
+    ("High / Resolved in SLA",         "High,exfiltration",  5.0,   2.0),
173
+    ("Medium / Open Watch",            "Medium,wazuh",       3.0,   None),
174
+    ("Medium / Open Urgent",           "Medium,phishing",    7.0,   None),
175
+    ("Medium / Breached",              "Medium,ransomware",  12.0,  None),
176
+    ("Medium / Resolved",              "Medium,malware",     10.0,  5.0),
177
+    ("Low / On Track",                 "Low,wazuh",          2.0,   None),
178
+    ("Low / Warning",                  "Low,recon",          14.0,  None),
179
+    ("Low / Resolved in SLA",          "Low,policy",         26.0,  10.0),
180
+]
181
+
182
+
183
+# ---------------------------------------------------------------------------
184
+# Create alerts
185
+# ---------------------------------------------------------------------------
186
+
187
+def create_alerts(sev_ids: dict, status_ids: dict, res_ids: dict, customer_id: int, dry_run: bool):
188
+    new_id = status_ids.get("new") or 2
189
+    closed_id = status_ids.get("closed") or 6
190
+    # Pick any "true positive" resolution, falling back to first available
191
+    res_tp_id = (
192
+        res_ids.get("true positive with impact")
193
+        or res_ids.get("true positive without impact")
194
+        or (list(res_ids.values())[0] if res_ids else 2)
195
+    )
196
+
197
+    print(f"\n=== Creating {len(ALERT_SCENARIOS)} alerts ===")
198
+    for label, sev_name, created_h, resolved_h in ALERT_SCENARIOS:
199
+        sev_id = sev_ids.get(sev_name.lower()) or sev_ids.get("medium") or 3
200
+        created_ts = _ts(created_h)
201
+
202
+        payload: dict = {
203
+            "alert_title": f"[KPI Test] {label}",
204
+            "alert_description": f"Seed data: {label}. Created {created_h}h ago.",
205
+            "alert_severity_id": sev_id,
206
+            "alert_status_id": new_id,
207
+            "alert_customer_id": customer_id,
208
+            "alert_source": "kpi-seed",
209
+            "alert_source_ref": "seed-kpi-test-data",
210
+            "alert_source_event_time": created_ts,
211
+            "alert_creation_time": created_ts,
212
+        }
213
+
214
+        if resolved_h is not None:
215
+            payload["alert_status_id"] = closed_id
216
+            if res_tp_id:
217
+                payload["alert_resolution_status_id"] = res_tp_id
218
+
219
+        if dry_run:
220
+            print(f"  DRY-RUN  {label}")
221
+            continue
222
+
223
+        try:
224
+            resp = post("/alerts/add", payload)
225
+            alert_data = resp.get("data") or {}
226
+            aid = alert_data.get("alert_id", "?")
227
+            print(f"  created  alert_id={aid}  {label}")
228
+        except Exception as exc:
229
+            print(f"  FAILED   {label}: {exc}")
230
+
231
+
232
+# ---------------------------------------------------------------------------
233
+# Create cases
234
+# ---------------------------------------------------------------------------
235
+
236
+def create_cases(customer_id: int, dry_run: bool):
237
+    print(f"\n=== Creating {len(CASE_SCENARIOS)} cases ===")
238
+    for label, tags, created_h, close_h in CASE_SCENARIOS:
239
+        open_date = _ts(created_h)
240
+        # close_date: a date-only string (IRIS v2 close_date is a date, not datetime)
241
+        close_date = _date(created_h - close_h) if close_h is not None else None
242
+
243
+        payload: dict = {
244
+            "case_name": f"[KPI Test] {label}",
245
+            "case_description": f"Seed data: {label}. Opened {created_h}h ago.",
246
+            "case_customer": customer_id,
247
+            "case_tags": tags,
248
+            "case_soc_id": "seed-kpi",
249
+        }
250
+
251
+        if dry_run:
252
+            print(f"  DRY-RUN  {label}")
253
+            continue
254
+
255
+        try:
256
+            resp = post("/api/v2/cases", payload)
257
+            # v2 create returns the case object directly (no data wrapper)
258
+            cid = resp.get("case_id") or (resp.get("data") or {}).get("case_id", "?")
259
+            print(f"  created  case_id={cid}  {label}")
260
+
261
+            # Close the case if needed — IRIS v2: PUT /api/v2/cases/{id} with close_date
262
+            if close_date and cid and cid != "?":
263
+                try:
264
+                    put(f"/api/v2/cases/{cid}", {"close_date": close_date})
265
+                    print(f"           └─ closed at {close_date}")
266
+                except Exception as exc:
267
+                    print(f"           └─ close failed: {exc}")
268
+        except Exception as exc:
269
+            print(f"  FAILED   {label}: {exc}")
270
+
271
+
272
+# ---------------------------------------------------------------------------
273
+# Main
274
+# ---------------------------------------------------------------------------
275
+
276
+def _backdate_alerts_via_db(scenarios: list, dry_run: bool):
277
+    """Update alert_creation_time and modification_history in Postgres via docker exec."""
278
+    import subprocess
279
+
280
+    lines = []
281
+    for label, sev, created_h, resolved_h in scenarios:
282
+        title_sql = label.replace("'", "''")
283
+        lines.append(
284
+            f"UPDATE alerts SET alert_creation_time = NOW() - INTERVAL '{int(created_h * 60)} minutes' "
285
+            f"WHERE alert_title = '[KPI Test] {title_sql}';"
286
+        )
287
+        if resolved_h is not None:
288
+            elapsed_h = created_h - resolved_h          # hours from now to resolution
289
+            lines.append(
290
+                f"WITH ts AS (SELECT EXTRACT(EPOCH FROM NOW() - INTERVAL '{int(elapsed_h * 60)} minutes') AS t) "
291
+                f"UPDATE alerts SET modification_history = jsonb_build_object((SELECT t::text FROM ts), "
292
+                f"'{{\"user\":\"seed\",\"action\":\"Alert resolved\"}}') "
293
+                f"WHERE alert_title = '[KPI Test] {title_sql}';"
294
+            )
295
+
296
+    sql = "\n".join(lines)
297
+    print("\n--- Backdating alert timestamps via docker exec ---")
298
+    if dry_run:
299
+        print("  DRY-RUN (SQL would be):")
300
+        print(sql[:500] + "...")
301
+        return
302
+    result = subprocess.run(
303
+        ["docker", "exec", "iriswebapp_db", "psql", "-U", "postgres", "-d", "iris_db", "-c", sql],
304
+        capture_output=True, text=True,
305
+    )
306
+    if result.returncode != 0:
307
+        print(f"  WARN: backdate failed: {result.stderr[:300]}")
308
+    else:
309
+        print("  done.")
310
+
311
+
312
+def main():
313
+    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
314
+    parser.add_argument("--alerts-only", action="store_true")
315
+    parser.add_argument("--cases-only", action="store_true")
316
+    parser.add_argument("--backdate", action="store_true",
317
+                        help="Update alert_creation_time in PostgreSQL via docker exec after creation")
318
+    parser.add_argument("--dry-run", action="store_true", help="Print what would be created without calling IRIS")
319
+    args = parser.parse_args()
320
+
321
+    print(f"IRIS: {IRIS_BASE_URL}")
322
+
323
+    if args.dry_run:
324
+        print("DRY-RUN mode — no requests will be made\n")
325
+        if not args.cases_only:
326
+            create_alerts({}, {}, {}, 1, dry_run=True)
327
+            if args.backdate:
328
+                _backdate_alerts_via_db(ALERT_SCENARIOS, dry_run=True)
329
+        if not args.alerts_only:
330
+            create_cases(1, dry_run=True)
331
+        return
332
+
333
+    print("Fetching IRIS lookup tables...")
334
+    try:
335
+        sev_ids = _get_severity_ids()
336
+        status_ids = _get_alert_status_ids()
337
+        res_ids = _get_resolution_status_ids()
338
+        customer_id = _get_customer_id()
339
+    except Exception as exc:
340
+        sys.exit(f"error: could not reach IRIS at {IRIS_BASE_URL}: {exc}")
341
+
342
+    print(f"  severities:    {sev_ids}")
343
+    print(f"  alert statuses:{status_ids}")
344
+    print(f"  resolution:    {res_ids}")
345
+    print(f"  customer_id:   {customer_id}")
346
+
347
+    if not args.cases_only:
348
+        create_alerts(sev_ids, status_ids, res_ids, customer_id, dry_run=False)
349
+        if args.backdate:
350
+            _backdate_alerts_via_db(ALERT_SCENARIOS, dry_run=False)
351
+    if not args.alerts_only:
352
+        create_cases(customer_id, dry_run=False)
353
+
354
+    print("\ndone.")
355
+
356
+
357
+if __name__ == "__main__":
358
+    main()

+ 95 - 1
soc-integrator/app/adapters/iris.py

@@ -67,8 +67,9 @@ class IrisAdapter:
67 67
         headers = self._headers()
68 68
         safe_limit = max(1, limit)
69 69
         safe_offset = max(0, offset)
70
+        page = (safe_offset // safe_limit) + 1
70 71
         v2_url = f"{self.base_url}/api/v2/cases"
71
-        params = {"limit": safe_limit, "offset": safe_offset}
72
+        params = {"page": page, "per_page": safe_limit}
72 73
         async with httpx.AsyncClient(verify=False, timeout=20.0) as client:
73 74
             response = await client.get(v2_url, params=params, headers=headers)
74 75
             active_url = v2_url
@@ -112,6 +113,9 @@ class IrisAdapter:
112 113
                 return {"status_code": response.status_code}
113 114
 
114 115
             result = response.json()
116
+            # IRIS v2 response: { "total": int, "data": [...], "last_page": int, ... }
117
+            if isinstance(result, dict) and isinstance(result.get("total"), int) and isinstance(result.get("data"), list):
118
+                return result  # pass v2 response through directly
115 119
             if isinstance(result, dict) and isinstance(result.get("data"), list):
116 120
                 total = result.get("recordsTotal")
117 121
                 if not isinstance(total, int):
@@ -125,3 +129,93 @@ class IrisAdapter:
125 129
                     "raw": result,
126 130
                 }
127 131
             return result
132
+
133
+    async def create_alert(self, payload: dict[str, Any]) -> dict[str, Any]:
134
+        headers = self._headers()
135
+        url = f"{self.base_url}/alerts/add"
136
+        async with httpx.AsyncClient(verify=False, timeout=20.0) as client:
137
+            response = await client.post(url, json=payload, headers=headers)
138
+            try:
139
+                response.raise_for_status()
140
+            except httpx.HTTPStatusError as exc:
141
+                detail = response.text.strip()
142
+                raise RuntimeError(
143
+                    f"IRIS returned {response.status_code} for {url}. Response: {detail}"
144
+                ) from exc
145
+            return response.json() if response.content else {"status_code": response.status_code}
146
+
147
+    async def get_case(self, case_id: int) -> dict[str, Any]:
148
+        headers = self._headers()
149
+        url = f"{self.base_url}/api/v2/cases/{case_id}"
150
+        async with httpx.AsyncClient(verify=False, timeout=20.0) as client:
151
+            response = await client.get(url, headers=headers)
152
+            try:
153
+                response.raise_for_status()
154
+            except httpx.HTTPStatusError as exc:
155
+                detail = response.text.strip()
156
+                raise RuntimeError(
157
+                    f"IRIS returned {response.status_code} for {url}. Response: {detail}"
158
+                ) from exc
159
+            return response.json() if response.content else {}
160
+
161
+    async def get_alert(self, alert_id: int) -> dict[str, Any]:
162
+        headers = self._headers()
163
+        url = f"{self.base_url}/alerts/{alert_id}"
164
+        async with httpx.AsyncClient(verify=False, timeout=20.0) as client:
165
+            response = await client.get(url, headers=headers)
166
+            try:
167
+                response.raise_for_status()
168
+            except httpx.HTTPStatusError as exc:
169
+                detail = response.text.strip()
170
+                raise RuntimeError(
171
+                    f"IRIS returned {response.status_code} for {url}. Response: {detail}"
172
+                ) from exc
173
+            result = response.json() if response.content else {}
174
+            # Legacy endpoint returns {"status": "success", "data": {...}}
175
+            return result.get("data", result)
176
+
177
+    async def list_alerts(
178
+        self,
179
+        page: int = 1,
180
+        per_page: int = 50,
181
+        sort_by: str = "alert_id",
182
+        sort_dir: str = "desc",
183
+        filter_title: str | None = None,
184
+        filter_owner_id: int | None = None,
185
+    ) -> dict[str, Any]:
186
+        headers = self._headers()
187
+        url = f"{self.base_url}/api/v2/alerts"
188
+        params: dict[str, Any] = {
189
+            "page": max(1, page),
190
+            "per_page": max(1, per_page),
191
+            "sort": f"{sort_by}:{sort_dir}",
192
+        }
193
+        if filter_title:
194
+            params["alert_title"] = filter_title
195
+        if filter_owner_id:
196
+            params["alert_owner_id"] = filter_owner_id
197
+        async with httpx.AsyncClient(verify=False, timeout=30.0) as client:
198
+            response = await client.get(url, params=params, headers=headers)
199
+            try:
200
+                response.raise_for_status()
201
+            except httpx.HTTPStatusError as exc:
202
+                detail = response.text.strip()
203
+                raise RuntimeError(
204
+                    f"IRIS returned {response.status_code} for {url}. Response: {detail}"
205
+                ) from exc
206
+            return response.json() if response.content else {"status_code": response.status_code}
207
+
208
+    async def assign_alert(self, alert_id: int, owner_id: int) -> dict[str, Any]:
209
+        headers = self._headers()
210
+        url = f"{self.base_url}/api/v2/alerts/{alert_id}"
211
+        payload = {"alert_owner_id": owner_id}
212
+        async with httpx.AsyncClient(verify=False, timeout=20.0) as client:
213
+            response = await client.put(url, json=payload, headers=headers)
214
+            try:
215
+                response.raise_for_status()
216
+            except httpx.HTTPStatusError as exc:
217
+                detail = response.text.strip()
218
+                raise RuntimeError(
219
+                    f"IRIS returned {response.status_code} for {url}. Response: {detail}"
220
+                ) from exc
221
+            return response.json() if response.content else {"status_code": response.status_code}

+ 362 - 1
soc-integrator/app/main.py

@@ -11,7 +11,9 @@ from pathlib import Path
11 11
 
12 12
 from psycopg import sql
13 13
 from fastapi import Depends, FastAPI, File, HTTPException, Request, UploadFile
14
-from fastapi.responses import FileResponse, Response
14
+import csv
15
+import io
16
+from fastapi.responses import FileResponse, Response, StreamingResponse
15 17
 from fastapi.staticfiles import StaticFiles
16 18
 
17 19
 from app.adapters.abuseipdb import AbuseIpdbAdapter
@@ -29,6 +31,7 @@ from app.models import (
29 31
     CDetectionEvaluateRequest,
30 32
     IocEnrichRequest,
31 33
     IocEvaluateRequest,
34
+    IrisAlertCreateRequest,
32 35
     IrisTicketCreateRequest,
33 36
     LogLossCheckRequest,
34 37
     LogLossStreamCheck,
@@ -2299,3 +2302,361 @@ async def monitor_c_detections_state() -> ApiResponse:
2299 2302
             "state": getattr(app.state, "c_detection_state", {}),
2300 2303
         }
2301 2304
     )
2305
+
2306
+
2307
+# ---------------------------------------------------------------------------
2308
+# KPI Timeout helpers and IRIS alert routes
2309
+# ---------------------------------------------------------------------------
2310
+
2311
+SLA_SECONDS: dict[str, int] = {"High": 14400, "Medium": 28800, "Low": 86400}
2312
+
2313
+
2314
+def compute_kpi(
2315
+    created_at: str,
2316
+    severity_name: str,
2317
+    resolved_at: str | None = None,
2318
+) -> dict[str, object]:
2319
+    sla = SLA_SECONDS.get(severity_name, 28800)
2320
+
2321
+    def _parse(ts: str) -> datetime:
2322
+        dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
2323
+        return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
2324
+
2325
+    start = _parse(created_at)
2326
+    thresholds = [("S1", "#22c55e", 25), ("S2", "#eab308", 50), ("S3", "#f97316", 75), ("S4", "#ef4444", 100)]
2327
+
2328
+    if resolved_at:
2329
+        end = _parse(resolved_at)
2330
+        elapsed = max(0, (end - start).total_seconds())  # clamp: close_date can't precede open_date
2331
+        elapsed_pct = min(elapsed / sla * 100, 100)
2332
+        kpi_pct = max(100 - elapsed_pct, 0)
2333
+        segments = [{"label": l, "color": c, "active": elapsed_pct >= t} for l, c, t in thresholds]
2334
+        return {
2335
+            "kpi_pct": round(kpi_pct, 1),
2336
+            "elapsed_pct": round(elapsed_pct, 1),
2337
+            "status": "Resolved",
2338
+            "segments": segments,
2339
+            "resolved": True,
2340
+        }
2341
+
2342
+    elapsed = (datetime.now(timezone.utc) - start).total_seconds()
2343
+    elapsed_pct = min(elapsed / sla * 100, 100)
2344
+    kpi_pct = max(100 - elapsed_pct, 0)
2345
+    segments = [{"label": l, "color": c, "active": elapsed_pct >= t} for l, c, t in thresholds]
2346
+    if kpi_pct >= 80:
2347
+        status = "On Track"
2348
+    elif kpi_pct >= 60:
2349
+        status = "Watch"
2350
+    elif kpi_pct >= 40:
2351
+        status = "Warning"
2352
+    elif kpi_pct >= 20:
2353
+        status = "Urgent"
2354
+    elif kpi_pct > 0:
2355
+        status = "Critical"
2356
+    else:
2357
+        status = "Breached"
2358
+    return {
2359
+        "kpi_pct": round(kpi_pct, 1),
2360
+        "elapsed_pct": round(elapsed_pct, 1),
2361
+        "status": status,
2362
+        "segments": segments,
2363
+        "resolved": False,
2364
+    }
2365
+
2366
+
2367
+def _enrich_alerts_with_kpi(iris_response: dict) -> dict:
2368
+    """Inject kpi field into each alert row returned by IRIS.
2369
+
2370
+    IRIS GET /api/v2/alerts returns: { "total": N, "data": [...], ... }
2371
+    """
2372
+    alerts = iris_response.get("data", [])
2373
+    if not isinstance(alerts, list):
2374
+        return iris_response
2375
+    for alert in alerts:
2376
+        created_at = alert.get("alert_creation_time") or ""
2377
+        severity = (alert.get("severity") or {}).get("severity_name", "Medium")
2378
+        if not created_at:
2379
+            continue
2380
+        resolved_at: str | None = None
2381
+        if alert.get("alert_resolution_status_id") is not None:
2382
+            history: dict = alert.get("modification_history") or {}
2383
+            if history:
2384
+                last_ts = max(history.keys(), key=lambda k: float(k))
2385
+                resolved_at = datetime.fromtimestamp(float(last_ts), tz=timezone.utc).isoformat()
2386
+        try:
2387
+            alert["kpi"] = compute_kpi(created_at, severity, resolved_at)
2388
+        except Exception:
2389
+            alert["kpi"] = {"kpi_pct": 0, "elapsed_pct": 100, "status": "Breached", "segments": [], "resolved": False}
2390
+    return iris_response
2391
+
2392
+
2393
+def _enrich_cases_with_kpi(iris_response: dict) -> dict:
2394
+    # v2 cases list: { "data": [...], "total": N, ... }
2395
+    # Each case uses open_date / close_date / state.state_name / severity_id
2396
+    _CASE_SEV: dict[int, str] = {1: "Medium", 4: "Low", 5: "High", 6: "High"}  # severity_id → name
2397
+    cases = iris_response.get("data") or iris_response.get("items", [])
2398
+    if not isinstance(cases, list):
2399
+        return iris_response
2400
+    for case in cases:
2401
+        created_at = case.get("open_date") or ""
2402
+        if not created_at:
2403
+            continue
2404
+        sev_id = case.get("severity_id") or 1
2405
+        severity = _CASE_SEV.get(int(sev_id), "Medium")
2406
+        resolved_at = None
2407
+        close_date = case.get("close_date")
2408
+        state_name = ((case.get("state") or {}).get("state_name") or "").lower()
2409
+        if close_date:
2410
+            resolved_at = close_date
2411
+        elif state_name == "closed":
2412
+            resolved_at = created_at
2413
+        try:
2414
+            case["kpi"] = compute_kpi(created_at, severity, resolved_at)
2415
+        except Exception:
2416
+            case["kpi"] = {"kpi_pct": 0, "elapsed_pct": 100, "status": "Breached", "segments": [], "resolved": False}
2417
+    return iris_response
2418
+
2419
+
2420
+@app.get(
2421
+    "/iris/cases/export-csv",
2422
+    summary="Export IRIS cases as CSV",
2423
+    description="Download all cases (up to 1000) with KPI as a CSV attachment.",
2424
+)
2425
+async def iris_export_cases_csv() -> StreamingResponse:
2426
+    try:
2427
+        raw = await iris_adapter.list_cases(limit=1000, offset=0)
2428
+    except Exception as exc:
2429
+        raise HTTPException(status_code=502, detail=f"IRIS case export failed: {exc}") from exc
2430
+    enriched = _enrich_cases_with_kpi(raw)
2431
+    cases = enriched.get("data") or enriched.get("items", [])
2432
+    _CASE_SEV: dict[int, str] = {1: "Medium", 4: "Low", 5: "High", 6: "High"}
2433
+    output = io.StringIO()
2434
+    fieldnames = ["case_id", "case_name", "severity", "state", "open_date", "close_date", "kpi_pct", "kpi_status"]
2435
+    writer = csv.DictWriter(output, fieldnames=fieldnames, extrasaction="ignore")
2436
+    writer.writeheader()
2437
+    for case in cases:
2438
+        kpi = case.get("kpi", {})
2439
+        writer.writerow({
2440
+            "case_id": case.get("case_id", ""),
2441
+            "case_name": case.get("case_name", ""),
2442
+            "severity": _CASE_SEV.get(int(case.get("severity_id") or 1), "Medium"),
2443
+            "state": (case.get("state") or {}).get("state_name", ""),
2444
+            "open_date": case.get("open_date", ""),
2445
+            "close_date": case.get("close_date", ""),
2446
+            "kpi_pct": kpi.get("kpi_pct", ""),
2447
+            "kpi_status": kpi.get("status", ""),
2448
+        })
2449
+    output.seek(0)
2450
+    return StreamingResponse(
2451
+        iter([output.getvalue()]),
2452
+        media_type="text/csv",
2453
+        headers={"Content-Disposition": "attachment; filename=iris_cases.csv"},
2454
+    )
2455
+
2456
+
2457
+@app.get(
2458
+    "/iris/cases/{case_id}",
2459
+    response_model=ApiResponse,
2460
+    summary="Get single IRIS case with KPI",
2461
+    description="Fetch one DFIR-IRIS case by ID and annotate with computed KPI data.",
2462
+)
2463
+async def iris_get_case(case_id: int) -> ApiResponse:
2464
+    try:
2465
+        raw = await iris_adapter.get_case(case_id)
2466
+    except Exception as exc:
2467
+        raise HTTPException(status_code=502, detail=f"IRIS case fetch failed: {exc}") from exc
2468
+    wrapper = {"data": [raw]}
2469
+    enriched = _enrich_cases_with_kpi(wrapper)
2470
+    case_out = enriched["data"][0] if enriched.get("data") else raw
2471
+    return ApiResponse(data={"case": case_out})
2472
+
2473
+
2474
+@app.get(
2475
+    "/iris/cases",
2476
+    response_model=ApiResponse,
2477
+    summary="List IRIS cases with KPI",
2478
+    description="Fetch cases from DFIR-IRIS and annotate each with computed KPI data.",
2479
+)
2480
+async def iris_list_cases(
2481
+    page: int = 1,
2482
+    per_page: int = 20,
2483
+    sort_by: str = "case_id",
2484
+    sort_dir: str = "desc",
2485
+    filter_name: str | None = None,
2486
+) -> ApiResponse:
2487
+    # adapter maps (limit, offset) → (per_page, page) for IRIS v2
2488
+    offset = (page - 1) * per_page
2489
+    try:
2490
+        raw = await iris_adapter.list_cases(limit=per_page, offset=offset)
2491
+    except Exception as exc:
2492
+        raise HTTPException(status_code=502, detail=f"IRIS case list failed: {exc}") from exc
2493
+    enriched = _enrich_cases_with_kpi(raw)
2494
+    items = enriched.get("data") or enriched.get("items", [])
2495
+    total = enriched.get("total", len(items))
2496
+    last_page = enriched.get("last_page", max(1, -(-total // per_page)))
2497
+    if filter_name:
2498
+        items = [c for c in items if filter_name.lower() in (c.get("case_name") or "").lower()]
2499
+    reverse = sort_dir == "desc"
2500
+    items.sort(key=lambda c: c.get(sort_by) or 0, reverse=reverse)
2501
+    return ApiResponse(data={"cases": {
2502
+        "data": items,
2503
+        "total": total,
2504
+        "current_page": page,
2505
+        "last_page": last_page,
2506
+    }})
2507
+
2508
+
2509
+@app.post(
2510
+    "/iris/alerts",
2511
+    response_model=ApiResponse,
2512
+    summary="Create IRIS alert",
2513
+    description="Create a new alert in DFIR-IRIS via /api/v2/alerts.",
2514
+)
2515
+async def iris_create_alert(payload: IrisAlertCreateRequest) -> ApiResponse:
2516
+    alert_payload: dict[str, Any] = {
2517
+        "alert_title": payload.title,
2518
+        "alert_description": payload.description,
2519
+        "alert_severity_id": payload.severity_id,
2520
+        "alert_status_id": payload.status_id,
2521
+        "alert_source": payload.source,
2522
+        "alert_customer_id": payload.customer_id or settings.iris_default_customer_id,
2523
+        "alert_source_event_time": datetime.now(timezone.utc).isoformat(),
2524
+    }
2525
+    if payload.source_ref:
2526
+        alert_payload["alert_source_ref"] = payload.source_ref
2527
+    if payload.payload:
2528
+        alert_payload.update(payload.payload)
2529
+    try:
2530
+        result = await iris_adapter.create_alert(alert_payload)
2531
+    except Exception as exc:
2532
+        raise HTTPException(status_code=502, detail=f"IRIS alert create failed: {exc}") from exc
2533
+    return ApiResponse(data={"alert": result})
2534
+
2535
+
2536
+@app.get(
2537
+    "/iris/alerts",
2538
+    response_model=ApiResponse,
2539
+    summary="List IRIS alerts with KPI Timeout",
2540
+    description="Fetch alerts from DFIR-IRIS and annotate each row with computed KPI Timeout data.",
2541
+)
2542
+async def iris_list_alerts(
2543
+    page: int = 1,
2544
+    per_page: int = 20,
2545
+    sort_by: str = "alert_id",
2546
+    sort_dir: str = "desc",
2547
+    filter_title: str | None = None,
2548
+    filter_owner_id: int | None = None,
2549
+) -> ApiResponse:
2550
+    try:
2551
+        raw = await iris_adapter.list_alerts(
2552
+            page=page,
2553
+            per_page=per_page,
2554
+            sort_by=sort_by,
2555
+            sort_dir=sort_dir,
2556
+            filter_title=filter_title,
2557
+            filter_owner_id=filter_owner_id,
2558
+        )
2559
+        enriched = _enrich_alerts_with_kpi(raw)
2560
+        return ApiResponse(data={
2561
+            "alerts": {
2562
+                "data": enriched.get("data", []),
2563
+                "total": enriched.get("total", 0),
2564
+                "current_page": enriched.get("current_page", page),
2565
+                "last_page": enriched.get("last_page", 1),
2566
+            }
2567
+        })
2568
+    except Exception as exc:
2569
+        raise HTTPException(status_code=502, detail=f"IRIS alert list failed: {exc}") from exc
2570
+
2571
+
2572
+@app.get(
2573
+    "/iris/alerts/export-csv",
2574
+    summary="Export IRIS alerts as CSV",
2575
+    description="Download all matching alerts (up to 1000) as a CSV attachment.",
2576
+)
2577
+async def iris_export_alerts_csv(
2578
+    sort_by: str = "alert_id",
2579
+    sort_dir: str = "desc",
2580
+    filter_title: str | None = None,
2581
+    filter_owner_id: int | None = None,
2582
+) -> StreamingResponse:
2583
+    try:
2584
+        raw = await iris_adapter.list_alerts(
2585
+            page=1,
2586
+            per_page=1000,
2587
+            sort_by=sort_by,
2588
+            sort_dir=sort_dir,
2589
+            filter_title=filter_title,
2590
+            filter_owner_id=filter_owner_id,
2591
+        )
2592
+    except Exception as exc:
2593
+        raise HTTPException(status_code=502, detail=f"IRIS alert export failed: {exc}") from exc
2594
+
2595
+    enriched = _enrich_alerts_with_kpi(raw)
2596
+    alerts = enriched.get("data", [])
2597
+
2598
+    output = io.StringIO()
2599
+    fieldnames = [
2600
+        "alert_id", "alert_title", "alert_severity", "alert_status",
2601
+        "alert_creation_time", "alert_source_event_time", "alert_owner",
2602
+        "kpi_pct", "kpi_status",
2603
+    ]
2604
+    writer = csv.DictWriter(output, fieldnames=fieldnames, extrasaction="ignore")
2605
+    writer.writeheader()
2606
+    for alert in alerts:
2607
+        kpi = alert.get("kpi", {})
2608
+        severity_name = (alert.get("severity") or {}).get("severity_name", "")
2609
+        writer.writerow({
2610
+            "alert_id": alert.get("alert_id", ""),
2611
+            "alert_title": alert.get("alert_title", ""),
2612
+            "alert_severity": severity_name,
2613
+            "alert_status": (alert.get("status") or {}).get("status_name", ""),
2614
+            "alert_creation_time": alert.get("alert_creation_time", ""),
2615
+            "alert_source_event_time": alert.get("alert_source_event_time", ""),
2616
+            "alert_owner": (alert.get("owner") or {}).get("user_name", ""),
2617
+            "kpi_pct": kpi.get("kpi_pct", ""),
2618
+            "kpi_status": kpi.get("status", ""),
2619
+        })
2620
+
2621
+    output.seek(0)
2622
+    return StreamingResponse(
2623
+        iter([output.getvalue()]),
2624
+        media_type="text/csv",
2625
+        headers={"Content-Disposition": "attachment; filename=iris_alerts.csv"},
2626
+    )
2627
+
2628
+
2629
+@app.get(
2630
+    "/iris/alerts/{alert_id}",
2631
+    response_model=ApiResponse,
2632
+    summary="Get single IRIS alert with KPI",
2633
+    description="Fetch one DFIR-IRIS alert by ID and annotate with computed KPI data.",
2634
+)
2635
+async def iris_get_alert(alert_id: int) -> ApiResponse:
2636
+    try:
2637
+        raw = await iris_adapter.get_alert(alert_id)
2638
+    except Exception as exc:
2639
+        raise HTTPException(status_code=502, detail=f"IRIS alert fetch failed: {exc}") from exc
2640
+    # Wrap in list-shaped dict so _enrich_alerts_with_kpi can process it
2641
+    alert = raw if isinstance(raw, dict) else {}
2642
+    wrapper = {"data": [alert]}
2643
+    enriched = _enrich_alerts_with_kpi(wrapper)
2644
+    alert_out = enriched["data"][0] if enriched.get("data") else alert
2645
+    return ApiResponse(data={"alert": alert_out})
2646
+
2647
+
2648
+@app.post(
2649
+    "/iris/alerts/{alert_id}/assign",
2650
+    response_model=ApiResponse,
2651
+    summary="Assign IRIS alert to owner",
2652
+    description="Update the owner of a DFIR-IRIS alert.",
2653
+)
2654
+async def iris_assign_alert(alert_id: int, body: dict) -> ApiResponse:
2655
+    owner_id = body.get("owner_id")
2656
+    if not isinstance(owner_id, int):
2657
+        raise HTTPException(status_code=422, detail="owner_id must be an integer")
2658
+    try:
2659
+        result = await iris_adapter.assign_alert(alert_id=alert_id, owner_id=owner_id)
2660
+        return ApiResponse(data=result)
2661
+    except Exception as exc:
2662
+        raise HTTPException(status_code=502, detail=f"IRIS alert assign failed: {exc}") from exc

+ 26 - 0
soc-integrator/app/models.py

@@ -355,6 +355,32 @@ class SimLogRunRequest(BaseModel):
355 355
     forever: bool = Field(default=False, description="Run continuously until stopped.", examples=[False])
356 356
 
357 357
 
358
+class IrisAlertCreateRequest(BaseModel):
359
+    model_config = ConfigDict(
360
+        json_schema_extra={
361
+            "example": {
362
+                "title": "Suspicious login detected",
363
+                "description": "Multiple failed logins followed by success from unusual IP",
364
+                "severity_id": 4,
365
+                "status_id": 2,
366
+                "source": "wazuh",
367
+                "source_ref": "wazuh-alert-12345",
368
+                "customer_id": 1,
369
+                "payload": {"alert_tags": "brute-force,authentication"},
370
+            }
371
+        }
372
+    )
373
+
374
+    title: str = Field(description="Alert title.", examples=["Suspicious login detected"])
375
+    description: str = Field(default="Created by soc-integrator", description="Alert description.")
376
+    severity_id: int = Field(default=3, description="IRIS severity ID (1=Info,2=Low,3=Medium,4=High,5=Critical).", examples=[4])
377
+    status_id: int = Field(default=2, description="IRIS alert status ID.", examples=[2])
378
+    source: str = Field(default="soc-integrator", description="Alert source name.", examples=["wazuh"])
379
+    source_ref: str | None = Field(default=None, description="Source-system reference ID.", examples=["wazuh-alert-12345"])
380
+    customer_id: int | None = Field(default=None, description="IRIS customer ID (defaults to configured value).")
381
+    payload: dict[str, Any] = Field(default_factory=dict, description="Additional IRIS alert fields merged into the request.")
382
+
383
+
358 384
 class ApiResponse(BaseModel):
359 385
     ok: bool = True
360 386
     message: str = "ok"

tum/whitesports - Gogs: Simplico Git Service

Nenhuma Descrição

class.jetpack-cli.php 69KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092
  1. <?php
  2. use Automattic\Jetpack\Connection\Client;
  3. use Automattic\Jetpack\Connection\Manager as Connection_Manager;
  4. use Automattic\Jetpack\Connection\Tokens;
  5. use Automattic\Jetpack\Identity_Crisis;
  6. use Automattic\Jetpack\Status;
  7. use Automattic\Jetpack\Sync\Actions;
  8. use Automattic\Jetpack\Sync\Listener;
  9. use Automattic\Jetpack\Sync\Modules;
  10. use Automattic\Jetpack\Sync\Queue;
  11. use Automattic\Jetpack\Sync\Settings;
  12. WP_CLI::add_command( 'jetpack', 'Jetpack_CLI' );
  13. /**
  14. * Control your local Jetpack installation.
  15. */
  16. class Jetpack_CLI extends WP_CLI_Command {
  17. // Aesthetics.
  18. public $green_open = "\033[32m";
  19. public $red_open = "\033[31m";
  20. public $yellow_open = "\033[33m";
  21. public $color_close = "\033[0m";
  22. /**
  23. * Get Jetpack Details
  24. *
  25. * ## OPTIONS
  26. *
  27. * empty: Leave it empty for basic stats
  28. *
  29. * full: View full stats. It's the data from the heartbeat
  30. *
  31. * ## EXAMPLES
  32. *
  33. * wp jetpack status
  34. * wp jetpack status full
  35. */
  36. public function status( $args, $assoc_args ) {
  37. jetpack_require_lib( 'debugger' );
  38. /* translators: %s is the site URL */
  39. WP_CLI::line( sprintf( __( 'Checking status for %s', 'jetpack' ), esc_url( get_home_url() ) ) );
  40. if ( isset( $args[0] ) && 'full' !== $args[0] ) {
  41. /* translators: %s is a command like "prompt" */
  42. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $args[0] ) );
  43. }
  44. $master_user_email = Jetpack::get_master_user_email();
  45. $cxntests = new Jetpack_Cxn_Tests();
  46. if ( $cxntests->pass() ) {
  47. $cxntests->output_results_for_cli();
  48. WP_CLI::success( __( 'Jetpack is currently connected to WordPress.com', 'jetpack' ) );
  49. } else {
  50. $error = array();
  51. foreach ( $cxntests->list_fails() as $fail ) {
  52. $error[] = $fail['name'] . ': ' . $fail['message'];
  53. }
  54. WP_CLI::error_multi_line( $error );
  55. $cxntests->output_results_for_cli();
  56. WP_CLI::error( __( 'One or more tests did not pass. Please investigate!', 'jetpack' ) ); // Exit CLI.
  57. }
  58. /* translators: %s is current version of Jetpack, for example 7.3 */
  59. WP_CLI::line( sprintf( __( 'The Jetpack Version is %s', 'jetpack' ), JETPACK__VERSION ) );
  60. /* translators: %d is WP.com ID of this blog */
  61. WP_CLI::line( sprintf( __( 'The WordPress.com blog_id is %d', 'jetpack' ), Jetpack_Options::get_option( 'id' ) ) );
  62. /* translators: %s is the email address of the connection owner */
  63. WP_CLI::line( sprintf( __( 'The WordPress.com account for the primary connection is %s', 'jetpack' ), $master_user_email ) );
  64. /*
  65. * Are they asking for all data?
  66. *
  67. * Loop through heartbeat data and organize by priority.
  68. */
  69. $all_data = ( isset( $args[0] ) && 'full' == $args[0] ) ? 'full' : false;
  70. if ( $all_data ) {
  71. // Heartbeat data
  72. WP_CLI::line( "\n" . __( 'Additional data: ', 'jetpack' ) );
  73. // Get the filtered heartbeat data.
  74. // Filtered so we can color/list by severity
  75. $stats = Jetpack::jetpack_check_heartbeat_data();
  76. // Display red flags first
  77. foreach ( $stats['bad'] as $stat => $value ) {
  78. printf( "$this->red_open%-'.16s %s $this->color_close\n", $stat, $value );
  79. }
  80. // Display caution warnings next
  81. foreach ( $stats['caution'] as $stat => $value ) {
  82. printf( "$this->yellow_open%-'.16s %s $this->color_close\n", $stat, $value );
  83. }
  84. // The rest of the results are good!
  85. foreach ( $stats['good'] as $stat => $value ) {
  86. // Modules should get special spacing for aestetics
  87. if ( strpos( $stat, 'odule-' ) ) {
  88. printf( "%-'.30s %s\n", $stat, $value );
  89. usleep( 4000 ); // For dramatic effect lolz
  90. continue;
  91. }
  92. printf( "%-'.16s %s\n", $stat, $value );
  93. usleep( 4000 ); // For dramatic effect lolz
  94. }
  95. } else {
  96. // Just the basics
  97. WP_CLI::line( "\n" . _x( "View full status with 'wp jetpack status full'", '"wp jetpack status full" is a command - do not translate', 'jetpack' ) );
  98. }
  99. }
  100. /**
  101. * Tests the active connection
  102. *
  103. * Does a two-way test to verify that the local site can communicate with remote Jetpack/WP.com servers and that Jetpack/WP.com servers can talk to the local site.
  104. *
  105. * ## EXAMPLES
  106. *
  107. * wp jetpack test-connection
  108. *
  109. * @subcommand test-connection
  110. */
  111. public function test_connection( $args, $assoc_args ) {
  112. /* translators: %s is the site URL */
  113. WP_CLI::line( sprintf( __( 'Testing connection for %s', 'jetpack' ), esc_url( get_site_url() ) ) );
  114. if ( ! Jetpack::is_connection_ready() ) {
  115. WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
  116. }
  117. $response = Client::wpcom_json_api_request_as_blog(
  118. sprintf( '/jetpack-blogs/%d/test-connection', Jetpack_Options::get_option( 'id' ) ),
  119. Client::WPCOM_JSON_API_VERSION
  120. );
  121. if ( is_wp_error( $response ) ) {
  122. /* translators: %1$s is the error code, %2$s is the error message */
  123. WP_CLI::error( sprintf( __( 'Failed to test connection (#%1$s: %2$s)', 'jetpack' ), $response->get_error_code(), $response->get_error_message() ) );
  124. }
  125. $body = wp_remote_retrieve_body( $response );
  126. if ( ! $body ) {
  127. WP_CLI::error( __( 'Failed to test connection (empty response body)', 'jetpack' ) );
  128. }
  129. $result = json_decode( $body );
  130. $is_connected = (bool) $result->connected;
  131. $message = $result->message;
  132. if ( $is_connected ) {
  133. WP_CLI::success( $message );
  134. } else {
  135. WP_CLI::error( $message );
  136. }
  137. }
  138. /**
  139. * Disconnect Jetpack Blogs or Users
  140. *
  141. * ## OPTIONS
  142. *
  143. * blog: Disconnect the entire blog.
  144. *
  145. * user <user_identifier>: Disconnect a specific user from WordPress.com.
  146. *
  147. * [--force]
  148. * If the user ID provided is the connection owner, it will only be disconnected if --force is passed
  149. *
  150. * ## EXAMPLES
  151. *
  152. * wp jetpack disconnect blog
  153. * wp jetpack disconnect user 13
  154. * wp jetpack disconnect user 1 --force
  155. * wp jetpack disconnect user username
  156. * wp jetpack disconnect user email@domain.com
  157. *
  158. * @synopsis <blog|user> [<user_identifier>] [--force]
  159. */
  160. public function disconnect( $args, $assoc_args ) {
  161. if ( ! Jetpack::is_connection_ready() ) {
  162. WP_CLI::success( __( 'The site is not currently connected, so nothing to do!', 'jetpack' ) );
  163. return;
  164. }
  165. $action = isset( $args[0] ) ? $args[0] : 'prompt';
  166. if ( ! in_array( $action, array( 'blog', 'user', 'prompt' ) ) ) {
  167. /* translators: %s is a command like "prompt" */
  168. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
  169. }
  170. if ( in_array( $action, array( 'user' ) ) ) {
  171. if ( isset( $args[1] ) ) {
  172. $user_id = $args[1];
  173. if ( ctype_digit( $user_id ) ) {
  174. $field = 'id';
  175. $user_id = (int) $user_id;
  176. } elseif ( is_email( $user_id ) ) {
  177. $field = 'email';
  178. $user_id = sanitize_user( $user_id, true );
  179. } else {
  180. $field = 'login';
  181. $user_id = sanitize_user( $user_id, true );
  182. }
  183. if ( ! $user = get_user_by( $field, $user_id ) ) {
  184. WP_CLI::error( __( 'Please specify a valid user.', 'jetpack' ) );
  185. }
  186. } else {
  187. WP_CLI::error( __( 'Please specify a user by either ID, username, or email.', 'jetpack' ) );
  188. }
  189. }
  190. $force_user_disconnect = ! empty( $assoc_args['force'] );
  191. switch ( $action ) {
  192. case 'blog':
  193. Jetpack::log( 'disconnect' );
  194. Jetpack::disconnect();
  195. WP_CLI::success(
  196. sprintf(
  197. /* translators: %s is the site URL */
  198. __( 'Jetpack has been successfully disconnected for %s.', 'jetpack' ),
  199. esc_url( get_site_url() )
  200. )
  201. );
  202. break;
  203. case 'user':
  204. $connection_manager = new Connection_Manager( 'jetpack' );
  205. $disconnected = $connection_manager->disconnect_user( $user->ID, $force_user_disconnect );
  206. if ( $disconnected ) {
  207. Jetpack::log( 'unlink', $user->ID );
  208. WP_CLI::success( __( 'User has been successfully disconnected.', 'jetpack' ) );
  209. } else {
  210. if ( ! $connection_manager->is_user_connected( $user->ID ) ) {
  211. /* translators: %s is a username */
  212. $error_message = sprintf( __( 'User %s could not be disconnected because it is not connected!', 'jetpack' ), "{$user->data->user_login} <{$user->data->user_email}>" );
  213. } elseif ( ! $force_user_disconnect && $connection_manager->is_connection_owner( $user->ID ) ) {
  214. /* translators: %s is a username */
  215. $error_message = sprintf( __( 'User %s could not be disconnected because it is the connection owner! If you want to disconnect in anyway, use the --force parameter.', 'jetpack' ), "{$user->data->user_login} <{$user->data->user_email}>" );
  216. } else {
  217. /* translators: %s is a username */
  218. $error_message = sprintf( __( 'User %s could not be disconnected.', 'jetpack' ), "{$user->data->user_login} <{$user->data->user_email}>" );
  219. }
  220. WP_CLI::error( $error_message );
  221. }
  222. break;
  223. case 'prompt':
  224. WP_CLI::error( __( 'Please specify if you would like to disconnect a blog or user.', 'jetpack' ) );
  225. break;
  226. }
  227. }
  228. /**
  229. * Reset Jetpack options and settings to default
  230. *
  231. * ## OPTIONS
  232. *
  233. * modules: Resets modules to default state ( get_default_modules() )
  234. *
  235. * options: Resets all Jetpack options except:
  236. * - All private options (Blog token, user token, etc...)
  237. * - id (The Client ID/WP.com Blog ID of this site)
  238. * - master_user
  239. * - version
  240. * - activated
  241. *
  242. * ## EXAMPLES
  243. *
  244. * wp jetpack reset options
  245. * wp jetpack reset modules
  246. * wp jetpack reset sync-checksum --dry-run --offset=0
  247. *
  248. * @synopsis <modules|options|sync-checksum> [--dry-run] [--offset=<offset>]
  249. */
  250. public function reset( $args, $assoc_args ) {
  251. $action = isset( $args[0] ) ? $args[0] : 'prompt';
  252. if ( ! in_array( $action, array( 'options', 'modules', 'sync-checksum' ), true ) ) {
  253. /* translators: %s is a command like "prompt" */
  254. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
  255. }
  256. $is_dry_run = ! empty( $assoc_args['dry-run'] );
  257. if ( $is_dry_run ) {
  258. WP_CLI::warning(
  259. __( "\nThis is a dry run.\n", 'jetpack' ) .
  260. __( "No actions will be taken.\n", 'jetpack' ) .
  261. __( "The following messages will give you preview of what will happen when you run this command.\n\n", 'jetpack' )
  262. );
  263. } else {
  264. // We only need to confirm "Are you sure?" when we are not doing a dry run.
  265. jetpack_cli_are_you_sure();
  266. }
  267. switch ( $action ) {
  268. case 'options':
  269. $options_to_reset = Jetpack_Options::get_options_for_reset();
  270. // Reset the Jetpack options
  271. WP_CLI::line(
  272. sprintf(
  273. /* translators: %s is the site URL */
  274. __( "Resetting Jetpack Options for %s...\n", 'jetpack' ),
  275. esc_url( get_site_url() )
  276. )
  277. );
  278. sleep( 1 ); // Take a breath
  279. foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
  280. if ( ! $is_dry_run ) {
  281. Jetpack_Options::delete_option( $option_to_reset );
  282. usleep( 100000 );
  283. }
  284. /* translators: This is the result of an action. The option named %s was reset */
  285. WP_CLI::success( sprintf( __( '%s option reset', 'jetpack' ), $option_to_reset ) );
  286. }
  287. // Reset the WP options
  288. WP_CLI::line( __( "Resetting the jetpack options stored in wp_options...\n", 'jetpack' ) );
  289. usleep( 500000 ); // Take a breath
  290. foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
  291. if ( ! $is_dry_run ) {
  292. delete_option( $option_to_reset );
  293. usleep( 100000 );
  294. }
  295. /* translators: This is the result of an action. The option named %s was reset */
  296. WP_CLI::success( sprintf( __( '%s option reset', 'jetpack' ), $option_to_reset ) );
  297. }
  298. // Reset to default modules
  299. WP_CLI::line( __( "Resetting default modules...\n", 'jetpack' ) );
  300. usleep( 500000 ); // Take a breath
  301. $default_modules = Jetpack::get_default_modules();
  302. if ( ! $is_dry_run ) {
  303. Jetpack::update_active_modules( $default_modules );
  304. }
  305. WP_CLI::success( __( 'Modules reset to default.', 'jetpack' ) );
  306. break;
  307. case 'modules':
  308. if ( ! $is_dry_run ) {
  309. $default_modules = Jetpack::get_default_modules();
  310. Jetpack::update_active_modules( $default_modules );
  311. }
  312. WP_CLI::success( __( 'Modules reset to default.', 'jetpack' ) );
  313. break;
  314. case 'prompt':
  315. WP_CLI::error( __( 'Please specify if you would like to reset your options, modules or sync-checksum', 'jetpack' ) );
  316. break;
  317. case 'sync-checksum':
  318. $option = 'jetpack_callables_sync_checksum';
  319. if ( is_multisite() ) {
  320. $offset = isset( $assoc_args['offset'] ) ? (int) $assoc_args['offset'] : 0;
  321. /*
  322. * 1000 is a good limit since we don't expect the number of sites to be more than 1000
  323. * Offset can be used to paginate and try to clean up more sites.
  324. */
  325. $sites = get_sites(
  326. array(
  327. 'number' => 1000,
  328. 'offset' => $offset,
  329. )
  330. );
  331. $count_fixes = 0;
  332. foreach ( $sites as $site ) {
  333. switch_to_blog( $site->blog_id );
  334. $count = self::count_option( $option );
  335. if ( $count > 1 ) {
  336. if ( ! $is_dry_run ) {
  337. delete_option( $option );
  338. }
  339. WP_CLI::line(
  340. sprintf(
  341. /* translators: %1$d is a number, %2$s is the name of an option, %2$s is the site URL. */
  342. __( 'Deleted %1$d %2$s options from %3$s', 'jetpack' ),
  343. $count,
  344. $option,
  345. "{$site->domain}{$site->path}"
  346. )
  347. );
  348. $count_fixes++;
  349. if ( ! $is_dry_run ) {
  350. /*
  351. * We could be deleting a lot of options rows at the same time.
  352. * Allow some time for replication to catch up.
  353. */
  354. sleep( 3 );
  355. }
  356. }
  357. restore_current_blog();
  358. }
  359. if ( $count_fixes ) {
  360. WP_CLI::success(
  361. sprintf(
  362. /* translators: %1$s is the name of an option, %2$d is a number of sites. */
  363. __( 'Successfully reset %1$s on %2$d sites.', 'jetpack' ),
  364. $option,
  365. $count_fixes
  366. )
  367. );
  368. } else {
  369. WP_CLI::success( __( 'No options were deleted.', 'jetpack' ) );
  370. }
  371. return;
  372. }
  373. $count = self::count_option( $option );
  374. if ( $count > 1 ) {
  375. if ( ! $is_dry_run ) {
  376. delete_option( $option );
  377. }
  378. WP_CLI::success(
  379. sprintf(
  380. /* translators: %1$d is a number, %2$s is the name of an option. */
  381. __( 'Deleted %1$d %2$s options', 'jetpack' ),
  382. $count,
  383. $option
  384. )
  385. );
  386. return;
  387. }
  388. WP_CLI::success( __( 'No options were deleted.', 'jetpack' ) );
  389. break;
  390. }
  391. }
  392. /**
  393. * Return the number of times an option appears
  394. * Normally an option would only appear 1 since the option key is supposed to be unique
  395. * but if a site hasn't updated the DB schema then that would not be the case.
  396. *
  397. * @param string $option Option name.
  398. *
  399. * @return int
  400. */
  401. private static function count_option( $option ) {
  402. global $wpdb;
  403. return (int) $wpdb->get_var(
  404. $wpdb->prepare(
  405. "SELECT COUNT(*) FROM $wpdb->options WHERE option_name = %s",
  406. $option
  407. )
  408. );
  409. }
  410. /**
  411. * Manage Jetpack Modules
  412. *
  413. * ## OPTIONS
  414. *
  415. * <list|activate|deactivate|toggle>
  416. * : The action to take.
  417. * ---
  418. * default: list
  419. * options:
  420. * - list
  421. * - activate
  422. * - deactivate
  423. * - toggle
  424. * ---
  425. *
  426. * [<module_slug>]
  427. * : The slug of the module to perform an action on.
  428. *
  429. * [--format=<format>]
  430. * : Allows overriding the output of the command when listing modules.
  431. * ---
  432. * default: table
  433. * options:
  434. * - table
  435. * - json
  436. * - csv
  437. * - yaml
  438. * - ids
  439. * - count
  440. * ---
  441. *
  442. * ## EXAMPLES
  443. *
  444. * wp jetpack module list
  445. * wp jetpack module list --format=json
  446. * wp jetpack module activate stats
  447. * wp jetpack module deactivate stats
  448. * wp jetpack module toggle stats
  449. * wp jetpack module activate all
  450. * wp jetpack module deactivate all
  451. */
  452. public function module( $args, $assoc_args ) {
  453. $action = isset( $args[0] ) ? $args[0] : 'list';
  454. if ( isset( $args[1] ) ) {
  455. $module_slug = $args[1];
  456. if ( 'all' !== $module_slug && ! Jetpack::is_module( $module_slug ) ) {
  457. /* translators: %s is a module slug like "stats" */
  458. WP_CLI::error( sprintf( __( '%s is not a valid module.', 'jetpack' ), $module_slug ) );
  459. }
  460. if ( 'toggle' === $action ) {
  461. $action = Jetpack::is_module_active( $module_slug )
  462. ? 'deactivate'
  463. : 'activate';
  464. }
  465. if ( 'all' === $args[1] ) {
  466. $action = ( 'deactivate' === $action )
  467. ? 'deactivate_all'
  468. : 'activate_all';
  469. }
  470. } elseif ( 'list' !== $action ) {
  471. WP_CLI::line( __( 'Please specify a valid module.', 'jetpack' ) );
  472. $action = 'list';
  473. }
  474. switch ( $action ) {
  475. case 'list':
  476. $modules_list = array();
  477. $modules = Jetpack::get_available_modules();
  478. sort( $modules );
  479. foreach ( (array) $modules as $module_slug ) {
  480. if ( 'vaultpress' === $module_slug ) {
  481. continue;
  482. }
  483. $modules_list[] = array(
  484. 'slug' => $module_slug,
  485. 'status' => Jetpack::is_module_active( $module_slug )
  486. ? __( 'Active', 'jetpack' )
  487. : __( 'Inactive', 'jetpack' ),
  488. );
  489. }
  490. WP_CLI\Utils\format_items( $assoc_args['format'], $modules_list, array( 'slug', 'status' ) );
  491. break;
  492. case 'activate':
  493. $module = Jetpack::get_module( $module_slug );
  494. Jetpack::log( 'activate', $module_slug );
  495. if ( Jetpack::activate_module( $module_slug, false, false ) ) {
  496. /* translators: %s is the name of a Jetpack module */
  497. WP_CLI::success( sprintf( __( '%s has been activated.', 'jetpack' ), $module['name'] ) );
  498. } else {
  499. /* translators: %s is the name of a Jetpack module */
  500. WP_CLI::error( sprintf( __( '%s could not be activated.', 'jetpack' ), $module['name'] ) );
  501. }
  502. break;
  503. case 'activate_all':
  504. $modules = Jetpack::get_available_modules();
  505. Jetpack::update_active_modules( $modules );
  506. WP_CLI::success( __( 'All modules activated!', 'jetpack' ) );
  507. break;
  508. case 'deactivate':
  509. $module = Jetpack::get_module( $module_slug );
  510. Jetpack::log( 'deactivate', $module_slug );
  511. Jetpack::deactivate_module( $module_slug );
  512. /* translators: %s is the name of a Jetpack module */
  513. WP_CLI::success( sprintf( __( '%s has been deactivated.', 'jetpack' ), $module['name'] ) );
  514. break;
  515. case 'deactivate_all':
  516. Jetpack::delete_active_modules();
  517. WP_CLI::success( __( 'All modules deactivated!', 'jetpack' ) );
  518. break;
  519. case 'toggle':
  520. // Will never happen, should have been handled above and changed to activate or deactivate.
  521. break;
  522. }
  523. }
  524. /**
  525. * Manage Protect Settings
  526. *
  527. * ## OPTIONS
  528. *
  529. * allow: Add an IP address to an always allow list. You can also read or clear the allow list.
  530. *
  531. *
  532. * ## EXAMPLES
  533. *
  534. * wp jetpack protect allow <ip address>
  535. * wp jetpack protect allow list
  536. * wp jetpack protect allow clear
  537. *
  538. * @synopsis <allow> [<ip|ip_low-ip_high|list|clear>]
  539. */
  540. public function protect( $args, $assoc_args ) {
  541. $action = isset( $args[0] ) ? $args[0] : 'prompt';
  542. if ( ! in_array( $action, array( 'whitelist', 'allow' ), true ) ) { // Still allow "whitelist" for legacy support.
  543. /* translators: %s is a command like "prompt" */
  544. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
  545. }
  546. // Check if module is active
  547. if ( ! Jetpack::is_module_active( __FUNCTION__ ) ) {
  548. /* translators: %s is a module name */
  549. WP_CLI::error( sprintf( _x( '%1$s is not active. You can activate it with "wp jetpack module activate %2$s"', '"wp jetpack module activate" is a command - do not translate', 'jetpack' ), __FUNCTION__, __FUNCTION__ ) );
  550. }
  551. if ( in_array( $action, array( 'allow', 'whitelist' ), true ) ) {
  552. if ( isset( $args[1] ) ) {
  553. $action = 'allow';
  554. } else {
  555. $action = 'prompt';
  556. }
  557. }
  558. switch ( $action ) {
  559. case 'allow':
  560. $allow = array();
  561. $new_ip = $args[1];
  562. $current_allow = get_site_option( 'jetpack_protect_whitelist', array() ); // @todo Update the option name.
  563. // Build array of IPs that are already on the allowed list.
  564. // Re-build manually instead of using jetpack_protect_format_whitelist() so we can easily get
  565. // low & high range params for jetpack_protect_ip_address_is_in_range();
  566. foreach ( $current_allow as $allowed ) {
  567. // IP ranges
  568. if ( $allowed->range ) {
  569. // Is it already on the allowed list?
  570. if ( jetpack_protect_ip_address_is_in_range( $new_ip, $allowed->range_low, $allowed->range_high ) ) {
  571. /* translators: %s is an IP address */
  572. WP_CLI::error( sprintf( __( '%s is already on the always allow list.', 'jetpack' ), $new_ip ) );
  573. break;
  574. }
  575. $allow[] = $allowed->range_low . ' - ' . $allowed->range_high;
  576. } else { // Individual IPs
  577. // Check if the IP is already on the allow list (single IP only).
  578. if ( $new_ip === $allowed->ip_address ) {
  579. /* translators: %s is an IP address */
  580. WP_CLI::error( sprintf( __( '%s is already on the always allow list.', 'jetpack' ), $new_ip ) );
  581. break;
  582. }
  583. $allow[] = $allowed->ip_address;
  584. }
  585. }
  586. /*
  587. * List the allowed IPs.
  588. * Done here because it's easier to read the $allow array after it's been rebuilt.
  589. */
  590. if ( isset( $args[1] ) && 'list' == $args[1] ) {
  591. if ( ! empty( $allow ) ) {
  592. WP_CLI::success( __( 'Here are your always allowed IPs:', 'jetpack' ) );
  593. foreach ( $allow as $ip ) {
  594. WP_CLI::line( "\t" . str_pad( $ip, 24 ) );
  595. }
  596. } else {
  597. WP_CLI::line( __( 'Always allow list is empty.', 'jetpack' ) );
  598. }
  599. break;
  600. }
  601. /*
  602. * Clear the always allow list.
  603. */
  604. if ( isset( $args[1] ) && 'clear' == $args[1] ) {
  605. if ( ! empty( $allow ) ) {
  606. $allow = array();
  607. jetpack_protect_save_whitelist( $allow ); // @todo Need to update function name in the Protect module.
  608. WP_CLI::success( __( 'Cleared all IPs from the always allow list.', 'jetpack' ) );
  609. } else {
  610. WP_CLI::line( __( 'Always allow list is empty.', 'jetpack' ) );
  611. }
  612. break;
  613. }
  614. // Append new IP to allow array.
  615. array_push( $allow, $new_ip );
  616. // Save allow list if there are no errors.
  617. $result = jetpack_protect_save_whitelist( $allow ); // @todo Need to update function name in the Protect module.
  618. if ( is_wp_error( $result ) ) {
  619. WP_CLI::error( $result );
  620. }
  621. /* translators: %s is an IP address */
  622. WP_CLI::success( sprintf( __( '%s has been added to the always allowed list.', 'jetpack' ), $new_ip ) );
  623. break;
  624. case 'prompt':
  625. WP_CLI::error(
  626. __( 'No command found.', 'jetpack' ) . "\n" .
  627. __( 'Please enter the IP address you want to always allow.', 'jetpack' ) . "\n" .
  628. _x( 'You can save a range of IPs {low_range}-{high_range}. No spaces allowed. (example: 1.1.1.1-2.2.2.2)', 'Instructions on how to add IP ranges - low_range/high_range should be translated.', 'jetpack' ) . "\n" .
  629. _x( "You can also 'list' or 'clear' the always allowed list.", "'list' and 'clear' are commands and should not be translated", 'jetpack' ) . "\n"
  630. );
  631. break;
  632. }
  633. }
  634. /**
  635. * Manage Jetpack Options
  636. *
  637. * ## OPTIONS
  638. *
  639. * list : List all jetpack options and their values
  640. * delete : Delete an option
  641. * - can only delete options that are white listed.
  642. * update : update an option
  643. * - can only update option strings
  644. * get : get the value of an option
  645. *
  646. * ## EXAMPLES
  647. *
  648. * wp jetpack options list
  649. * wp jetpack options get <option_name>
  650. * wp jetpack options delete <option_name>
  651. * wp jetpack options update <option_name> [<option_value>]
  652. *
  653. * @synopsis <list|get|delete|update> [<option_name>] [<option_value>]
  654. */
  655. public function options( $args, $assoc_args ) {
  656. $action = isset( $args[0] ) ? $args[0] : 'list';
  657. $safe_to_modify = Jetpack_Options::get_options_for_reset();
  658. // Is the option flagged as unsafe?
  659. $flagged = ! in_array( $args[1], $safe_to_modify );
  660. if ( ! in_array( $action, array( 'list', 'get', 'delete', 'update' ) ) ) {
  661. /* translators: %s is a command like "prompt" */
  662. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
  663. }
  664. if ( isset( $args[0] ) ) {
  665. if ( 'get' == $args[0] && isset( $args[1] ) ) {
  666. $action = 'get';
  667. } elseif ( 'delete' == $args[0] && isset( $args[1] ) ) {
  668. $action = 'delete';
  669. } elseif ( 'update' == $args[0] && isset( $args[1] ) ) {
  670. $action = 'update';
  671. } else {
  672. $action = 'list';
  673. }
  674. }
  675. // Bail if the option isn't found
  676. $option = isset( $args[1] ) ? Jetpack_Options::get_option( $args[1] ) : false;
  677. if ( isset( $args[1] ) && ! $option && 'update' !== $args[0] ) {
  678. WP_CLI::error( __( 'Option not found or is empty. Use "list" to list option names', 'jetpack' ) );
  679. }
  680. // Let's print_r the option if it's an array
  681. // Used in the 'get' and 'list' actions
  682. $option = is_array( $option ) ? print_r( $option ) : $option;
  683. switch ( $action ) {
  684. case 'get':
  685. WP_CLI::success( "\t" . $option );
  686. break;
  687. case 'delete':
  688. jetpack_cli_are_you_sure( $flagged );
  689. Jetpack_Options::delete_option( $args[1] );
  690. /* translators: %s is the option name */
  691. WP_CLI::success( sprintf( __( 'Deleted option: %s', 'jetpack' ), $args[1] ) );
  692. break;
  693. case 'update':
  694. jetpack_cli_are_you_sure( $flagged );
  695. // Updating arrays would get pretty tricky...
  696. $value = Jetpack_Options::get_option( $args[1] );
  697. if ( $value && is_array( $value ) ) {
  698. WP_CLI::error( __( 'Sorry, no updating arrays at this time', 'jetpack' ) );
  699. }
  700. Jetpack_Options::update_option( $args[1], $args[2] );
  701. /* translators: %1$s is the previous value, %2$s is the new value */
  702. WP_CLI::success( sprintf( _x( 'Updated option: %1$s to "%2$s"', 'Updating an option from "this" to "that".', 'jetpack' ), $args[1], $args[2] ) );
  703. break;
  704. case 'list':
  705. $options_compact = Jetpack_Options::get_option_names();
  706. $options_non_compact = Jetpack_Options::get_option_names( 'non_compact' );
  707. $options_private = Jetpack_Options::get_option_names( 'private' );
  708. $options = array_merge( $options_compact, $options_non_compact, $options_private );
  709. // Table headers
  710. WP_CLI::line( "\t" . str_pad( __( 'Option', 'jetpack' ), 30 ) . __( 'Value', 'jetpack' ) );
  711. // List out the options and their values
  712. // Tell them if the value is empty or not
  713. // Tell them if it's an array
  714. foreach ( $options as $option ) {
  715. $value = Jetpack_Options::get_option( $option );
  716. if ( ! $value ) {
  717. WP_CLI::line( "\t" . str_pad( $option, 30 ) . 'Empty' );
  718. continue;
  719. }
  720. if ( ! is_array( $value ) ) {
  721. WP_CLI::line( "\t" . str_pad( $option, 30 ) . $value );
  722. } elseif ( is_array( $value ) ) {
  723. WP_CLI::line( "\t" . str_pad( $option, 30 ) . 'Array - Use "get <option>" to read option array.' );
  724. }
  725. }
  726. $option_text = '{' . _x( 'option', 'a variable command that a user can write, provided in the printed instructions', 'jetpack' ) . '}';
  727. $value_text = '{' . _x( 'value', 'the value that they want to update the option to', 'jetpack' ) . '}';
  728. WP_CLI::success(
  729. _x( "Above are your options. You may 'get', 'delete', and 'update' them.", "'get', 'delete', and 'update' are commands - do not translate.", 'jetpack' ) . "\n" .
  730. str_pad( 'wp jetpack options get', 26 ) . $option_text . "\n" .
  731. str_pad( 'wp jetpack options delete', 26 ) . $option_text . "\n" .
  732. str_pad( 'wp jetpack options update', 26 ) . "$option_text $value_text" . "\n" .
  733. _x( "Type 'wp jetpack options' for more info.", "'wp jetpack options' is a command - do not translate.", 'jetpack' ) . "\n"
  734. );
  735. break;
  736. }
  737. }
  738. /**
  739. * Get the status of or start a new Jetpack sync.
  740. *
  741. * ## OPTIONS
  742. *
  743. * status : Print the current sync status
  744. * settings : Prints the current sync settings
  745. * start : Start a full sync from this site to WordPress.com
  746. * enable : Enables sync on the site
  747. * disable : Disable sync on a site
  748. * reset : Disables sync and Resets the sync queues on a site
  749. *
  750. * ## EXAMPLES
  751. *
  752. * wp jetpack sync status
  753. * wp jetpack sync settings
  754. * wp jetpack sync start --modules=functions --sync_wait_time=5
  755. * wp jetpack sync enable
  756. * wp jetpack sync disable
  757. * wp jetpack sync reset
  758. * wp jetpack sync reset --queue=full or regular
  759. *
  760. * @synopsis <status|start> [--<field>=<value>]
  761. */
  762. public function sync( $args, $assoc_args ) {
  763. $action = isset( $args[0] ) ? $args[0] : 'status';
  764. switch ( $action ) {
  765. case 'status':
  766. $status = Actions::get_sync_status();
  767. $collection = array();
  768. foreach ( $status as $key => $item ) {
  769. $collection[] = array(
  770. 'option' => $key,
  771. 'value' => is_scalar( $item ) ? $item : json_encode( $item ),
  772. );
  773. }
  774. WP_CLI::log( __( 'Sync Status:', 'jetpack' ) );
  775. WP_CLI\Utils\format_items( 'table', $collection, array( 'option', 'value' ) );
  776. break;
  777. case 'settings':
  778. WP_CLI::log( __( 'Sync Settings:', 'jetpack' ) );
  779. foreach ( Settings::get_settings() as $setting => $item ) {
  780. $settings[] = array(
  781. 'setting' => $setting,
  782. 'value' => is_scalar( $item ) ? $item : json_encode( $item ),
  783. );
  784. }
  785. WP_CLI\Utils\format_items( 'table', $settings, array( 'setting', 'value' ) );
  786. case 'disable':
  787. // Don't set it via the Settings since that also resets the queues.
  788. update_option( 'jetpack_sync_settings_disable', 1 );
  789. /* translators: %s is the site URL */
  790. WP_CLI::log( sprintf( __( 'Sync Disabled on %s', 'jetpack' ), get_site_url() ) );
  791. break;
  792. case 'enable':
  793. Settings::update_settings( array( 'disable' => 0 ) );
  794. /* translators: %s is the site URL */
  795. WP_CLI::log( sprintf( __( 'Sync Enabled on %s', 'jetpack' ), get_site_url() ) );
  796. break;
  797. case 'reset':
  798. // Don't set it via the Settings since that also resets the queues.
  799. update_option( 'jetpack_sync_settings_disable', 1 );
  800. /* translators: %s is the site URL */
  801. WP_CLI::log( sprintf( __( 'Sync Disabled on %s. Use `wp jetpack sync enable` to enable syncing again.', 'jetpack' ), get_site_url() ) );
  802. $listener = Listener::get_instance();
  803. if ( empty( $assoc_args['queue'] ) ) {
  804. $listener->get_sync_queue()->reset();
  805. $listener->get_full_sync_queue()->reset();
  806. /* translators: %s is the site URL */
  807. WP_CLI::log( sprintf( __( 'Reset Full Sync and Regular Queues Queue on %s', 'jetpack' ), get_site_url() ) );
  808. break;
  809. }
  810. if ( ! empty( $assoc_args['queue'] ) ) {
  811. switch ( $assoc_args['queue'] ) {
  812. case 'regular':
  813. $listener->get_sync_queue()->reset();
  814. /* translators: %s is the site URL */
  815. WP_CLI::log( sprintf( __( 'Reset Regular Sync Queue on %s', 'jetpack' ), get_site_url() ) );
  816. break;
  817. case 'full':
  818. $listener->get_full_sync_queue()->reset();
  819. /* translators: %s is the site URL */
  820. WP_CLI::log( sprintf( __( 'Reset Full Sync Queue on %s', 'jetpack' ), get_site_url() ) );
  821. break;
  822. default:
  823. WP_CLI::error( __( 'Please specify what type of queue do you want to reset: `full` or `regular`.', 'jetpack' ) );
  824. break;
  825. }
  826. }
  827. break;
  828. case 'start':
  829. if ( ! Actions::sync_allowed() ) {
  830. if ( Settings::get_setting( 'disable' ) ) {
  831. WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. It is currently disabled. Run `wp jetpack sync enable` to enable it.', 'jetpack' ) );
  832. return;
  833. }
  834. $connection = new Connection_Manager();
  835. if ( ! $connection->is_connected() ) {
  836. if ( ! doing_action( 'jetpack_site_registered' ) ) {
  837. WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. Jetpack is not connected.', 'jetpack' ) );
  838. return;
  839. }
  840. }
  841. $status = new Status();
  842. if ( $status->is_offline_mode() ) {
  843. WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. The site is in offline mode.', 'jetpack' ) );
  844. return;
  845. }
  846. if ( $status->is_staging_site() ) {
  847. WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. The site is in staging mode.', 'jetpack' ) );
  848. return;
  849. }
  850. }
  851. // Get the original settings so that we can restore them later
  852. $original_settings = Settings::get_settings();
  853. // Initialize sync settigns so we can sync as quickly as possible
  854. $sync_settings = wp_parse_args(
  855. array_intersect_key( $assoc_args, Settings::$valid_settings ),
  856. array(
  857. 'sync_wait_time' => 0,
  858. 'enqueue_wait_time' => 0,
  859. 'queue_max_writes_sec' => 10000,
  860. 'max_queue_size_full_sync' => 100000,
  861. 'full_sync_send_duration' => HOUR_IN_SECONDS,
  862. )
  863. );
  864. Settings::update_settings( $sync_settings );
  865. // Convert comma-delimited string of modules to an array
  866. if ( ! empty( $assoc_args['modules'] ) ) {
  867. $modules = array_map( 'trim', explode( ',', $assoc_args['modules'] ) );
  868. // Convert the array so that the keys are the module name and the value is true to indicate
  869. // that we want to sync the module
  870. $modules = array_map( '__return_true', array_flip( $modules ) );
  871. }
  872. foreach ( array( 'posts', 'comments', 'users' ) as $module_name ) {
  873. if (
  874. 'users' === $module_name &&
  875. isset( $assoc_args[ $module_name ] ) &&
  876. 'initial' === $assoc_args[ $module_name ]
  877. ) {
  878. $modules['users'] = 'initial';
  879. } elseif ( isset( $assoc_args[ $module_name ] ) ) {
  880. $ids = explode( ',', $assoc_args[ $module_name ] );
  881. if ( count( $ids ) > 0 ) {
  882. $modules[ $module_name ] = $ids;
  883. }
  884. }
  885. }
  886. if ( empty( $modules ) ) {
  887. $modules = null;
  888. }
  889. // Kick off a full sync
  890. if ( Actions::do_full_sync( $modules ) ) {
  891. if ( $modules ) {
  892. /* translators: %s is a comma separated list of Jetpack modules */
  893. WP_CLI::log( sprintf( __( 'Initialized a new full sync with modules: %s', 'jetpack' ), join( ', ', array_keys( $modules ) ) ) );
  894. } else {
  895. WP_CLI::log( __( 'Initialized a new full sync', 'jetpack' ) );
  896. }
  897. } else {
  898. // Reset sync settings to original.
  899. Settings::update_settings( $original_settings );
  900. if ( $modules ) {
  901. /* translators: %s is a comma separated list of Jetpack modules */
  902. WP_CLI::error( sprintf( __( 'Could not start a new full sync with modules: %s', 'jetpack' ), join( ', ', $modules ) ) );
  903. } else {
  904. WP_CLI::error( __( 'Could not start a new full sync', 'jetpack' ) );
  905. }
  906. }
  907. // Keep sending to WPCOM until there's nothing to send
  908. $i = 1;
  909. do {
  910. $result = Actions::$sender->do_full_sync();
  911. if ( is_wp_error( $result ) ) {
  912. $queue_empty_error = ( 'empty_queue_full_sync' == $result->get_error_code() );
  913. if ( ! $queue_empty_error || ( $queue_empty_error && ( 1 == $i ) ) ) {
  914. /* translators: %s is an error code */
  915. WP_CLI::error( sprintf( __( 'Sync errored with code: %s', 'jetpack' ), $result->get_error_code() ) );
  916. }
  917. } else {
  918. if ( 1 == $i ) {
  919. WP_CLI::log( __( 'Sent data to WordPress.com', 'jetpack' ) );
  920. } else {
  921. WP_CLI::log( __( 'Sent more data to WordPress.com', 'jetpack' ) );
  922. }
  923. // Immediate Full Sync does not wait for WP.com to process data so we need to enforce a wait.
  924. if ( false !== strpos( get_class( Modules::get_module( 'full-sync' ) ), 'Full_Sync_Immediately' ) ) {
  925. sleep( 15 );
  926. }
  927. }
  928. $i++;
  929. } while ( $result && ! is_wp_error( $result ) );
  930. // Reset sync settings to original.
  931. Settings::update_settings( $original_settings );
  932. WP_CLI::success( __( 'Finished syncing to WordPress.com', 'jetpack' ) );
  933. break;
  934. }
  935. }
  936. /**
  937. * List the contents of a specific Jetpack sync queue.
  938. *
  939. * ## OPTIONS
  940. *
  941. * peek : List the 100 front-most items on the queue.
  942. *
  943. * ## EXAMPLES
  944. *
  945. * wp jetpack sync_queue full_sync peek
  946. *
  947. * @synopsis <incremental|full_sync> <peek>
  948. */
  949. public function sync_queue( $args, $assoc_args ) {
  950. if ( ! Actions::sync_allowed() ) {
  951. WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site.', 'jetpack' ) );
  952. }
  953. $queue_name = isset( $args[0] ) ? $args[0] : 'sync';
  954. $action = isset( $args[1] ) ? $args[1] : 'peek';
  955. // We map the queue name that way we can support more friendly queue names in the commands, but still use
  956. // the queue name that the code expects.
  957. $queue_name_map = $allowed_queues = array(
  958. 'incremental' => 'sync',
  959. 'full' => 'full_sync',
  960. );
  961. $mapped_queue_name = isset( $queue_name_map[ $queue_name ] ) ? $queue_name_map[ $queue_name ] : $queue_name;
  962. switch ( $action ) {
  963. case 'peek':
  964. $queue = new Queue( $mapped_queue_name );
  965. $items = $queue->peek( 100 );
  966. if ( empty( $items ) ) {
  967. /* translators: %s is the name of the queue, either 'incremental' or 'full' */
  968. WP_CLI::log( sprintf( __( 'Nothing is in the queue: %s', 'jetpack' ), $queue_name ) );
  969. } else {
  970. $collection = array();
  971. foreach ( $items as $item ) {
  972. $collection[] = array(
  973. 'action' => $item[0],
  974. 'args' => json_encode( $item[1] ),
  975. 'current_user_id' => $item[2],
  976. 'microtime' => $item[3],
  977. 'importing' => (string) $item[4],
  978. );
  979. }
  980. WP_CLI\Utils\format_items(
  981. 'table',
  982. $collection,
  983. array(
  984. 'action',
  985. 'args',
  986. 'current_user_id',
  987. 'microtime',
  988. 'importing',
  989. )
  990. );
  991. }
  992. break;
  993. }
  994. }
  995. /**
  996. * Cancel's the current Jetpack plan granted by this partner, if applicable
  997. *
  998. * Returns success or error JSON
  999. *
  1000. * <token_json>
  1001. * : JSON blob of WPCOM API token
  1002. * [--partner_tracking_id=<partner_tracking_id>]
  1003. * : This is an optional ID that a host can pass to help identify a site in logs on WordPress.com
  1004. *
  1005. * * @synopsis <token_json> [--partner_tracking_id=<partner_tracking_id>]
  1006. */
  1007. public function partner_cancel( $args, $named_args ) {
  1008. list( $token_json ) = $args;
  1009. if ( ! $token_json || ! ( $token = json_decode( $token_json ) ) ) {
  1010. /* translators: %s is the invalid JSON string */
  1011. $this->partner_provision_error( new WP_Error( 'missing_access_token', sprintf( __( 'Invalid token JSON: %s', 'jetpack' ), $token_json ) ) );
  1012. }
  1013. if ( isset( $token->error ) ) {
  1014. $this->partner_provision_error( new WP_Error( $token->error, $token->message ) );
  1015. }
  1016. if ( ! isset( $token->access_token ) ) {
  1017. $this->partner_provision_error( new WP_Error( 'missing_access_token', __( 'Missing or invalid access token', 'jetpack' ) ) );
  1018. }
  1019. if ( Identity_Crisis::validate_sync_error_idc_option() ) {
  1020. $this->partner_provision_error(
  1021. new WP_Error(
  1022. 'site_in_safe_mode',
  1023. esc_html__( 'Can not cancel a plan while in safe mode. See: https://jetpack.com/support/safe-mode/', 'jetpack' )
  1024. )
  1025. );
  1026. }
  1027. $site_identifier = Jetpack_Options::get_option( 'id' );
  1028. if ( ! $site_identifier ) {
  1029. $status = new Status();
  1030. $site_identifier = $status->get_site_suffix();
  1031. }
  1032. $request = array(
  1033. 'headers' => array(
  1034. 'Authorization' => 'Bearer ' . $token->access_token,
  1035. 'Host' => 'public-api.wordpress.com',
  1036. ),
  1037. 'timeout' => 60,
  1038. 'method' => 'POST',
  1039. );
  1040. $url = sprintf( '%s/rest/v1.3/jpphp/%s/partner-cancel', $this->get_api_host(), $site_identifier );
  1041. if ( ! empty( $named_args ) && ! empty( $named_args['partner_tracking_id'] ) ) {
  1042. $url = esc_url_raw( add_query_arg( 'partner_tracking_id', $named_args['partner_tracking_id'], $url ) );
  1043. }
  1044. $result = Client::_wp_remote_request( $url, $request );
  1045. Jetpack_Options::delete_option( 'onboarding' );
  1046. if ( is_wp_error( $result ) ) {
  1047. $this->partner_provision_error( $result );
  1048. }
  1049. WP_CLI::log( wp_remote_retrieve_body( $result ) );
  1050. }
  1051. /**
  1052. * Provision a site using a Jetpack Partner license
  1053. *
  1054. * Returns JSON blob
  1055. *
  1056. * ## OPTIONS
  1057. *
  1058. * <token_json>
  1059. * : JSON blob of WPCOM API token
  1060. * [--plan=<plan_name>]
  1061. * : Slug of the requested plan, e.g. premium
  1062. * [--wpcom_user_id=<user_id>]
  1063. * : WordPress.com ID of user to connect as (must be whitelisted against partner key)
  1064. * [--wpcom_user_email=<wpcom_user_email>]
  1065. * : Override the email we send to WordPress.com for registration
  1066. * [--onboarding=<onboarding>]
  1067. * : Guide the user through an onboarding wizard
  1068. * [--force_register=<register>]
  1069. * : Whether to force a site to register
  1070. * [--force_connect=<force_connect>]
  1071. * : Force JPS to not reuse existing credentials
  1072. * [--home_url=<home_url>]
  1073. * : Overrides the home option via the home_url filter, or the WP_HOME constant
  1074. * [--site_url=<site_url>]
  1075. * : Overrides the siteurl option via the site_url filter, or the WP_SITEURL constant
  1076. * [--partner_tracking_id=<partner_tracking_id>]
  1077. * : This is an optional ID that a host can pass to help identify a site in logs on WordPress.com
  1078. *
  1079. * ## EXAMPLES
  1080. *
  1081. * $ wp jetpack partner_provision '{ some: "json" }' premium 1
  1082. * { success: true }
  1083. *
  1084. * @synopsis <token_json> [--wpcom_user_id=<user_id>] [--plan=<plan_name>] [--onboarding=<onboarding>] [--force_register=<register>] [--force_connect=<force_connect>] [--home_url=<home_url>] [--site_url=<site_url>] [--wpcom_user_email=<wpcom_user_email>] [--partner_tracking_id=<partner_tracking_id>]
  1085. */
  1086. public function partner_provision( $args, $named_args ) {
  1087. list( $token_json ) = $args;
  1088. if ( ! $token_json || ! ( $token = json_decode( $token_json ) ) ) {
  1089. /* translators: %s is the invalid JSON string */
  1090. $this->partner_provision_error( new WP_Error( 'missing_access_token', sprintf( __( 'Invalid token JSON: %s', 'jetpack' ), $token_json ) ) );
  1091. }
  1092. if ( isset( $token->error ) ) {
  1093. $message = isset( $token->message )
  1094. ? $token->message
  1095. : '';
  1096. $this->partner_provision_error( new WP_Error( $token->error, $message ) );
  1097. }
  1098. if ( ! isset( $token->access_token ) ) {
  1099. $this->partner_provision_error( new WP_Error( 'missing_access_token', __( 'Missing or invalid access token', 'jetpack' ) ) );
  1100. }
  1101. require_once JETPACK__PLUGIN_DIR . '_inc/class.jetpack-provision.php';
  1102. $body_json = Jetpack_Provision::partner_provision( $token->access_token, $named_args );
  1103. if ( is_wp_error( $body_json ) ) {
  1104. error_log(
  1105. json_encode(
  1106. array(
  1107. 'success' => false,
  1108. 'error_code' => $body_json->get_error_code(),
  1109. 'error_message' => $body_json->get_error_message(),
  1110. )
  1111. )
  1112. );
  1113. exit( 1 );
  1114. }
  1115. WP_CLI::log( json_encode( $body_json ) );
  1116. }
  1117. /**
  1118. * Manages your Jetpack sitemap
  1119. *
  1120. * ## OPTIONS
  1121. *
  1122. * rebuild : Rebuild all sitemaps
  1123. * --purge : if set, will remove all existing sitemap data before rebuilding
  1124. *
  1125. * ## EXAMPLES
  1126. *
  1127. * wp jetpack sitemap rebuild
  1128. *
  1129. * @subcommand sitemap
  1130. * @synopsis <rebuild> [--purge]
  1131. */
  1132. public function sitemap( $args, $assoc_args ) {
  1133. if ( ! Jetpack::is_connection_ready() ) {
  1134. WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
  1135. }
  1136. if ( ! Jetpack::is_module_active( 'sitemaps' ) ) {
  1137. WP_CLI::error( __( 'Jetpack Sitemaps module is not currently active. Activate it first if you want to work with sitemaps.', 'jetpack' ) );
  1138. }
  1139. if ( ! class_exists( 'Jetpack_Sitemap_Builder' ) ) {
  1140. WP_CLI::error( __( 'Jetpack Sitemaps module is active, but unavailable. This can happen if your site is set to discourage search engine indexing. Please enable search engine indexing to allow sitemap generation.', 'jetpack' ) );
  1141. }
  1142. if ( isset( $assoc_args['purge'] ) && $assoc_args['purge'] ) {
  1143. $librarian = new Jetpack_Sitemap_Librarian();
  1144. $librarian->delete_all_stored_sitemap_data();
  1145. }
  1146. $sitemap_builder = new Jetpack_Sitemap_Builder();
  1147. $sitemap_builder->update_sitemap();
  1148. }
  1149. /**
  1150. * Allows authorizing a user via the command line and will activate
  1151. *
  1152. * ## EXAMPLES
  1153. *
  1154. * wp jetpack authorize_user --token=123456789abcdef
  1155. *
  1156. * @synopsis --token=<value>
  1157. */
  1158. public function authorize_user( $args, $named_args ) {
  1159. if ( ! is_user_logged_in() ) {
  1160. WP_CLI::error( __( 'Please select a user to authorize via the --user global argument.', 'jetpack' ) );
  1161. }
  1162. if ( empty( $named_args['token'] ) ) {
  1163. WP_CLI::error( __( 'A non-empty token argument must be passed.', 'jetpack' ) );
  1164. }
  1165. $is_connection_owner = ! Jetpack::connection()->has_connected_owner();
  1166. $current_user_id = get_current_user_id();
  1167. ( new Tokens() )->update_user_token( $current_user_id, sprintf( '%s.%d', $named_args['token'], $current_user_id ), $is_connection_owner );
  1168. WP_CLI::log( wp_json_encode( $named_args ) );
  1169. if ( $is_connection_owner ) {
  1170. /**
  1171. * Auto-enable SSO module for new Jetpack Start connections
  1172. *
  1173. * @since 5.0.0
  1174. *
  1175. * @param bool $enable_sso Whether to enable the SSO module. Default to true.
  1176. */
  1177. $enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
  1178. Jetpack::handle_post_authorization_actions( $enable_sso, false );
  1179. /* translators: %d is a user ID */
  1180. WP_CLI::success( sprintf( __( 'Authorized %d and activated default modules.', 'jetpack' ), $current_user_id ) );
  1181. } else {
  1182. /* translators: %d is a user ID */
  1183. WP_CLI::success( sprintf( __( 'Authorized %d.', 'jetpack' ), $current_user_id ) );
  1184. }
  1185. }
  1186. /**
  1187. * Allows calling a WordPress.com API endpoint using the current blog's token.
  1188. *
  1189. * ## OPTIONS
  1190. * --resource=<resource>
  1191. * : The resource to call with the current blog's token, where `%d` represents the current blog's ID.
  1192. *
  1193. * [--api_version=<api_version>]
  1194. * : The API version to query against.
  1195. *
  1196. * [--base_api_path=<base_api_path>]
  1197. * : The base API path to query.
  1198. * ---
  1199. * default: rest
  1200. * ---
  1201. *
  1202. * [--body=<body>]
  1203. * : A JSON encoded string representing arguments to send in the body.
  1204. *
  1205. * [--field=<value>]
  1206. * : Any number of arguments that should be passed to the resource.
  1207. *
  1208. * [--pretty]
  1209. * : Will pretty print the results of a successful API call.
  1210. *
  1211. * [--strip-success]
  1212. * : Will remove the green success label from successful API calls.
  1213. *
  1214. * ## EXAMPLES
  1215. *
  1216. * wp jetpack call_api --resource='/sites/%d'
  1217. */
  1218. public function call_api( $args, $named_args ) {
  1219. if ( ! Jetpack::is_connection_ready() ) {
  1220. WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
  1221. }
  1222. $consumed_args = array(
  1223. 'resource',
  1224. 'api_version',
  1225. 'base_api_path',
  1226. 'body',
  1227. 'pretty',
  1228. );
  1229. // Get args that should be passed to resource.
  1230. $other_args = array_diff_key( $named_args, array_flip( $consumed_args ) );
  1231. $decoded_body = ! empty( $named_args['body'] )
  1232. ? json_decode( $named_args['body'], true )
  1233. : false;
  1234. $resource_url = ( false === strpos( $named_args['resource'], '%d' ) )
  1235. ? $named_args['resource']
  1236. : sprintf( $named_args['resource'], Jetpack_Options::get_option( 'id' ) );
  1237. $response = Client::wpcom_json_api_request_as_blog(
  1238. $resource_url,
  1239. empty( $named_args['api_version'] ) ? Client::WPCOM_JSON_API_VERSION : $named_args['api_version'],
  1240. $other_args,
  1241. empty( $decoded_body ) ? null : $decoded_body,
  1242. empty( $named_args['base_api_path'] ) ? 'rest' : $named_args['base_api_path']
  1243. );
  1244. if ( is_wp_error( $response ) ) {
  1245. WP_CLI::error(
  1246. sprintf(
  1247. /* translators: %1$s is an endpoint route (ex. /sites/123456), %2$d is an error code, %3$s is an error message. */
  1248. __( 'Request to %1$s returned an error: (%2$d) %3$s.', 'jetpack' ),
  1249. $resource_url,
  1250. $response->get_error_code(),
  1251. $response->get_error_message()
  1252. )
  1253. );
  1254. }
  1255. if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
  1256. WP_CLI::error(
  1257. sprintf(
  1258. /* translators: %1$s is an endpoint route (ex. /sites/123456), %2$d is an HTTP status code. */
  1259. __( 'Request to %1$s returned a non-200 response code: %2$d.', 'jetpack' ),
  1260. $resource_url,
  1261. wp_remote_retrieve_response_code( $response )
  1262. )
  1263. );
  1264. }
  1265. $output = wp_remote_retrieve_body( $response );
  1266. if ( isset( $named_args['pretty'] ) ) {
  1267. $decoded_output = json_decode( $output );
  1268. if ( $decoded_output ) {
  1269. $output = wp_json_encode( $decoded_output, JSON_PRETTY_PRINT );
  1270. }
  1271. }
  1272. if ( isset( $named_args['strip-success'] ) ) {
  1273. WP_CLI::log( $output );
  1274. WP_CLI::halt( 0 );
  1275. }
  1276. WP_CLI::success( $output );
  1277. }
  1278. /**
  1279. * Allows uploading SSH Credentials to the current site for backups, restores, and security scanning.
  1280. *
  1281. * ## OPTIONS
  1282. *
  1283. * [--host=<host>]
  1284. * : The SSH server's address.
  1285. *
  1286. * [--ssh-user=<user>]
  1287. * : The username to use to log in to the SSH server.
  1288. *
  1289. * [--pass=<pass>]
  1290. * : The password used to log in, if using a password. (optional)
  1291. *
  1292. * [--kpri=<kpri>]
  1293. * : The private key used to log in, if using a private key. (optional)
  1294. *
  1295. * [--pretty]
  1296. * : Will pretty print the results of a successful API call. (optional)
  1297. *
  1298. * [--strip-success]
  1299. * : Will remove the green success label from successful API calls. (optional)
  1300. *
  1301. * ## EXAMPLES
  1302. *
  1303. * wp jetpack upload_ssh_creds --host=example.com --ssh-user=example --pass=password
  1304. * wp jetpack updload_ssh_creds --host=example.com --ssh-user=example --kpri=key
  1305. */
  1306. public function upload_ssh_creds( $args, $named_args ) {
  1307. if ( ! Jetpack::is_connection_ready() ) {
  1308. WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
  1309. }
  1310. $required_args = array(
  1311. 'host',
  1312. 'ssh-user',
  1313. );
  1314. foreach ( $required_args as $arg ) {
  1315. if ( empty( $named_args[ $arg ] ) ) {
  1316. WP_CLI::error(
  1317. sprintf(
  1318. /* translators: %s is a slug, such as 'host'. */
  1319. __( '`%s` cannot be empty.', 'jetpack' ),
  1320. $arg
  1321. )
  1322. );
  1323. }
  1324. }
  1325. if ( empty( $named_args['pass'] ) && empty( $named_args['kpri'] ) ) {
  1326. WP_CLI::error( __( 'Both `pass` and `kpri` fields cannot be blank.', 'jetpack' ) );
  1327. }
  1328. $values = array(
  1329. 'credentials' => array(
  1330. 'site_url' => get_site_url(),
  1331. 'abspath' => ABSPATH,
  1332. 'protocol' => 'ssh',
  1333. 'port' => 22,
  1334. 'role' => 'main',
  1335. 'host' => $named_args['host'],
  1336. 'user' => $named_args['ssh-user'],
  1337. 'pass' => empty( $named_args['pass'] ) ? '' : $named_args['pass'],
  1338. 'kpri' => empty( $named_args['kpri'] ) ? '' : $named_args['kpri'],
  1339. ),
  1340. );
  1341. $named_args = wp_parse_args(
  1342. array(
  1343. 'resource' => '/activity-log/%d/update-credentials',
  1344. 'method' => 'POST',
  1345. 'api_version' => '1.1',
  1346. 'body' => wp_json_encode( $values ),
  1347. 'timeout' => 30,
  1348. ),
  1349. $named_args
  1350. );
  1351. self::call_api( $args, $named_args );
  1352. }
  1353. /**
  1354. * API wrapper for getting stats from the WordPress.com API for the current site.
  1355. *
  1356. * ## OPTIONS
  1357. *
  1358. * [--quantity=<quantity>]
  1359. * : The number of units to include.
  1360. * ---
  1361. * default: 30
  1362. * ---
  1363. *
  1364. * [--period=<period>]
  1365. * : The unit of time to query stats for.
  1366. * ---
  1367. * default: day
  1368. * options:
  1369. * - day
  1370. * - week
  1371. * - month
  1372. * - year
  1373. * ---
  1374. *
  1375. * [--date=<date>]
  1376. * : The latest date to return stats for. Ex. - 2018-01-01.
  1377. *
  1378. * [--pretty]
  1379. * : Will pretty print the results of a successful API call.
  1380. *
  1381. * [--strip-success]
  1382. * : Will remove the green success label from successful API calls.
  1383. *
  1384. * ## EXAMPLES
  1385. *
  1386. * wp jetpack get_stats
  1387. */
  1388. public function get_stats( $args, $named_args ) {
  1389. $selected_args = array_intersect_key(
  1390. $named_args,
  1391. array_flip(
  1392. array(
  1393. 'quantity',
  1394. 'date',
  1395. )
  1396. )
  1397. );
  1398. // The API expects unit, but period seems to be more correct.
  1399. $selected_args['unit'] = $named_args['period'];
  1400. $command = sprintf(
  1401. 'jetpack call_api --resource=/sites/%d/stats/%s',
  1402. Jetpack_Options::get_option( 'id' ),
  1403. add_query_arg( $selected_args, 'visits' )
  1404. );
  1405. if ( isset( $named_args['pretty'] ) ) {
  1406. $command .= ' --pretty';
  1407. }
  1408. if ( isset( $named_args['strip-success'] ) ) {
  1409. $command .= ' --strip-success';
  1410. }
  1411. WP_CLI::runcommand(
  1412. $command,
  1413. array(
  1414. 'launch' => false, // Use the current process.
  1415. )
  1416. );
  1417. }
  1418. /**
  1419. * Allows management of publicize connections.
  1420. *
  1421. * ## OPTIONS
  1422. *
  1423. * <list|disconnect>
  1424. * : The action to perform.
  1425. * ---
  1426. * options:
  1427. * - list
  1428. * - disconnect
  1429. * ---
  1430. *
  1431. * [<identifier>]
  1432. * : The connection ID or service to perform an action on.
  1433. *
  1434. * [--format=<format>]
  1435. * : Allows overriding the output of the command when listing connections.
  1436. * ---
  1437. * default: table
  1438. * options:
  1439. * - table
  1440. * - json
  1441. * - csv
  1442. * - yaml
  1443. * - ids
  1444. * - count
  1445. * ---
  1446. *
  1447. * ## EXAMPLES
  1448. *
  1449. * # List all publicize connections.
  1450. * $ wp jetpack publicize list
  1451. *
  1452. * # List publicize connections for a given service.
  1453. * $ wp jetpack publicize list twitter
  1454. *
  1455. * # List all publicize connections for a given user.
  1456. * $ wp --user=1 jetpack publicize list
  1457. *
  1458. * # List all publicize connections for a given user and service.
  1459. * $ wp --user=1 jetpack publicize list twitter
  1460. *
  1461. * # Display details for a given connection.
  1462. * $ wp jetpack publicize list 123456
  1463. *
  1464. * # Diconnection a given connection.
  1465. * $ wp jetpack publicize disconnect 123456
  1466. *
  1467. * # Disconnect all connections.
  1468. * $ wp jetpack publicize disconnect all
  1469. *
  1470. * # Disconnect all connections for a given service.
  1471. * $ wp jetpack publicize disconnect twitter
  1472. */
  1473. public function publicize( $args, $named_args ) {
  1474. if ( ! Jetpack::connection()->has_connected_owner() ) {
  1475. WP_CLI::error( __( 'Publicize requires a user-level connection to WordPress.com', 'jetpack' ) );
  1476. }
  1477. if ( ! Jetpack::is_module_active( 'publicize' ) ) {
  1478. WP_CLI::error( __( 'The publicize module is not active.', 'jetpack' ) );
  1479. }
  1480. if ( ( new Status() )->is_offline_mode() ) {
  1481. if (
  1482. ! defined( 'JETPACK_DEV_DEBUG' ) &&
  1483. ! has_filter( 'jetpack_development_mode' ) &&
  1484. ! has_filter( 'jetpack_offline_mode' ) &&
  1485. false === strpos( site_url(), '.' )
  1486. ) {
  1487. WP_CLI::error( __( "Jetpack is current in offline mode because the site url does not contain a '.', which often occurs when dynamically setting the WP_SITEURL constant. While in offline mode, the publicize module will not load.", 'jetpack' ) );
  1488. }
  1489. WP_CLI::error( __( 'Jetpack is currently in offline mode, so the publicize module will not load.', 'jetpack' ) );
  1490. }
  1491. if ( ! class_exists( 'Publicize' ) ) {
  1492. WP_CLI::error( __( 'The publicize module is not loaded.', 'jetpack' ) );
  1493. }
  1494. $action = $args[0];
  1495. $publicize = new Publicize();
  1496. $identifier = ! empty( $args[1] ) ? $args[1] : false;
  1497. $services = array_keys( $publicize->get_services() );
  1498. $id_is_service = in_array( $identifier, $services, true );
  1499. switch ( $action ) {
  1500. case 'list':
  1501. $connections_to_return = array();
  1502. // For the CLI command, let's return all connections when a user isn't specified. This
  1503. // differs from the logic in the Publicize class.
  1504. $option_connections = is_user_logged_in()
  1505. ? (array) $publicize->get_all_connections_for_user()
  1506. : (array) $publicize->get_all_connections();
  1507. foreach ( $option_connections as $service_name => $connections ) {
  1508. foreach ( (array) $connections as $id => $connection ) {
  1509. $connection['id'] = $id;
  1510. $connection['service'] = $service_name;
  1511. $connections_to_return[] = $connection;
  1512. }
  1513. }
  1514. if ( $id_is_service && ! empty( $identifier ) && ! empty( $connections_to_return ) ) {
  1515. $temp_connections = $connections_to_return;
  1516. $connections_to_return = array();
  1517. foreach ( $temp_connections as $connection ) {
  1518. if ( $identifier === $connection['service'] ) {
  1519. $connections_to_return[] = $connection;
  1520. }
  1521. }
  1522. }
  1523. if ( $identifier && ! $id_is_service && ! empty( $connections_to_return ) ) {
  1524. $connections_to_return = wp_list_filter( $connections_to_return, array( 'id' => $identifier ) );
  1525. }
  1526. $expected_keys = array(
  1527. 'id',
  1528. 'service',
  1529. 'user_id',
  1530. 'provider',
  1531. 'issued',
  1532. 'expires',
  1533. 'external_id',
  1534. 'external_name',
  1535. 'external_display',
  1536. 'type',
  1537. 'connection_data',
  1538. );
  1539. // Somehow, a test site ended up in a state where $connections_to_return looked like:
  1540. // array( array( array( 'id' => 0, 'service' => 0 ) ) ) // phpcs:ignore Squiz.PHP.CommentedOutCode.Found
  1541. // This caused the CLI command to error when running WP_CLI\Utils\format_items() below. So
  1542. // to minimize future issues, this nested loop will remove any connections that don't contain
  1543. // any keys that we expect.
  1544. foreach ( (array) $connections_to_return as $connection_key => $connection ) {
  1545. foreach ( $expected_keys as $expected_key ) {
  1546. if ( ! isset( $connection[ $expected_key ] ) ) {
  1547. unset( $connections_to_return[ $connection_key ] );
  1548. continue;
  1549. }
  1550. }
  1551. }
  1552. if ( empty( $connections_to_return ) ) {
  1553. return false;
  1554. }
  1555. WP_CLI\Utils\format_items( $named_args['format'], $connections_to_return, $expected_keys );
  1556. break; // list.
  1557. case 'disconnect':
  1558. if ( ! $identifier ) {
  1559. WP_CLI::error( __( 'A connection ID must be passed in order to disconnect.', 'jetpack' ) );
  1560. }
  1561. // If the connection ID is 'all' then delete all connections. If the connection ID
  1562. // matches a service, delete all connections for that service.
  1563. if ( 'all' === $identifier || $id_is_service ) {
  1564. if ( 'all' === $identifier ) {
  1565. WP_CLI::log( __( "You're about to delete all publicize connections.", 'jetpack' ) );
  1566. } else {
  1567. /* translators: %s is a lowercase string for a social network. */
  1568. WP_CLI::log( sprintf( __( "You're about to delete all publicize connections to %s.", 'jetpack' ), $identifier ) );
  1569. }
  1570. jetpack_cli_are_you_sure();
  1571. $connections = array();
  1572. $service = $identifier;
  1573. $option_connections = is_user_logged_in()
  1574. ? (array) $publicize->get_all_connections_for_user()
  1575. : (array) $publicize->get_all_connections();
  1576. if ( 'all' === $service ) {
  1577. foreach ( (array) $option_connections as $service_name => $service_connections ) {
  1578. foreach ( $service_connections as $id => $connection ) {
  1579. $connections[ $id ] = $connection;
  1580. }
  1581. }
  1582. } elseif ( ! empty( $option_connections[ $service ] ) ) {
  1583. $connections = $option_connections[ $service ];
  1584. }
  1585. if ( ! empty( $connections ) ) {
  1586. $count = count( $connections );
  1587. $progress = \WP_CLI\Utils\make_progress_bar(
  1588. /* translators: %s is a lowercase string for a social network. */
  1589. sprintf( __( 'Disconnecting all connections to %s.', 'jetpack' ), $service ),
  1590. $count
  1591. );
  1592. foreach ( $connections as $id => $connection ) {
  1593. if ( false === $publicize->disconnect( false, $id ) ) {
  1594. WP_CLI::error(
  1595. sprintf(
  1596. /* translators: %1$d is a numeric ID and %2$s is a lowercase string for a social network. */
  1597. __( 'Publicize connection %d could not be disconnected', 'jetpack' ),
  1598. $id
  1599. )
  1600. );
  1601. }
  1602. $progress->tick();
  1603. }
  1604. $progress->finish();
  1605. if ( 'all' === $service ) {
  1606. WP_CLI::success( __( 'All publicize connections were successfully disconnected.', 'jetpack' ) );
  1607. } else {
  1608. /* translators: %s is a lowercase string for a social network. */
  1609. WP_CLI::success( __( 'All publicize connections to %s were successfully disconnected.', 'jetpack' ), $service );
  1610. }
  1611. }
  1612. } else {
  1613. if ( false !== $publicize->disconnect( false, $identifier ) ) {
  1614. /* translators: %d is a numeric ID. Example: 1234. */
  1615. WP_CLI::success( sprintf( __( 'Publicize connection %d has been disconnected.', 'jetpack' ), $identifier ) );
  1616. } else {
  1617. /* translators: %d is a numeric ID. Example: 1234. */
  1618. WP_CLI::error( sprintf( __( 'Publicize connection %d could not be disconnected.', 'jetpack' ), $identifier ) );
  1619. }
  1620. }
  1621. break; // disconnect.
  1622. }
  1623. }
  1624. private function get_api_host() {
  1625. $env_api_host = getenv( 'JETPACK_START_API_HOST', true );
  1626. return $env_api_host ? 'https://' . $env_api_host : JETPACK__WPCOM_JSON_API_BASE;
  1627. }
  1628. private function partner_provision_error( $error ) {
  1629. WP_CLI::log(
  1630. json_encode(
  1631. array(
  1632. 'success' => false,
  1633. 'error_code' => $error->get_error_code(),
  1634. 'error_message' => $error->get_error_message(),
  1635. )
  1636. )
  1637. );
  1638. exit( 1 );
  1639. }
  1640. /**
  1641. * Creates the essential files in Jetpack to start building a Gutenberg block or plugin.
  1642. *
  1643. * ## TYPES
  1644. *
  1645. * block: it creates a Jetpack block. All files will be created in a directory under extensions/blocks named based on the block title or a specific given slug.
  1646. *
  1647. * ## BLOCK TYPE OPTIONS
  1648. *
  1649. * The first parameter is the block title and it's not associative. Add it wrapped in quotes.
  1650. * The title is also used to create the slug and the edit PHP class name. If it's something like "Logo gallery", the slug will be 'logo-gallery' and the class name will be LogoGalleryEdit.
  1651. * --slug: Specific slug to identify the block that overrides the one generated based on the title.
  1652. * --description: Allows to provide a text description of the block.
  1653. * --keywords: Provide up to three keywords separated by comma so users can find this block when they search in Gutenberg's inserter.
  1654. * --variation: Allows to decide whether the block should be a production block, experimental, or beta. Defaults to Beta when arg not provided.
  1655. *
  1656. * ## BLOCK TYPE EXAMPLES
  1657. *
  1658. * wp jetpack scaffold block "Cool Block"
  1659. * wp jetpack scaffold block "Amazing Rock" --slug="good-music" --description="Rock the best music on your site"
  1660. * wp jetpack scaffold block "Jukebox" --keywords="music, audio, media"
  1661. * wp jetpack scaffold block "Jukebox" --variation="experimental"
  1662. *
  1663. * @subcommand scaffold block
  1664. * @synopsis <type> <title> [--slug] [--description] [--keywords] [--variation]
  1665. *
  1666. * @param array $args Positional parameters, when strings are passed, wrap them in quotes.
  1667. * @param array $assoc_args Associative parameters like --slug="nice-block".
  1668. */
  1669. public function scaffold( $args, $assoc_args ) {
  1670. // It's ok not to check if it's set, because otherwise WPCLI exits earlier.
  1671. switch ( $args[0] ) {
  1672. case 'block':
  1673. $this->block( $args, $assoc_args );
  1674. break;
  1675. default:
  1676. /* translators: %s is the subcommand */
  1677. WP_CLI::error( sprintf( esc_html__( 'Invalid subcommand %s.', 'jetpack' ), $args[0] ) . ' 👻' );
  1678. exit( 1 );
  1679. }
  1680. }
  1681. /**
  1682. * Creates the essential files in Jetpack to build a Gutenberg block.
  1683. *
  1684. * @param array $args Positional parameters. Only one is used, that corresponds to the block title.
  1685. * @param array $assoc_args Associative parameters defined in the scaffold() method.
  1686. */
  1687. public function block( $args, $assoc_args ) {
  1688. if ( isset( $args[1] ) ) {
  1689. $title = ucwords( $args[1] );
  1690. } else {
  1691. WP_CLI::error( esc_html__( 'The title parameter is required.', 'jetpack' ) . ' 👻' );
  1692. exit( 1 );
  1693. }
  1694. $slug = isset( $assoc_args['slug'] )
  1695. ? $assoc_args['slug']
  1696. : sanitize_title( $title );
  1697. $variation_options = array( 'production', 'experimental', 'beta' );
  1698. $variation = ( isset( $assoc_args['variation'] ) && in_array( $assoc_args['variation'], $variation_options, true ) )
  1699. ? $assoc_args['variation']
  1700. : 'beta';
  1701. if ( preg_match( '#^jetpack/#', $slug ) ) {
  1702. $slug = preg_replace( '#^jetpack/#', '', $slug );
  1703. }
  1704. if ( ! preg_match( '/^[a-z][a-z0-9\-]*$/', $slug ) ) {
  1705. WP_CLI::error( esc_html__( 'Invalid block slug. They can contain only lowercase alphanumeric characters or dashes, and start with a letter', 'jetpack' ) . ' 👻' );
  1706. }
  1707. global $wp_filesystem;
  1708. if ( ! WP_Filesystem() ) {
  1709. WP_CLI::error( esc_html__( "Can't write files", 'jetpack' ) . ' 😱' );
  1710. }
  1711. $path = JETPACK__PLUGIN_DIR . "extensions/blocks/$slug";
  1712. if ( $wp_filesystem->exists( $path ) && $wp_filesystem->is_dir( $path ) ) {
  1713. /* translators: %s is path to the conflicting block */
  1714. WP_CLI::error( sprintf( esc_html__( 'Name conflicts with the existing block %s', 'jetpack' ), $path ) . ' ⛔️' );
  1715. exit( 1 );
  1716. }
  1717. $wp_filesystem->mkdir( $path );
  1718. $hasKeywords = isset( $assoc_args['keywords'] );
  1719. $files = array(
  1720. "$path/$slug.php" => $this->render_block_file(
  1721. 'block-register-php',
  1722. array(
  1723. 'slug' => $slug,
  1724. 'title' => $title,
  1725. 'underscoredSlug' => str_replace( '-', '_', $slug ),
  1726. 'underscoredTitle' => str_replace( ' ', '_', $title ),
  1727. 'jetpackVersion' => substr( JETPACK__VERSION, 0, strpos( JETPACK__VERSION, '.' ) ) . '.x',
  1728. )
  1729. ),
  1730. "$path/index.js" => $this->render_block_file(
  1731. 'block-index-js',
  1732. array(
  1733. 'slug' => $slug,
  1734. 'title' => $title,
  1735. 'description' => isset( $assoc_args['description'] )
  1736. ? $assoc_args['description']
  1737. : $title,
  1738. 'keywords' => $hasKeywords
  1739. ? array_map(
  1740. function( $keyword ) {
  1741. // Construction necessary for Mustache lists
  1742. return array( 'keyword' => trim( $keyword ) );
  1743. },
  1744. explode( ',', $assoc_args['keywords'], 3 )
  1745. )
  1746. : '',
  1747. 'hasKeywords' => $hasKeywords,
  1748. )
  1749. ),
  1750. "$path/editor.js" => $this->render_block_file( 'block-editor-js' ),
  1751. "$path/editor.scss" => $this->render_block_file(
  1752. 'block-editor-scss',
  1753. array(
  1754. 'slug' => $slug,
  1755. 'title' => $title,
  1756. )
  1757. ),
  1758. "$path/edit.js" => $this->render_block_file(
  1759. 'block-edit-js',
  1760. array(
  1761. 'title' => $title,
  1762. 'className' => str_replace( ' ', '', ucwords( str_replace( '-', ' ', $slug ) ) ),
  1763. )
  1764. ),
  1765. "$path/icon.js" => $this->render_block_file( 'block-icon-js' ),
  1766. "$path/attributes.js" => $this->render_block_file( 'block-attributes-js' ),
  1767. );
  1768. $files_written = array();
  1769. foreach ( $files as $filename => $contents ) {
  1770. if ( $wp_filesystem->put_contents( $filename, $contents ) ) {
  1771. $files_written[] = $filename;
  1772. } else {
  1773. /* translators: %s is a file name */
  1774. WP_CLI::error( sprintf( esc_html__( 'Error creating %s', 'jetpack' ), $filename ) );
  1775. }
  1776. }
  1777. if ( empty( $files_written ) ) {
  1778. WP_CLI::log( esc_html__( 'No files were created', 'jetpack' ) );
  1779. } else {
  1780. // Load index.json and insert the slug of the new block in its block variation array.
  1781. $block_list_path = JETPACK__PLUGIN_DIR . 'extensions/index.json';
  1782. $block_list = $wp_filesystem->get_contents( $block_list_path );
  1783. if ( empty( $block_list ) ) {
  1784. /* translators: %s is the path to the file with the block list */
  1785. WP_CLI::error( sprintf( esc_html__( 'Error fetching contents of %s', 'jetpack' ), $block_list_path ) );
  1786. } elseif ( false === stripos( $block_list, $slug ) ) {
  1787. $new_block_list = json_decode( $block_list );
  1788. $new_block_list->{ $variation }[] = $slug;
  1789. // Format the JSON to match our coding standards.
  1790. $new_block_list_formatted = wp_json_encode( $new_block_list, JSON_PRETTY_PRINT ) . "\n";
  1791. $new_block_list_formatted = preg_replace_callback(
  1792. // Find all occurrences of multiples of 4 spaces a the start of the line.
  1793. '/^((?: )+)/m',
  1794. function ( $matches ) {
  1795. // Replace each occurrence of 4 spaces with a tab character.
  1796. return str_repeat( "\t", substr_count( $matches[0], ' ' ) );
  1797. },
  1798. $new_block_list_formatted
  1799. );
  1800. if ( ! $wp_filesystem->put_contents( $block_list_path, $new_block_list_formatted ) ) {
  1801. /* translators: %s is the path to the file with the block list */
  1802. WP_CLI::error( sprintf( esc_html__( 'Error writing new %s', 'jetpack' ), $block_list_path ) );
  1803. }
  1804. }
  1805. if ( 'beta' === $variation || 'experimental' === $variation ) {
  1806. $block_constant = sprintf(
  1807. /* translators: the placeholder is a constant name */
  1808. esc_html__( 'To load the block, add the constant %1$s as true to your wp-config.php file', 'jetpack' ),
  1809. ( 'beta' === $variation ? 'JETPACK_BETA_BLOCKS' : 'JETPACK_EXPERIMENTAL_BLOCKS' )
  1810. );
  1811. } else {
  1812. $block_constant = '';
  1813. }
  1814. WP_CLI::success(
  1815. sprintf(
  1816. /* translators: the placeholders are a human readable title, and a series of words separated by dashes */
  1817. esc_html__( 'Successfully created block %1$s with slug %2$s', 'jetpack' ) . ' 🎉' . "\n" .
  1818. "--------------------------------------------------------------------------------------------------------------------\n" .
  1819. /* translators: the placeholder is a directory path */
  1820. esc_html__( 'The files were created at %3$s', 'jetpack' ) . "\n" .
  1821. esc_html__( 'To start using the block, build the blocks with pnpm run build-extensions', 'jetpack' ) . "\n" .
  1822. /* translators: the placeholder is a file path */
  1823. esc_html__( 'The block slug has been added to the %4$s list at %5$s', 'jetpack' ) . "\n" .
  1824. '%6$s' . "\n" .
  1825. /* translators: the placeholder is a URL */
  1826. "\n" . esc_html__( 'Read more at %7$s', 'jetpack' ) . "\n",
  1827. $title,
  1828. $slug,
  1829. $path,
  1830. $variation,
  1831. $block_list_path,
  1832. $block_constant,
  1833. 'https://github.com/Automattic/jetpack/blob/master/extensions/README.md#develop-new-blocks'
  1834. ) . '--------------------------------------------------------------------------------------------------------------------'
  1835. );
  1836. }
  1837. }
  1838. /**
  1839. * Built the file replacing the placeholders in the template with the data supplied.
  1840. *
  1841. * @param string $template
  1842. * @param array $data
  1843. *
  1844. * @return string mixed
  1845. */
  1846. private static function render_block_file( $template, $data = array() ) {
  1847. return \WP_CLI\Utils\mustache_render( JETPACK__PLUGIN_DIR . "wp-cli-templates/$template.mustache", $data );
  1848. }
  1849. }
  1850. /*
  1851. * Standard "ask for permission to continue" function.
  1852. * If action cancelled, ask if they need help.
  1853. *
  1854. * Written outside of the class so it's not listed as an executable command w/ 'wp jetpack'
  1855. *
  1856. * @param $flagged bool false = normal option | true = flagged by get_jetpack_options_for_reset()
  1857. * @param $error_msg string (optional)
  1858. */
  1859. function jetpack_cli_are_you_sure( $flagged = false, $error_msg = false ) {
  1860. $cli = new Jetpack_CLI();
  1861. // Default cancellation message
  1862. if ( ! $error_msg ) {
  1863. $error_msg =
  1864. __( 'Action cancelled. Have a question?', 'jetpack' )
  1865. . ' '
  1866. . $cli->green_open
  1867. . 'jetpack.com/support'
  1868. . $cli->color_close;
  1869. }
  1870. if ( ! $flagged ) {
  1871. $prompt_message = _x( 'Are you sure? This cannot be undone. Type "yes" to continue:', '"yes" is a command - do not translate.', 'jetpack' );
  1872. } else {
  1873. $prompt_message = _x( 'Are you sure? Modifying this option may disrupt your Jetpack connection. Type "yes" to continue.', '"yes" is a command - do not translate.', 'jetpack' );
  1874. }
  1875. WP_CLI::line( $prompt_message );
  1876. $handle = fopen( 'php://stdin', 'r' );
  1877. $line = fgets( $handle );
  1878. if ( 'yes' != trim( $line ) ) {
  1879. WP_CLI::error( $error_msg );
  1880. }
  1881. }