v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
+6
View File
@@ -0,0 +1,6 @@
function ze(e,t){return function(){return e.apply(t,arguments)}}const{toString:ht}=Object.prototype,{getPrototypeOf:we}=Object,{iterator:re,toStringTag:Je}=Symbol,se=(e=>t=>{const n=ht.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),P=e=>(e=e.toLowerCase(),t=>se(t)===e),oe=e=>t=>typeof t===e,{isArray:M}=Array,I=oe("undefined");function V(e){return e!==null&&!I(e)&&e.constructor!==null&&!I(e.constructor)&&T(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Ve=P("ArrayBuffer");function mt(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Ve(e.buffer),t}const yt=oe("string"),T=oe("function"),We=oe("number"),W=e=>e!==null&&typeof e=="object",bt=e=>e===!0||e===!1,Y=e=>{if(se(e)!=="object")return!1;const t=we(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Je in e)&&!(re in e)},wt=e=>{if(!W(e)||V(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Et=P("Date"),gt=P("File"),Rt=P("Blob"),St=P("FileList"),Ot=e=>W(e)&&T(e.pipe),Tt=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||T(e.append)&&((t=se(e))==="formdata"||t==="object"&&T(e.toString)&&e.toString()==="[object FormData]"))},At=P("URLSearchParams"),[xt,Ct,Nt,Pt]=["ReadableStream","Request","Response","Headers"].map(P),Ft=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function K(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),M(e))for(r=0,s=e.length;r<s;r++)t.call(null,e[r],r,e);else{if(V(e))return;const i=n?Object.getOwnPropertyNames(e):Object.keys(e),o=i.length;let c;for(r=0;r<o;r++)c=i[r],t.call(null,e[c],c,e)}}function Ke(e,t){if(V(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,s;for(;r-- >0;)if(s=n[r],t===s.toLowerCase())return s;return null}const D=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ve=e=>!I(e)&&e!==D;function pe(){const{caseless:e,skipUndefined:t}=ve(this)&&this||{},n={},r=(s,i)=>{const o=e&&Ke(n,i)||i;Y(n[o])&&Y(s)?n[o]=pe(n[o],s):Y(s)?n[o]=pe({},s):M(s)?n[o]=s.slice():(!t||!I(s))&&(n[o]=s)};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&K(arguments[s],r);return n}const _t=(e,t,n,{allOwnKeys:r}={})=>(K(t,(s,i)=>{n&&T(s)?e[i]=ze(s,n):e[i]=s},{allOwnKeys:r}),e),Ut=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Lt=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Bt=(e,t,n,r)=>{let s,i,o;const c={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)o=s[i],(!r||r(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=n!==!1&&we(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kt=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},Dt=e=>{if(!e)return null;if(M(e))return e;let t=e.length;if(!We(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},jt=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&we(Uint8Array)),qt=(e,t)=>{const r=(e&&e[re]).call(e);let s;for(;(s=r.next())&&!s.done;){const i=s.value;t.call(e,i[0],i[1])}},Ht=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},It=P("HTMLFormElement"),Mt=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),Ce=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),$t=P("RegExp"),Xe=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};K(n,(s,i)=>{let o;(o=t(s,i,e))!==!1&&(r[i]=o||s)}),Object.defineProperties(e,r)},zt=e=>{Xe(e,(t,n)=>{if(T(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(T(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Jt=(e,t)=>{const n={},r=s=>{s.forEach(i=>{n[i]=!0})};return M(e)?r(e):r(String(e).split(t)),n},Vt=()=>{},Wt=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Kt(e){return!!(e&&T(e.append)&&e[Je]==="FormData"&&e[re])}const vt=e=>{const t=new Array(10),n=(r,s)=>{if(W(r)){if(t.indexOf(r)>=0)return;if(V(r))return r;if(!("toJSON"in r)){t[s]=r;const i=M(r)?[]:{};return K(r,(o,c)=>{const d=n(o,s+1);!I(d)&&(i[c]=d)}),t[s]=void 0,i}}return r};return n(e,0)},Xt=P("AsyncFunction"),Gt=e=>e&&(W(e)||T(e))&&T(e.then)&&T(e.catch),Ge=((e,t)=>e?setImmediate:t?((n,r)=>(D.addEventListener("message",({source:s,data:i})=>{s===D&&i===n&&r.length&&r.shift()()},!1),s=>{r.push(s),D.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",T(D.postMessage)),Qt=typeof queueMicrotask<"u"?queueMicrotask.bind(D):typeof process<"u"&&process.nextTick||Ge,Zt=e=>e!=null&&T(e[re]),a={isArray:M,isArrayBuffer:Ve,isBuffer:V,isFormData:Tt,isArrayBufferView:mt,isString:yt,isNumber:We,isBoolean:bt,isObject:W,isPlainObject:Y,Line truncated
`).forEach(function(o){s=o.indexOf(":"),n=o.substring(0,s).trim().toLowerCase(),r=o.substring(s+1).trim(),!(!n||t[n]&&yn[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},_e=Symbol("internals");function J(e){return e&&String(e).trim().toLowerCase()}function ee(e){return e===!1||e==null?e:a.isArray(e)?e.map(ee):String(e)}function wn(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const En=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function ue(e,t,n,r,s){if(a.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!a.isString(t)){if(a.isString(r))return t.indexOf(r)!==-1;if(a.isRegExp(r))return r.test(t)}}function gn(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Rn(e,t){const n=a.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,i,o){return this[r].call(this,t,s,i,o)},configurable:!0})})}let A=class{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function i(c,d,f){const l=J(d);if(!l)throw new Error("header name must be a non-empty string");const h=a.findKey(s,l);(!h||s[h]===void 0||f===!0||f===void 0&&s[h]!==!1)&&(s[h||d]=ee(c))}const o=(c,d)=>a.forEach(c,(f,l)=>i(f,l,d));if(a.isPlainObject(t)||t instanceof this.constructor)o(t,n);else if(a.isString(t)&&(t=t.trim())&&!En(t))o(bn(t),n);else if(a.isObject(t)&&a.isIterable(t)){let c={},d,f;for(const l of t){if(!a.isArray(l))throw TypeError("Object iterator must return a key-value pair");c[f=l[0]]=(d=c[f])?a.isArray(d)?[...d,l[1]]:[d,l[1]]:l[1]}o(c,n)}else t!=null&&i(n,t,r);return this}get(t,n){if(t=J(t),t){const r=a.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return wn(s);if(a.isFunction(n))return n.call(this,s,r);if(a.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=J(t),t){const r=a.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||ue(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function i(o){if(o=J(o),o){const c=a.findKey(r,o);c&&(!n||ue(r,r[c],c,n))&&(delete r[c],s=!0)}}return a.isArray(t)?t.forEach(i):i(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const i=n[r];(!t||ue(this,this[i],i,t,!0))&&(delete this[i],s=!0)}return s}normalize(t){const n=this,r={};return a.forEach(this,(s,i)=>{const o=a.findKey(r,i);if(o){n[o]=ee(s),delete n[i];return}const c=t?gn(i):String(i).trim();c!==i&&delete n[i],n[c]=ee(s),r[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return a.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&a.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[_e]=this[_e]={accessors:{}}).accessors,s=this.prototype;function i(o){const c=J(o);r[c]||(Rn(s,o),r[c]=!0)}return a.isArray(t)?t.forEach(i):i(t),this}};A.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.reduceDescriptors(A.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});a.freezeMethods(A);function fe(e,t){const n=this||v,r=t||n,s=A.from(r.headers);let i=r.data;return a.forEach(e,function(c){i=c.call(n,i,s.normalize(),t?t.status:void 0)}),s.normalize(),i}function st(e){return!!(e&&e.__CANCEL__)}function $(e,t,n){y.call(this,e??"canceled",y.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits($,y,{__CANCEL__:!0});function ot(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new y("Request failed with status code "+n.status,[y.ERR_BAD_REQUEST,y.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Sn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function On(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,i=0,o;return t=t!==void 0?t:1e3,function(d){const f=Date.now(),l=r[i];o||(o=f),n[s]=d,r[s]=f;let h=i,b=0;for(;h!==s;)b+=n[h++],h=h%e;if(s=(s+1)%e,s===i&&(i=(i+1)%e),f-o<t)return;const R=l&&f-l;return R?Math.round(b*1e3/R):void 0}}function Tn(e,t){let n=0,r=1e3/t,s,i;const o=(f,l=Date.now())=>{n=l,s=null,i&&(clearTimeout(i),i=null),e(...f)};return[(...f)=>{const l=Date.now(),h=l-n;h>=r?o(f,l):(s=f,i||(i=setTimeout(()=>{i=null,o(s)},r-h)))},()=>s&&o(s)]}const ne=(e,t,n=3)=>{let r=0;const s=On(50,250);return Tn(i=>{const o=i.loaded,c=i.lengthComputable?i.total:void 0,d=o-r,f=s(d),l=o<=c;r=o;const h={loaded:o,total:c,progress:c?o/c:void 0,bytes:d,rate:f||void 0,estimated:f&&c&&l?(c-o)/f:void 0,event:i,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(h)},n)},Ue=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Le=e=>(...t)=>a.asap(()=>e(...t)),An=S.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,S.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(S.origin),S.navigator&&/(msie|trident)/i.test(S.navigator.userAgent)):()=>!0,xn=S.hasStandardBrowserEnv?{write(e,t,n,r,s,i){const o=[e+"="+encodeURIComponent(t)];a.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),a.isString(r)&&o.push("path="+r),a.isString(s)&&o.push("domain="+s),i===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Cn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Nn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function it(e,t,n){let r=!Cn(t);return e&&(r||n==!1)?Nn(e,t):t}const Be=e=>e instanceof A?{...e}:e;function q(e,t){t=t||{};const n={};function r(f,l,h,b){return a.isPlainObject(f)&&a.isPlainObject(l)?a.merge.call({caseless:b},f,l):a.isPlainObject(l)?a.merge({},l):a.isArray(l)?l.slice():l}function s(f,l,h,b){if(a.isUndefined(l)){if(!a.isUndefined(f))return r(void 0,f,h,b)}else return r(f,l,h,b)}function i(f,l){if(!a.isUndefined(l))return r(void 0,l)}function o(f,l){if(a.isUndefined(l)){if(!a.isUndefined(f))return r(void 0,f)}else return r(void 0,l)}function c(f,l,h){if(h in t)return r(f,l);if(h in e)return r(void 0,f)}const d={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(f,l,h)=>s(Be(f),Be(l),h,!0)};return a.forEach(Object.keys({...e,...t}),function(l){const h=d[l]||s,b=h(e[l],t[l],l);a.isUndefined(b)&&h!==c||(n[l]=b)}),n}const at=e=>{const t=q({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:i,headers:o,auth:c}=t;if(t.headers=o=A.from(o),t.url=tt(it(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),a.isFormData(n)){if(S.hasStandardBrowserEnv||S.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(a.isFunction(n.getHeaders)){const d=n.getHeaders(),f=["content-type","content-length"];Object.entries(d).forEach(([l,h])=>{f.includes(l.toLowerCase())&&o.set(l,h)})}}if(S.hasStandardBrowserEnv&&(r&&a.isFunction(r)&&(r=r(t)),r||r!==!1&&An(t.url))){const d=s&&i&&xn.read(i);d Line truncated
`+o.map(Ie).join(`
`):" "+Ie(o[0]):"as no adapter specified";throw new y("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return s},adapters:ye};function de(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new $(null,e)}function Me(e){return de(e),e.headers=A.from(e.headers),e.data=fe.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),lt.getAdapter(e.adapter||v.adapter,e)(e).then(function(r){return de(e),r.data=fe.call(e,e.transformResponse,r),r.headers=A.from(r.headers),r},function(r){return st(r)||(de(e),r&&r.response&&(r.response.data=fe.call(e,e.transformResponse,r.response),r.response.headers=A.from(r.response.headers))),Promise.reject(r)})}const ut="1.12.2",ae={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ae[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const $e={};ae.transitional=function(t,n,r){function s(i,o){return"[Axios v"+ut+"] Transitional option '"+i+"'"+o+(r?". "+r:"")}return(i,o,c)=>{if(t===!1)throw new y(s(o," has been removed"+(n?" in "+n:"")),y.ERR_DEPRECATED);return n&&!$e[o]&&($e[o]=!0,console.warn(s(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,o,c):!0}};ae.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Hn(e,t,n){if(typeof e!="object")throw new y("options must be an object",y.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const i=r[s],o=t[i];if(o){const c=e[i],d=c===void 0||o(c,i,e);if(d!==!0)throw new y("option "+i+" must be "+d,y.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new y("Unknown option "+i,y.ERR_BAD_OPTION)}}const te={assertOptions:Hn,validators:ae},_=te.validators;let j=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Fe,response:new Fe}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const i=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?i&&!String(r.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(r.stack+=`
`+i):r.stack=i}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=q(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:i}=n;r!==void 0&&te.assertOptions(r,{silentJSONParsing:_.transitional(_.boolean),forcedJSONParsing:_.transitional(_.boolean),clarifyTimeoutError:_.transitional(_.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:te.assertOptions(s,{encode:_.function,serialize:_.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),te.assertOptions(n,{baseUrl:_.spelling("baseURL"),withXsrfToken:_.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=i&&a.merge(i.common,i[n.method]);i&&a.forEach(["delete","get","head","post","put","patch","common"],u=>{delete i[u]}),n.headers=A.concat(o,i);const c=[];let d=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(d=d&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const f=[];this.interceptors.response.forEach(function(m){f.push(m.fulfilled,m.rejected)});let l,h=0,b;if(!d){const u=[Me.bind(this),void 0];for(u.unshift(...c),u.push(...f),b=u.length,l=Promise.resolve(n);h<b;)l=l.then(u[h++],u[h++]);return l}b=c.length;let R=n;for(;h<b;){const u=c[h++],m=c[h++];try{R=u(R)}catch(p){m.call(this,p);break}}try{l=Me.call(this,R)}catch(u){return Promise.reject(u)}for(h=0,b=f.length;h<b;)l=l.then(f[h++],f[h++]);return l}getUri(t){t=q(this.defaults,t);const n=it(t.baseURL,t.url,t.allowAbsoluteUrls);return tt(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){j.prototype[t]=function(n,r){return this.request(q(r||{},{method:t,url:n,data:(r||{}).data}))}});a.forEach(["post","put","patch"],function(t){function n(r){return function(i,o,c){return this.request(q(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:i,data:o}))}}j.prototype[t]=n(),j.prototype[t+"Form"]=n(!0)});let In=class ft{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(i){n=i});const r=this;this.promise.then(s=>{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](s);r._listeners=null}),this.promise.then=s=>{let i;const o=new Promise(c=>{r.subscribe(c),i=c}).then(s);return o.cancel=function(){r.unsubscribe(i)},o},t(function(i,o,c){r.reason||(r.reason=new $(i,o,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new ft(function(s){t=s}),cancel:t}}};function Mn(e){return function(n){return e.apply(null,n)}}function $n(e){return a.isObject(e)&&e.isAxiosError===!0}const be={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(be).forEach(([e,t])=>{be[t]=e});function dt(e){const t=new j(e),n=ze(j.prototype.request,t);return a.extend(n,j.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return dt(q(e,s))},n}const w=dt(v);w.Axios=j;w.CanceledError=$;w.CancelToken=In;w.isCancel=st;w.VERSION=ut;w.toFormData=ie;w.AxiosError=y;w.Cancel=w.CanceledError;w.all=function(t){return Promise.all(t)};w.spread=Mn;w.isAxiosError=$n;w.mergeConfig=q;w.AxiosHeaders=A;w.formToJSON=e=>rt(a.isHTMLForm(e)?new FormData(e):e);w.getAdapter=lt.getAdapter;w.HttpStatusCode=be;w.default=w;const{Axios:Vn,AxiosError:Wn,CanceledError:Kn,isCancel:vn Line truncated
+1
View File
@@ -0,0 +1 @@
/*! tailwindcss v4.1.16 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-pan-x:initial;--tw-pan-y:initial;--tw-pinch-zoom:initial;--tw-scroll-snap-strictness:proximity;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:""}}}@layer theme{:root,:host{--font-sans:"Instrument Sans",ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-200:oklch(88.5% .062 18.334);--color-red-300:oklch(80.8% .114 19.571);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-red-900:oklch(39.6% .141 25.723);--color-red-950:oklch(25.8% .092 26.042);--color-orange-50:oklch(98% .016 73.684);--color-orange-100:oklch(95.4% .038 75.164);--color-orange-200:oklch(90.1% .076 70.697);--color-orange-300:oklch(83.7% .128 66.29);--color-orange-400:oklch(75% .183 55.934);--color-orange-500:oklch(70.5% .213 47.604);--color-orange-600:oklch(64.6% .222 41.116);--color-orange-700:oklch(55.3% .195 38.402);--color-orange-800:oklch(47% .157 37.304);--color-orange-900:oklch(40.8% .123 38.172);--color-orange-950:oklch(26.6% .079 36.259);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-900:oklch(41.4% .112 45.904);--color-amber-950:oklch(27.9% .077 45.635);--color-yellow-50:oklch(98.7% .026 102.212);--color-yellow-100:oklch(97.3% .071 103.193);--color-yellow-200:oklch(94.5% .129 101.54);--color-yellow-300:oklch(90.5% .182 98.111);--color-yellow-400:oklch(85.2% .199 91.936);--color-yellow-500:oklch(79.5% .184 86.047);--color-yellow-600:oklch(68.1% .162 75.834);--color-yellow-700:oklch(55.4% .135 66.442);--color-yellow-800:oklch(47.6% .114 61.907);--color-yellow-900:oklch(42.1% .095 57.708);--color-yellow-950:oklch(28.6% .066 53.813);--color-lime-50:oklch(98.6% .031 120.757);--color-lime-100:oklch(96.7% .067 122.328);--color-lime-200:oklch(93.8% .127 124.321);--color-lime-300:oklch(89.7% .196 126.665);--color-lime-400:oklch(84.1% .238 128.85);--color-lime-500:oklch(76.8% .233 130.85);--color-lime-600:oklch(64.8% .2 131.684);--color-lime-700:oklch(53.2% .157 131.589);--color-lime-800:oklch(45.3% .124 130.933);--color-lime-900:oklch(40.5% .101 131.063);--color-lime-950:oklch(27.4% .072 132.109);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-200:oklch(92.5% .084 155.995);--color-green-300:oklch(87.1% .15 154.449);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7Line truncated
+14
View File
@@ -0,0 +1,14 @@
{
"core": {
"errors": {
"template_not_found": "No active template found",
"layout_load_failed": "Failed to load layout",
"layout_load_failed_with_id": "Failed to load layout ({layoutId})",
"component_load_failed": "Failed to load component",
"component_load_failed_with_name": "Failed to load component ({componentName})",
"translation_load_failed": "Failed to load translation file",
"translation_load_failed_with_locale": "Failed to load {locale} translation file",
"template_init_error": "An error occurred while initializing the template engine"
}
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"core": {
"errors": {
"template_not_found": "활성화된 템플릿이 없습니다",
"layout_load_failed": "레이아웃을 불러오는데 실패했습니다",
"layout_load_failed_with_id": "레이아웃({layoutId})을 불러오는데 실패했습니다",
"component_load_failed": "컴포넌트를 불러오는데 실패했습니다",
"component_load_failed_with_name": "컴포넌트({componentName})를 불러오는데 실패했습니다",
"translation_load_failed": "다국어 파일을 불러오는데 실패했습니다",
"translation_load_failed_with_locale": "{locale} 다국어 파일을 불러오는데 실패했습니다",
"template_init_error": "템플릿 엔진을 초기화하는 중 오류가 발생했습니다"
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
{"version":3,"file":"template-engine.min.js","sources":["../../../node_modules/react/cjs/react.production.js","../../../node_modules/react/index.js","../../../node_modules/scheduler/cjs/scheduler.production.js","../../../node_modules/scheduler/index.js","../../../node_modules/react-dom/cjs/react-dom.production.js","../../../node_modules/react-dom/index.js","../../../node_modules/react-dom/cjs/react-dom-client.production.js","../../../node_modules/react-dom/client.js","../../../resources/js/core/utils/Logger.ts","../../../resources/js/core/template-engine/ComponentRegistry.ts","../../../resources/js/core/template-engine/TranslationEngine.ts","../../../resources/js/core/template-engine/PipeRegistry.ts","../../../resources/js/core/template-engine/rawMarkers.ts","../../../resources/js/core/template-engine/DataBindingEngine.ts","../../../resources/js/core/template-engine/ResponsiveManager.ts","../../../resources/js/core/template-engine/helpers/ConditionEvaluator.ts","../../../resources/js/core/template-engine/helpers/RenderHelpers.ts","../../../node_modules/axios/lib/helpers/bind.js","../../../node_modules/axios/lib/utils.js","../../../node_modules/axios/lib/core/AxiosError.js","../../../node_modules/axios/lib/helpers/null.js","../../../node_modules/axios/lib/helpers/toFormData.js","../../../node_modules/axios/lib/helpers/AxiosURLSearchParams.js","../../../node_modules/axios/lib/helpers/buildURL.js","../../../node_modules/axios/lib/core/InterceptorManager.js","../../../node_modules/axios/lib/defaults/transitional.js","../../../node_modules/axios/lib/platform/browser/index.js","../../../node_modules/axios/lib/platform/browser/classes/URLSearchParams.js","../../../node_modules/axios/lib/platform/browser/classes/FormData.js","../../../node_modules/axios/lib/platform/browser/classes/Blob.js","../../../node_modules/axios/lib/platform/common/utils.js","../../../node_modules/axios/lib/platform/index.js","../../../node_modules/axios/lib/helpers/toURLEncodedForm.js","../../../node_modules/axios/lib/helpers/formDataToJSON.js","../../../node_modules/axios/lib/defaults/index.js","../../../node_modules/axios/lib/helpers/parseHeaders.js","../../../node_modules/axios/lib/core/AxiosHeaders.js","../../../node_modules/axios/lib/core/transformData.js","../../../node_modules/axios/lib/cancel/isCancel.js","../../../node_modules/axios/lib/cancel/CanceledError.js","../../../node_modules/axios/lib/core/settle.js","../../../node_modules/axios/lib/helpers/parseProtocol.js","../../../node_modules/axios/lib/helpers/speedometer.js","../../../node_modules/axios/lib/helpers/throttle.js","../../../node_modules/axios/lib/helpers/progressEventReducer.js","../../../node_modules/axios/lib/helpers/isURLSameOrigin.js","../../../node_modules/axios/lib/helpers/cookies.js","../../../node_modules/axios/lib/helpers/isAbsoluteURL.js","../../../node_modules/axios/lib/helpers/combineURLs.js","../../../node_modules/axios/lib/core/buildFullPath.js","../../../node_modules/axios/lib/core/mergeConfig.js","../../../node_modules/axios/lib/helpers/resolveConfig.js","../../../node_modules/axios/lib/adapters/xhr.js","../../../node_modules/axios/lib/helpers/composeSignals.js","../../../node_modules/axios/lib/helpers/trackStream.js","../../../node_modules/axios/lib/adapters/fetch.js","../../../node_modules/axios/lib/adapters/adapters.js","../../../node_modules/axios/lib/core/dispatchRequest.js","../../../node_modules/axios/lib/env/data.js","../../../node_modules/axios/lib/helpers/validator.js","../../../node_modules/axios/lib/core/Axios.js","../../../node_modules/axios/lib/cancel/CancelToken.js","../../../node_modules/axios/lib/helpers/spread.js","../../../node_modules/axios/lib/helpers/isAxiosError.js","../../../node_modules/axios/lib/helpers/HttpStatusCode.js","../../../node_modules/axios/lib/axios.js","../../../node_modules/axios/index.js","../../../resources/js/core/api/ApiClient.ts","../../../resources/js/core/auth/AuthManager.ts","../../../resources/js/core/types/ErrorHandling.ts","../../../resources/js/core/error/ErrorHandlingResolver.ts","../../../node_modules/react/cjs/react-jsx-runtime.production.js","../../../node_modules/react/jsx-runtime.js","../../../resources/js/core/template-engine/ParentContextProvider.tsx","../../../resources/js/core/template-engine/ActionDispatcher.ts","../../../resources/js/core/template-engine/TransitionManager.ts","../../../resources/js/core/template-engine/TransitionContext.tsx","../../../resources/js/core/template-engine/ResponsiveContext.tsx","../../../resources/js/core/template-engine/FormContext.tsx","../../../resources/js/core/template-engine/IsolatedStateContext.tsx","../../../node_modules/@dnd-kit/utilities/dist/utilities.esm.js","../../../node_modules/@dnd-kit/accessibility/dist/accessibility.esm.js","../../../node_modules/@dnd-kit/core/dist/core.esm.js","../../../node_modules/@dnd-kit/sortable/dist/sortable.esm.js","../../../resources/js/core/template-engine/sortable/SortableContainer.tsx","../../../resources/js/core/teLine truncated
+16
View File
@@ -0,0 +1,16 @@
{
"resources/css/app.css": {
"file": "assets/app-vMwpJt-1.css",
"src": "resources/css/app.css",
"isEntry": true,
"names": [
"app.css"
]
},
"resources/js/app.js": {
"file": "assets/app-Bj43h_rG.js",
"name": "app",
"src": "resources/js/app.js",
"isEntry": true
}
}
View File
Whitespace-only changes.
+93
View File
@@ -0,0 +1,93 @@
<?php
// 설치 완료 여부 확인
$installedFlagPath = __DIR__ . '/../storage/app/g7_installed';
$envPath = __DIR__ . '/../.env';
// 설치 확인: g7_installed 파일 또는 .env의 INSTALLER_COMPLETED
$isInstalled = file_exists($installedFlagPath) || (
file_exists($envPath) &&
preg_match('/^INSTALLER_COMPLETED=true$/m', file_get_contents($envPath))
);
// 미설치 시 /install로 리다이렉트
if (!$isInstalled) {
$installUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/') . '/install';
echo '<script>
alert("G7 최초 사용을 위해 설치 절차가 필요합니다. 설치 화면으로 이동합니다.");
window.location.href="' . htmlspecialchars($installUrl) . '";
</script>';
exit;
}
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
$loader = require __DIR__.'/../vendor/autoload.php';
// Register extension (module/plugin) autoload...
$extensionAutoloadFile = __DIR__.'/../bootstrap/cache/autoload-extensions.php';
if (file_exists($extensionAutoloadFile)) {
// CoreServiceProvider에서 중복 등록 방지용 플래그
define('G7_EXTENSION_AUTOLOAD_REGISTERED', true);
$extensionAutoloads = require $extensionAutoloadFile;
// PSR-4 네임스페이스 등록
if (!empty($extensionAutoloads['psr4'])) {
foreach ($extensionAutoloads['psr4'] as $namespace => $paths) {
// 경로가 배열인 경우와 문자열인 경우 모두 처리
$paths = (array) $paths;
foreach ($paths as $path) {
$absolutePath = __DIR__.'/../'.$path;
if (is_dir($absolutePath)) {
$loader->addPsr4($namespace, $absolutePath);
}
}
}
}
// Classmap 파일 로드 (module.php, plugin.php)
if (!empty($extensionAutoloads['classmap'])) {
foreach ($extensionAutoloads['classmap'] as $file) {
$absolutePath = __DIR__.'/../'.$file;
if (file_exists($absolutePath)) {
require_once $absolutePath;
}
}
}
// Files 로드 (헬퍼 함수 등)
if (!empty($extensionAutoloads['files'])) {
foreach ($extensionAutoloads['files'] as $file) {
$absolutePath = __DIR__.'/../'.$file;
if (file_exists($absolutePath)) {
require_once $absolutePath;
}
}
}
// Vendor autoloads 로드 (모듈/플러그인의 composer 의존성)
if (!empty($extensionAutoloads['vendor_autoloads'])) {
foreach ($extensionAutoloads['vendor_autoloads'] as $vendorAutoload) {
$absolutePath = __DIR__.'/../'.$vendorAutoload;
if (file_exists($absolutePath)) {
require_once $absolutePath;
}
}
}
}
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());
+915
View File
@@ -0,0 +1,915 @@
<?php
/**
* G7 인스톨러 - 검증 통합 API
*
* 서버 요구사항 검증 및 데이터베이스 연결 테스트 기능을 하나의 API로 통합
*
* 엔드포인트:
* - GET ?action=requirements : 서버 요구사항 검증 (action 생략 시 기본값)
* - POST ?action=test-db : 데이터베이스 연결 테스트
*/
/**
* 검증 API 클래스
*/
class ValidationApi
{
/**
* 요청 처리 메인 메서드
*/
public function handleRequest(): void
{
// JSON 헤더 설정
$this->setJsonHeaders();
// HTTP 메서드 및 action 파라미터 확인
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? ($method === 'GET' ? 'requirements' : null);
try {
// action에 따라 적절한 메서드 호출
match ($action) {
'requirements' => $this->checkRequirements(),
'test-db' => $this->testDbConnection(),
'detect-php' => $this->detectPhpBinaries(),
'test-php-binary' => $this->testPhpBinary(),
'test-composer' => $this->testComposer(),
'check-core-pending-path' => $this->checkCorePendingPath(),
default => $this->error400('Invalid action parameter'),
};
} catch (Throwable $e) {
$this->error500($e);
}
}
/**
* JSON 응답 헤더 설정
*/
private function setJsonHeaders(): void
{
header('Content-Type: application/json; charset=utf-8');
}
/**
* GET ?action=requirements
* 서버 요구사항 검증
*
* PHP 버전, 확장 모듈, 디스크 공간, 디렉토리 권한, HTTPS 등을 검증합니다.
*/
private function checkRequirements(): void
{
// 요구사항 검증 결과 배열
$requirements = [
'php_version' => $this->checkPhpVersion(),
'php_extensions' => $this->checkPhpExtensions(),
'disabled_functions' => $this->checkDisabledFunctions(),
'php_cli_version' => $this->checkPhpCliVersion(),
'disk_space' => $this->checkDiskSpace(),
'directories' => $this->checkDirectoryPermissions(),
'required_files' => $this->checkRequiredFiles(),
'https' => $this->checkHttps(),
];
// 모든 필수 요구사항 통과 여부
$requirements['all_required_passed'] = $this->isAllRequiredPassed($requirements);
// OS 정보 (프론트엔드에서 명령어 분기용)
$requirements['is_windows'] = isWindows();
// JSON 응답 반환
echo json_encode($requirements, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
/**
* POST ?action=test-db
* 데이터베이스 연결 테스트
*
* POST로 전달받은 데이터베이스 연결 정보를 사용하여
* 연결 테스트 및 권한 검증을 수행합니다.
*/
private function testDbConnection(): void
{
// POST 메서드만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => lang('api_method_not_allowed'),
], JSON_UNESCAPED_UNICODE);
exit;
}
try {
// POST 데이터 파싱
$input = json_decode(file_get_contents('php://input'), true);
if (! $input || ! is_array($input)) {
throw new Exception(lang('api_invalid_request'));
}
// DB 타입 확인 ('write' 또는 'read')
$type = $input['type'] ?? 'write';
$isReadDb = ($type === 'read');
// DB 연결 정보 구성
$config = [];
if ($isReadDb) {
$config['db_read_host'] = $input['host'] ?? 'localhost';
$config['db_read_port'] = $input['port'] ?? '3306';
$config['db_read_database'] = $input['database'] ?? '';
$config['db_read_username'] = $input['username'] ?? '';
$config['db_read_password'] = $input['password'] ?? '';
} else {
$config['db_write_host'] = $input['host'] ?? 'localhost';
$config['db_write_port'] = $input['port'] ?? '3306';
$config['db_write_database'] = $input['database'] ?? '';
$config['db_write_username'] = $input['username'] ?? '';
$config['db_write_password'] = $input['password'] ?? '';
}
// 필수 필드 검증
$database = $isReadDb ? $config['db_read_database'] : $config['db_write_database'];
$username = $isReadDb ? $config['db_read_username'] : $config['db_write_username'];
if (empty($database) || empty($username)) {
throw new Exception(lang('error_db_credentials_required'));
}
// 데이터베이스 연결 시도
$pdo = getDatabaseConnection($config, $isReadDb);
// 권한 검증
$privileges = checkDatabasePrivileges($pdo, $database, $isReadDb);
// 권한 부족 확인
if (! $privileges['has_all'] && ! empty($privileges['missing'])) {
$missingPrivs = implode(', ', $privileges['missing']);
$dbTypeLabel = $isReadDb ? 'Read' : 'Write';
throw new Exception(
lang('error_db_privileges_insufficient_detail', ['type' => $dbTypeLabel, 'missing' => $missingPrivs])
);
}
// 연결 및 권한 검증 성공 플래그 (Write/Read 구분)
if ($isReadDb) {
$_SESSION['db_read_tested'] = true;
$message = lang('success_db_read_connected');
} else {
$_SESSION['db_write_tested'] = true;
$message = lang('success_db_write_connected');
}
// 성공 응답
echo json_encode([
'success' => true,
'message' => $message,
'type' => $type,
'privileges' => [
'has_all' => $privileges['has_all'],
'found' => $privileges['found'],
'required' => $privileges['required'],
],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
// 연결 실패 플래그
$isReadDb = isset($type) && $type === 'read';
if ($isReadDb) {
$_SESSION['db_read_tested'] = false;
} else {
$_SESSION['db_write_tested'] = false;
}
// 에러 로깅
logInstallationError(lang('error_db_connection_failed'), $e);
// 에러 응답 (200 OK + success: false)
echo json_encode([
'success' => false,
'message' => lang('error_db_connection_failed_detail', ['type' => ($isReadDb ? 'Read' : 'Write'), 'error' => $e->getMessage()]),
'type' => $type ?? 'write',
], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
// 권한 검증 실패 또는 기타 에러
$isReadDb = isset($type) && $type === 'read';
if (isset($type)) {
if ($isReadDb) {
$_SESSION['db_read_tested'] = false;
} else {
$_SESSION['db_write_tested'] = false;
}
}
// 에러 로깅
logInstallationError(lang('error_db_test_failed'), $e);
// 에러 응답 (200 OK + success: false)
echo json_encode([
'success' => false,
'message' => $e->getMessage(),
'type' => $type ?? 'write',
], JSON_UNESCAPED_UNICODE);
}
}
// ========================================
// 서버 요구사항 검증 헬퍼 메서드
// ========================================
/**
* PHP 버전 검증
*/
private function checkPhpVersion(): array
{
$currentVersion = PHP_VERSION;
$minVersion = MIN_PHP_VERSION;
$passed = version_compare($currentVersion, $minVersion, '>=');
return [
'required' => true,
'min_version' => $minVersion,
'current_version' => $currentVersion,
'passed' => $passed,
'message' => $passed
? lang('success_php_version_detail', ['current' => $currentVersion, 'min' => $minVersion])
: lang('error_php_version_insufficient_detail', ['current' => $currentVersion, 'min' => $minVersion]),
];
}
/**
* PHP 확장 모듈 검증
*
* 필수 및 선택적 확장 모듈을 검증합니다.
* 선택적 모듈은 설치 여부만 표시하며 전체 검증 통과에 영향을 주지 않습니다.
*/
private function checkPhpExtensions(): array
{
$requiredExtensions = REQUIRED_EXTENSIONS;
$optionalExtensions = defined('OPTIONAL_EXTENSIONS') ? OPTIONAL_EXTENSIONS : [];
$installed = [];
$allRequiredPassed = true;
// 필수 확장 검증
foreach ($requiredExtensions as $extension) {
$isLoaded = extension_loaded($extension);
$installed[$extension] = [
'required' => true,
'installed' => $isLoaded,
];
if (! $isLoaded) {
$allRequiredPassed = false;
}
}
// 선택적 확장 검증 (설치 여부만 표시)
$optionalInstalled = [];
foreach ($optionalExtensions as $extension) {
$optionalInstalled[$extension] = [
'required' => false,
'installed' => extension_loaded($extension),
];
}
return [
'required' => $requiredExtensions,
'optional' => $optionalExtensions,
'installed' => $installed,
'optional_installed' => $optionalInstalled,
'all_required_passed' => $allRequiredPassed,
'message' => $allRequiredPassed
? lang('success_php_extensions')
: lang('error_php_extensions_missing'),
];
}
/**
* 디스크 공간 검증
*/
private function checkDiskSpace(): array
{
$minSpaceMb = MIN_DISK_SPACE_MB;
$freeSpaceBytes = @disk_free_space(BASE_PATH);
// disk_free_space() 실패 시
if ($freeSpaceBytes === false) {
return [
'required' => true,
'min_mb' => $minSpaceMb,
'current_mb' => 0,
'passed' => false,
'message' => lang('error_disk_space_unknown'),
];
}
$freeSpaceMb = round($freeSpaceBytes / 1024 / 1024, 2);
$passed = $freeSpaceMb >= $minSpaceMb;
return [
'required' => true,
'min_mb' => $minSpaceMb,
'current_mb' => $freeSpaceMb,
'passed' => $passed,
'message' => $passed
? lang('success_disk_space_detail', ['current' => $freeSpaceMb, 'min' => $minSpaceMb])
: lang('error_disk_space_insufficient_detail', ['current' => $freeSpaceMb, 'min' => $minSpaceMb]),
];
}
/**
* 디렉토리 권한 검증
*
* functions.php의 공통 함수를 사용하여 권한을 체크합니다.
*/
private function checkDirectoryPermissions(): array
{
// 공통 함수 호출
$check = checkDirectoryPermissions(REQUIRED_DIRECTORIES);
// API 응답 형식에 맞게 변환
$results = [];
foreach ($check['results'] as $dir => $result) {
$results[$dir] = [
'path' => $dir,
'full_path' => BASE_PATH.'/'.$dir,
'relative_path' => './'.$dir,
'exists' => $result['exists'],
'writable' => $result['writable'],
'permissions' => $result['permissions'],
'owner' => $result['owner'],
'group' => $result['group'],
'passed' => $result['passed'],
'error_type' => $result['error_type'],
'has_subdirectory_issues' => $result['has_subdirectory_issues'],
'failed_subdirectories' => $result['failed_subdirectories'],
];
}
return [
'required' => true,
'paths' => array_keys(REQUIRED_DIRECTORIES),
'results' => $results,
'required_permissions' => REQUIRED_DIRECTORY_PERMISSIONS_DISPLAY,
'web_server_group' => getWebServerGroup() ?? getWebServerUser() ?? 'www-data',
'web_server_user' => getWebServerUser(),
'all_passed' => $check['all_passed'],
'message' => $check['all_passed']
? lang('success_directories_writable')
: lang('error_directory_not_writable_detail', ['permissions' => REQUIRED_DIRECTORY_PERMISSIONS_DISPLAY]),
];
}
/**
* 필수 파일 존재 여부 검증
*
* .env 파일이 프로젝트 루트에 존재하는지 확인합니다.
*/
private function checkRequiredFiles(): array
{
$basePath = BASE_PATH;
$filePaths = [
'.env' => $basePath.'/.env',
];
$createCommands = [
'.env' => getEnvCopyCommand($basePath),
];
$files = [];
$allPassed = true;
$hasNotWritable = false;
foreach ($filePaths as $name => $fullPath) {
$exists = file_exists($fullPath);
$writable = $exists && is_writable($fullPath);
// 통과 조건: 존재 + 쓰기 가능
$passed = $exists && $writable;
if (! $passed) {
$allPassed = false;
}
// 에러 타입 결정
$errorType = null;
if (! $exists) {
$errorType = 'not_exists';
} elseif (! $writable) {
$errorType = 'not_writable';
$hasNotWritable = true;
}
$files[$name] = [
'exists' => $exists,
'writable' => $writable,
'passed' => $passed,
'error_type' => $errorType,
'command' => $createCommands[$name],
];
}
return [
'required' => true,
'files' => $files,
'all_passed' => $allPassed,
'has_not_writable' => $hasNotWritable,
'web_server_group' => getWebServerGroup() ?? getWebServerUser() ?? 'www-data',
'web_server_user' => getWebServerUser(),
'base_path' => $basePath,
'relative_base_path' => '.',
'message' => $allPassed
? lang('success_required_files')
: lang('error_required_files_missing'),
];
}
/**
* HTTPS 사용 여부 확인
*/
private function checkHttps(): array
{
$isHttps = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on';
// HTTP_X_FORWARDED_PROTO 헤더도 확인 (프록시 환경)
if (! $isHttps && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$isHttps = strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https';
}
return [
'required' => false, // HTTPS는 선택 사항
'enabled' => $isHttps,
'message' => $isHttps
? lang('https_enabled')
: lang('https_disabled'),
];
}
/**
* 필수 PHP 함수(exec, proc_open) 비활성화 여부 검증
*/
private function checkDisabledFunctions(): array
{
$requiredFunctions = ['exec', 'proc_open', 'shell_exec'];
$disabledStr = ini_get('disable_functions');
$disabledList = array_map('trim', explode(',', $disabledStr));
$disabled = [];
foreach ($requiredFunctions as $func) {
if (in_array($func, $disabledList, true)) {
$disabled[] = $func;
}
}
$passed = empty($disabled);
return [
'required' => true,
'checked_functions' => $requiredFunctions,
'disabled' => $disabled,
'passed' => $passed,
'message' => $passed
? lang('success_required_functions')
: lang('error_disabled_functions', ['functions' => implode(', ', $disabled)]),
];
}
/**
* PHP CLI 버전과 웹 PHP 버전 일치 여부 확인
*/
private function checkPhpCliVersion(): array
{
$webVersion = PHP_VERSION;
$cliVersion = null;
$cliPath = 'php';
// exec 사용 가능 여부 먼저 확인
$disabledStr = ini_get('disable_functions');
$disabledList = array_map('trim', explode(',', $disabledStr));
if (in_array('exec', $disabledList, true)) {
return [
'required' => false,
'web_version' => $webVersion,
'cli_version' => null,
'cli_path' => null,
'matched' => null,
'message' => lang('php_cli_version_check_skipped'),
];
}
$output = [];
$returnCode = -1;
exec('php --version 2>&1', $output, $returnCode);
if ($returnCode === 0 && !empty($output)) {
$outputStr = implode("\n", $output);
if (preg_match('/PHP\s+(\d+\.\d+\.\d+)/', $outputStr, $matches)) {
$cliVersion = $matches[1];
}
}
// 메이저.마이너 버전 비교 (패치 차이는 무시)
$webMajorMinor = implode('.', array_slice(explode('.', $webVersion), 0, 2));
$cliMajorMinor = $cliVersion ? implode('.', array_slice(explode('.', $cliVersion), 0, 2)) : null;
$matched = $cliMajorMinor !== null && $webMajorMinor === $cliMajorMinor;
return [
'required' => false,
'web_version' => $webVersion,
'cli_version' => $cliVersion,
'cli_path' => $cliPath,
'matched' => $matched,
'message' => $cliVersion === null
? lang('php_cli_version_unknown')
: ($matched
? lang('php_cli_version_matched', ['web' => $webVersion, 'cli' => $cliVersion])
: lang('php_cli_version_mismatch', ['web' => $webVersion, 'cli' => $cliVersion])),
];
}
/**
* GET ?action=detect-php
* 서버에서 사용 가능한 PHP 바이너리 자동 탐색
*/
private function detectPhpBinaries(): void
{
$commonPaths = [
'/usr/local/php84/bin/php',
'/usr/local/php83/bin/php',
'/usr/local/php82/bin/php',
'/usr/bin/php8.4',
'/usr/bin/php8.3',
'/usr/bin/php8.2',
'/usr/local/bin/php',
'/usr/bin/php',
];
$found = [];
$checkedPaths = [];
$minVersion = MIN_PHP_VERSION;
// PHP_BINARY 상수
if (defined('PHP_BINARY') && PHP_BINARY !== '' && !in_array(PHP_BINARY, $checkedPaths, true)) {
$checkedPaths[] = PHP_BINARY;
$result = $this->validatePhpPath(PHP_BINARY);
if ($result['valid']) {
$found[] = ['path' => PHP_BINARY, 'version' => $result['version']];
}
}
// 공통 경로 스캔
foreach ($commonPaths as $path) {
if (in_array($path, $checkedPaths, true)) {
continue;
}
$checkedPaths[] = $path;
if (!file_exists($path)) {
continue;
}
$result = $this->validatePhpPath($path);
if ($result['valid']) {
$found[] = ['path' => $path, 'version' => $result['version']];
}
}
// 시스템 PATH의 'php'
$defaultPhpAvailable = false;
if (!in_array('php', $checkedPaths, true)) {
$result = $this->validatePhpPath('php');
if ($result['valid']) {
$found[] = ['path' => 'php', 'version' => $result['version']];
$defaultPhpAvailable = true;
}
} else {
// 이미 체크된 경우 found 배열에서 확인
foreach ($found as $bin) {
if ($bin['path'] === 'php') {
$defaultPhpAvailable = true;
break;
}
}
}
// Composer 자동 감지 (감지된 PHP 중 첫 번째로 검증)
$phpForComposer = !empty($found) ? $found[0]['path'] : 'php';
$composerResult = $this->detectComposerBinary($phpForComposer);
echo json_encode([
'success' => !empty($found),
'binaries' => $found,
'default_php_available' => $defaultPhpAvailable,
'composer' => $composerResult,
'message' => empty($found) ? lang('no_php_detected') : lang('php_detected_count', ['count' => count($found)]),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
/**
* Composer 바이너리 자동 감지
*
* @param string $phpPath .phar 실행 시 사용할 PHP 경로
* @return array{found: bool, path: string|null, version: string|null}
*/
private function detectComposerBinary(string $phpPath = 'php'): array
{
// 1. 시스템 PATH의 composer
$result = $this->validateComposerPath('composer', $phpPath);
if ($result['valid']) {
return ['found' => true, 'path' => 'composer', 'version' => $result['version']];
}
// 2. 프로젝트 루트의 composer.phar
$pharPath = realpath(__DIR__ . '/../../..') . '/composer.phar';
if (file_exists($pharPath)) {
$result = $this->validateComposerPath($pharPath, $phpPath);
if ($result['valid']) {
return ['found' => true, 'path' => $pharPath, 'version' => $result['version']];
}
}
// 3. 현재 디렉토리(public/install/api)의 composer.phar
$localPhar = realpath(__DIR__) . '/composer.phar';
if (file_exists($localPhar)) {
$result = $this->validateComposerPath($localPhar, $phpPath);
if ($result['valid']) {
return ['found' => true, 'path' => $localPhar, 'version' => $result['version']];
}
}
return ['found' => false, 'path' => null, 'version' => null];
}
/**
* POST ?action=test-php-binary
* 지정된 PHP 바이너리 경로의 유효성 검증
*/
private function testPhpBinary(): void
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$this->error400('POST method required');
}
$input = json_decode(file_get_contents('php://input'), true);
$path = $input['path'] ?? 'php';
$result = $this->validatePhpPath($path);
echo json_encode([
'success' => $result['valid'],
'version' => $result['version'],
'message' => $result['message'],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
/**
* POST ?action=test-composer
* Composer 바이너리 경로의 유효성 검증
*/
private function testComposer(): void
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$this->error400('POST method required');
}
$input = json_decode(file_get_contents('php://input'), true);
$composerPath = trim($input['path'] ?? '');
$phpPath = trim($input['php_path'] ?? 'php');
$result = $this->validateComposerPath($composerPath, $phpPath);
echo json_encode([
'success' => $result['valid'],
'version' => $result['version'],
'message' => $result['message'],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
/**
* GET ?action=check-core-pending-path
* 코어 업데이트 _pending 경로 퍼미션/소유자 체크
*/
private function checkCorePendingPath(): void
{
$path = $_GET['path'] ?? '';
if (empty($path)) {
echo json_encode(['success' => false, 'message' => lang('error_path_required')], JSON_UNESCAPED_UNICODE);
return;
}
$absolutePath = str_starts_with($path, '/')
? $path
: BASE_PATH . '/' . $path;
if (!file_exists($absolutePath)) {
echo json_encode([
'success' => false,
'message' => lang('error_path_not_exists', ['path' => $path]),
], JSON_UNESCAPED_UNICODE);
return;
}
if (!is_dir($absolutePath)) {
echo json_encode([
'success' => false,
'message' => lang('error_core_pending_not_directory'),
], JSON_UNESCAPED_UNICODE);
return;
}
$writable = is_writable($absolutePath);
echo json_encode([
'success' => $writable,
'message' => $writable
? lang('success_core_pending_path')
: lang('error_core_pending_not_writable'),
], JSON_UNESCAPED_UNICODE);
}
/**
* PHP 바이너리 경로 유효성 검증 헬퍼
*
* @param string $path PHP 바이너리 경로
* @return array{valid: bool, version: string|null, message: string}
*/
private function validatePhpPath(string $path): array
{
if (empty($path)) {
return ['valid' => false, 'version' => null, 'message' => lang('error_php_path_empty')];
}
// file_exists 사전 체크 없이 실행 결과로 판단
$command = escapeshellarg($path) . ' --version 2>&1';
$output = [];
$returnCode = -1;
exec($command, $output, $returnCode);
if ($returnCode !== 0) {
return ['valid' => false, 'version' => null, 'message' => lang('error_php_exec_failed', ['path' => $path])];
}
$outputStr = implode("\n", $output);
if (preg_match('/PHP\s+(\d+\.\d+\.\d+)/', $outputStr, $matches)) {
$version = $matches[1];
if (version_compare($version, MIN_PHP_VERSION, '>=')) {
return [
'valid' => true,
'version' => $version,
'message' => lang('success_php_binary_version', ['path' => $path, 'version' => $version]),
];
}
return [
'valid' => false,
'version' => $version,
'message' => lang('error_php_version_too_low', ['path' => $path, 'version' => $version, 'min' => MIN_PHP_VERSION]),
];
}
return ['valid' => false, 'version' => null, 'message' => lang('error_php_version_parse_failed')];
}
/**
* Composer 바이너리 경로 유효성 검증 헬퍼
*
* @param string $composerPath Composer 바이너리 경로 (빈 문자열이면 시스템 'composer')
* @param string $phpPath PHP 바이너리 경로 (.phar 실행 시 사용)
* @return array{valid: bool, version: string|null, message: string}
*/
private function validateComposerPath(string $composerPath, string $phpPath = 'php'): array
{
// 빈 문자열이면 시스템 기본 composer 사용
$effectivePath = $composerPath ?: 'composer';
// 실행 명령어 구성
if (str_contains($effectivePath, ' ')) {
// 공백 포함 = 전체 실행 명령어 (예: "/usr/local/php84/bin/php composer.phar")
// escapeshellarg 없이 그대로 실행
$command = $effectivePath . ' --version 2>&1';
} elseif (str_ends_with($effectivePath, '.phar')) {
// .phar 파일 단독 경로 → PHP 바이너리와 결합
$command = escapeshellarg($phpPath) . ' ' . escapeshellarg($effectivePath) . ' --version 2>&1';
} else {
// composer 바이너리 경로
$command = escapeshellarg($effectivePath) . ' --version 2>&1';
}
$output = [];
$returnCode = -1;
exec($command, $output, $returnCode);
if ($returnCode !== 0) {
return ['valid' => false, 'version' => null, 'message' => lang('error_composer_exec_failed', ['path' => $effectivePath])];
}
$outputStr = implode("\n", $output);
if (preg_match('/Composer\s+(?:version\s+)?(\d+\.\d+\.\d+)/', $outputStr, $matches)) {
$version = $matches[1];
return [
'valid' => true,
'version' => $version,
'message' => lang('success_composer_version', ['path' => $effectivePath, 'version' => $version]),
];
}
return ['valid' => false, 'version' => null, 'message' => lang('error_composer_version_parse_failed')];
}
/**
* 모든 필수 요구사항 통과 여부 확인
*/
private function isAllRequiredPassed(array $requirements): bool
{
// PHP 버전 확인
if (! $requirements['php_version']['passed']) {
return false;
}
// PHP 확장 확인
if (! $requirements['php_extensions']['all_required_passed']) {
return false;
}
// 필수 함수 비활성화 확인
if (isset($requirements['disabled_functions']) && ! $requirements['disabled_functions']['passed']) {
return false;
}
// 디스크 공간 확인
if (! $requirements['disk_space']['passed']) {
return false;
}
// 디렉토리 권한 확인
if (! $requirements['directories']['all_passed']) {
return false;
}
// 필수 파일 확인
if (! $requirements['required_files']['all_passed']) {
return false;
}
// HTTPS는 선택 사항이므로 검증하지 않음
return true;
}
// ========================================
// 공통 에러 처리 메서드
// ========================================
/**
* 400 Bad Request 응답
*/
private function error400(string $message): void
{
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'Bad Request',
'message' => $message,
], JSON_UNESCAPED_UNICODE);
exit;
}
/**
* 500 Internal Server Error 응답
*/
private function error500(Throwable $e): void
{
// 에러 로깅
if (function_exists('logInstallationError')) {
logInstallationError('Validation API error', $e);
}
// 에러 응답
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Internal Server Error',
'message' => $e->getMessage(),
'details' => $e->getMessage(),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
exit;
}
}
// ========================================
// 실행 부분
// ========================================
// 필수 파일 로드 (config.php가 BASE_PATH를 정의함)
require_once __DIR__.'/../includes/config.php';
require_once __DIR__.'/../includes/session.php';
require_once __DIR__.'/../includes/functions.php';
// 다국어 로드
$currentLang = getCurrentLanguage();
$translations = loadTranslations($currentLang);
// API 인스턴스 생성 및 요청 처리
$api = new ValidationApi;
$api->handleRequest();
+45
View File
@@ -0,0 +1,45 @@
<?php
/**
* 그누보드7 웹 인스톨러 - 필수 파일 존재 여부 체크 API
*
* Step 5 진입 시 JavaScript에서 호출하여 .env 파일의
* 존재 여부 및 쓰기 가능 여부를 확인합니다.
*
* @package G7\Installer
*/
// 필수 파일 include
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';
// JSON 응답 헤더
header('Content-Type: application/json; charset=utf-8');
// GET 요청만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => 'Only GET requests are allowed.',
], JSON_UNESCAPED_UNICODE);
exit;
}
$envPath = BASE_PATH . '/.env';
// 소유자 === 웹 서버 사용자 여부 판별 (chgrp/sudo 생략 기준)
$webUser = getWebServerUser();
$baseOwner = function_exists('posix_getpwuid') && function_exists('posix_getuid')
? (posix_getpwuid(fileowner(BASE_PATH))['name'] ?? null)
: null;
$ownerIsWebUser = $webUser && $baseOwner && $webUser === $baseOwner;
echo json_encode([
'env_exists' => file_exists($envPath),
'env_writable' => file_exists($envPath) && is_writable($envPath),
'path' => BASE_PATH,
'relative_path' => '.',
'is_windows' => isWindows(),
'owner_is_web_user' => $ownerIsWebUser,
], JSON_UNESCAPED_UNICODE);
+196
View File
@@ -0,0 +1,196 @@
<?php
/**
* G7 인스톨러 설치 프로세스 API (SSE 방식)
*
* 설치 설정을 저장하고 상태를 'started'로 변경합니다.
* 실제 설치 작업은 install-worker.php가 SSE를 통해 실행합니다.
*
* @method POST
* @response JSON {"status": "started", "message": "설치가 시작되었습니다"}
*/
// 필수 파일 포함 (config.php가 BASE_PATH를 정의함)
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/session.php';
require_once __DIR__ . '/../includes/installer-state.php';
require_once __DIR__ . '/../includes/functions.php';
// 다국어 로드
$currentLang = getCurrentLanguage();
$translations = loadTranslations($currentLang);
// JSON 응답 헤더 설정
header('Content-Type: application/json; charset=UTF-8');
/**
* POST 요청인지 확인
*/
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => lang('error_method_not_allowed'),
], JSON_UNESCAPED_UNICODE);
exit;
}
try {
/**
* 세션에서 설정 정보 로드
* 세션이 비어있으면 (브라우저 재시작 등) state.json에서 로드
*/
$config = getSessionData('install_config');
// 세션이 비어있으면 state.json에서 로드
if (empty($config)) {
$state = getInstallationState();
$config = $state['config'] ?? [];
// state.json에도 config가 없으면 에러
if (empty($config)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => lang('error_config_not_in_session'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// state.json에서 로드한 config를 세션에도 저장 (이후 요청에서 사용)
setSessionData('install_config', $config);
}
/**
* 필수 설정 항목 검증
*/
$requiredFields = [
'db_write_host',
'db_write_database',
'db_write_username',
'app_name',
'app_url',
'admin_name',
'admin_email',
'admin_password',
];
$missingFields = [];
foreach ($requiredFields as $field) {
if (empty($config[$field])) {
$missingFields[] = $field;
}
}
if (!empty($missingFields)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => lang('error_required_fields_missing', ['fields' => implode(', ', $missingFields)]),
], JSON_UNESCAPED_UNICODE);
exit;
}
/**
* 필수 파일 존재 여부 사전 체크
*/
$missingRequiredFiles = [];
if (!file_exists(BASE_PATH . '/.env')) {
$missingRequiredFiles[] = '.env';
}
if (!empty($missingRequiredFiles)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => lang('error_env_not_found'),
'env_required' => true,
'missing_files' => $missingRequiredFiles,
'base_path' => BASE_PATH,
'is_windows' => isWindows(),
], JSON_UNESCAPED_UNICODE);
exit;
}
/**
* 현재 상태 가져오기
*/
$state = getInstallationState();
/**
* 상태 초기화
*
* 재시도/재개인 경우 (installation_status가 'running', 'failed' 또는 'aborted'인 경우):
* - completed_tasks는 유지 (이미 완료된 작업은 건너뛰기)
* - error는 초기화
* - 나머지는 running 상태로 재설정
*/
$isRetry = isset($state['installation_status']) &&
in_array($state['installation_status'], ['running', 'failed', 'aborted']);
$state['current_step'] = 5; // Step 5 = Installation (Step 4 = Extension Selection)
$state['installation_status'] = 'running';
$state['completed_tasks'] = $isRetry ? ($state['completed_tasks'] ?? []) : [];
$state['current_task'] = null;
$state['config'] = $config;
$state['error'] = null;
/**
* 로그 파일 초기화 (재시도가 아닌 경우에만)
*
* Step 4 -> Step 5로 새로 진입하는 경우 이전 로그를 초기화합니다.
* 재시도/재개인 경우에는 기존 로그를 유지합니다.
*/
if (!$isRetry) {
$logFilePath = BASE_PATH . '/storage/logs/installation.log';
if (file_exists($logFilePath)) {
@unlink($logFilePath);
}
}
/**
* 상태 저장
*/
$saved = saveInstallationState($state);
if (!$saved) {
throw new Exception(lang('state_save_failed'));
}
/**
* 로그 기록
*/
addLog(lang('log_installation_config_saved'));
/**
* 클라이언트에 즉시 응답 전송
*
* JavaScript에서 이 응답을 받은 후 install-worker.php로 SSE 연결을 시작합니다.
*/
http_response_code(200);
echo json_encode([
'success' => true,
'status' => 'started',
'message' => lang('success_installation_started'),
], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
/**
* 에러 처리
*/
// 에러 로깅
logInstallationError(lang('error_installation_start_failed'), $e);
// 상태를 failed로 변경
$state = getInstallationState();
$state['installation_status'] = 'failed';
$state['error'] = $e->getMessage();
saveInstallationState($state);
// 에러 응답
http_response_code(500);
echo json_encode([
'success' => false,
'message' => lang('error_installation_start_exception', ['error' => $e->getMessage()]),
], JSON_UNESCAPED_UNICODE);
}
File diff suppressed because it is too large. Load diff
+529
View File
@@ -0,0 +1,529 @@
<?php
/**
* G7 인스톨러 - 롤백 함수 모음
*
* 설치 중단 시 각 작업을 롤백하는 함수들을 제공합니다.
*/
/**
* 중단된 작업을 롤백합니다.
*
* @param string $taskId 롤백할 작업 식별자
* @param array $state 현재 설치 상태
* @return array ['success' => bool, 'message' => string] 롤백 결과
*/
function rollbackTask(string $taskId, array $state): array
{
try {
switch ($taskId) {
case 'db_migrate':
return rollbackDbMigrate();
case 'db_seed':
return rollbackDbSeed($state);
case 'complete_flag':
return rollbackCompleteFlag();
// 롤백 불필요한 작업들 (새로 생성하면 되는 것들)
case 'composer_check':
case 'composer_install':
case 'env_create':
case 'env_update':
case 'key_generate':
case 'cache_clear':
case 'create_settings_json':
return [
'success' => true,
'message' => lang('rollback_not_needed_recreatable'),
];
// 롤백 불필요한 확장 작업 (재설치/재활성화 시 덮어쓰기 가능)
case 'template_install':
case 'template_activate':
case 'module_install':
case 'module_activate':
case 'plugin_install':
case 'plugin_activate':
case 'user_template_install':
case 'user_template_activate':
return [
'success' => true,
'message' => lang('rollback_not_needed_overwritable'),
];
default:
return [
'success' => false,
'message' => lang('rollback_unknown_task', ['task' => $taskId])
];
}
} catch (Exception $e) {
addLog(lang('rollback_error', ['task' => $taskId, 'error' => $e->getMessage()]));
return [
'success' => false,
'message' => lang('rollback_exception', ['error' => $e->getMessage()])
];
}
}
/**
* 마이그레이션 롤백을 실행합니다 (migrate:rollback --force)
*
* @param string|null $logPrefix 로그 접두사 (null이면 lang('log_prefix_rollback') 사용)
* @return array ['success' => bool, 'message' => string, 'output' => array]
*/
function executeMigrateRollback(?string $logPrefix = null): array
{
$logPrefix = $logPrefix ?? lang('log_prefix_rollback');
try {
addLog("{$logPrefix} " . lang('rollback_migrate_start'));
$output = [];
$returnCode = 0;
$phpBin = escapeshellarg(function_exists('getPhpBinary') ? getPhpBinary() : 'php');
$command = sprintf(
'cd /d %s && %s artisan migrate:rollback --force 2>&1',
escapeshellarg(BASE_PATH),
$phpBin
);
exec($command, $output, $returnCode);
addLog("{$logPrefix} " . lang('rollback_migrate_result', ['result' => implode("\n", $output)]));
if ($returnCode === 0) {
return [
'success' => true,
'message' => lang('rollback_migrate_success'),
'output' => $output,
];
}
addLog("{$logPrefix} " . lang('rollback_migrate_failed_code', ['code' => $returnCode]));
return [
'success' => false,
'message' => lang('rollback_migrate_failed'),
'output' => $output,
];
} catch (Exception $e) {
return [
'success' => false,
'message' => lang('rollback_migrate_error', ['error' => $e->getMessage()]),
'output' => [],
];
}
}
/**
* db_migrate 작업 롤백: migrate:rollback 실행
*
* @return array ['success' => bool, 'message' => string, 'output' => array]
*/
function rollbackDbMigrate(): array
{
return executeMigrateRollback(lang('log_prefix_rollback'));
}
/**
* 시드 데이터 TRUNCATE를 실행합니다 (PDO 세션 내 FOREIGN_KEY_CHECKS 제어)
*
* @param array $config DB 연결 설정
* @param bool $force true: 무조건 TRUNCATE, false: 미완료 시에만 TRUNCATE
* @param string|null $logPrefix 로그 접두사 (null이면 lang('log_prefix_rollback') 사용)
* @return array ['success' => bool, 'message' => string]
*/
function executeSeedTruncate(array $config, bool $force = false, ?string $logPrefix = null): array
{
$logPrefix = $logPrefix ?? lang('log_prefix_rollback');
if (empty($config['db_write_host']) || empty($config['db_write_database'])) {
addLog("{$logPrefix} " . lang('rollback_seed_no_config'));
return ['success' => true, 'message' => lang('rollback_seed_no_config')];
}
$dsn = sprintf(
'mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4',
$config['db_write_host'],
$config['db_write_port'] ?? '3306',
$config['db_write_database']
);
try {
$pdo = new PDO($dsn, $config['db_write_username'], $config['db_write_password'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// 강제 모드가 아니면 완료 여부 확인
if (!$force) {
$stmt = $pdo->query("SHOW TABLES LIKE 'roles'");
if ($stmt->rowCount() > 0) {
$count = $pdo->query("SELECT COUNT(*) FROM roles")->fetchColumn();
if ($count > 0) {
addLog("{$logPrefix} " . lang('rollback_seed_already_done'));
return ['success' => true, 'message' => lang('rollback_seed_already_done')];
}
}
addLog("{$logPrefix} " . lang('rollback_seed_interrupted'));
} else {
addLog("{$logPrefix} " . lang('rollback_seed_force_truncate'));
}
$pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
$tables = ['users', 'roles', 'permissions', 'role_user', 'permission_role'];
foreach ($tables as $table) {
try {
$pdo->exec("TRUNCATE TABLE `{$table}`");
addLog("{$logPrefix} " . lang('rollback_table_truncated', ['table' => $table]));
} catch (PDOException $e) {
addLog("{$logPrefix} " . lang('rollback_table_truncate_skipped', ['table' => $table, 'error' => $e->getMessage()]));
}
}
$pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
return ['success' => true, 'message' => lang('rollback_seed_data_deleted')];
} catch (PDOException $e) {
if ($force) {
return ['success' => false, 'message' => lang('rollback_db_connection_failed', ['error' => $e->getMessage()])];
}
addLog("{$logPrefix} " . lang('rollback_db_connection_failed_skip'));
return ['success' => true, 'message' => lang('rollback_db_connection_failed_skip')];
}
}
/**
* db_seed 작업 롤백: 중단된 경우에만 TRUNCATE
*
* @param array $state 현재 설치 상태
* @return array ['success' => bool, 'message' => string]
*/
function rollbackDbSeed(array $state): array
{
try {
return executeSeedTruncate($state['config'] ?? [], false, lang('log_prefix_rollback'));
} catch (Exception $e) {
return ['success' => false, 'message' => lang('rollback_seed_error', ['error' => $e->getMessage()])];
}
}
/**
* db_migrate 작업 강제 롤백 (설정으로 돌아갈 때 사용)
*
* @return array ['success' => bool, 'message' => string, 'output' => array]
*/
function forceRollbackDbMigrate(): array
{
return executeMigrateRollback(lang('log_prefix_force_rollback'));
}
/**
* db_seed 작업 강제 롤백 (설정으로 돌아갈 때 사용)
*
* @param array $state 현재 설치 상태
* @return array ['success' => bool, 'message' => string]
*/
function forceRollbackDbSeed(array $state): array
{
try {
return executeSeedTruncate($state['config'] ?? [], true, lang('log_prefix_force_rollback'));
} catch (Exception $e) {
return ['success' => false, 'message' => lang('rollback_seed_error', ['error' => $e->getMessage()])];
}
}
/**
* complete_flag 작업 롤백: 설치 완료 플래그 제거
*/
function rollbackCompleteFlag(): array
{
try {
$envPath = BASE_PATH . '/.env';
$installedFlagPath = BASE_PATH . '/storage/app/g7_installed';
$results = [];
// .env에서 INSTALLER_COMPLETED 제거
if (file_exists($envPath)) {
$envContent = file_get_contents($envPath);
$envContent = preg_replace('/^INSTALLER_COMPLETED=.*$/m', '', $envContent);
$envContent = preg_replace("/\n\n+/", "\n\n", $envContent);
if (file_put_contents($envPath, $envContent) !== false) {
addLog(lang('rollback_env_flag_removed'));
$results[] = lang('rollback_env_flag_removed');
}
}
// g7_installed 파일 삭제
if (file_exists($installedFlagPath)) {
if (@unlink($installedFlagPath)) {
addLog(lang('rollback_installed_flag_removed'));
$results[] = lang('rollback_installed_flag_removed');
}
}
return [
'success' => true,
'message' => lang('rollback_complete_flag_removed', ['details' => implode(', ', $results)])
];
} catch (Exception $e) {
return [
'success' => false,
'message' => lang('rollback_complete_flag_error', ['error' => $e->getMessage()])
];
}
}
/**
* 디렉토리 내용을 삭제합니다.
*
* Git 추적 파일(.gitkeep 등)은 보존하고, 디렉토리 자체도 유지합니다.
* 이는 인스톨러가 프로젝트 구조에 필수적인 파일/디렉토리를
* 실수로 삭제하는 것을 방지합니다.
*
* @param string $dir 삭제할 디렉토리 경로
* @param bool $removeDir true이면 디렉토리 자체도 삭제 (기본: false, 내용만 삭제)
* @return bool 삭제 성공 여부
*/
function deleteDirectory(string $dir, bool $removeDir = false): bool
{
if (!is_dir($dir)) {
return false;
}
// 보존해야 할 파일 패턴 (Git 추적용 파일)
$preserveFiles = ['.gitkeep', '.gitignore'];
$items = array_diff(scandir($dir), ['.', '..']);
$hasPreservedFiles = false;
foreach ($items as $item) {
$path = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($path)) {
deleteDirectory($path, true);
} else {
// 보존 대상 파일은 건너뛰기
if (in_array($item, $preserveFiles, true)) {
$hasPreservedFiles = true;
continue;
}
@unlink($path);
}
}
// 보존 파일이 남아있거나 removeDir이 false이면 디렉토리 유지
if ($hasPreservedFiles || !$removeDir) {
return true;
}
return @rmdir($dir);
}
/**
* 현재 진행 중인 작업을 롤백합니다. (abort.php에서 사용)
*
* @param array $state 현재 설치 상태
* @return array ['success' => bool, 'message' => string, 'task' => string|null]
*/
function rollbackCurrentTask(array $state): array
{
$currentTask = $state['current_task'] ?? null;
if (!$currentTask) {
addLog(lang('rollback_no_current_task'));
return [
'success' => true,
'message' => lang('rollback_no_current_task'),
'task' => null,
];
}
if (in_array($currentTask, $state['completed_tasks'] ?? [])) {
addLog(lang('rollback_task_already_completed', ['task' => $currentTask]));
return [
'success' => true,
'message' => lang('rollback_task_already_completed', ['task' => $currentTask]),
'task' => $currentTask,
];
}
addLog(lang('rollback_current_task_start', ['task' => $currentTask]));
$rollbackResult = rollbackTask($currentTask, $state);
if ($rollbackResult['success']) {
addLog(lang('abort_rollback_success', ['message' => $rollbackResult['message']]));
return [
'success' => true,
'message' => lang('abort_rollback_success', ['message' => $rollbackResult['message']]),
'task' => $currentTask,
];
} else {
addLog(lang('abort_rollback_failed', ['message' => $rollbackResult['message']]));
return [
'success' => false,
'message' => lang('failed_rollback_failed', ['message' => $rollbackResult['message']]),
'task' => $currentTask,
];
}
}
/**
* 완료된 작업들을 역순으로 롤백합니다. (reset-state.php에서 사용)
*
* @param array $completedTasks 완료된 작업 목록
* @param array $rollbackableTasks 롤백 가능한 작업 목록
* @param array $state 현재 설치 상태
* @return array ['results' => array, 'errors' => array]
*/
function rollbackCompletedTasks(array $completedTasks, array $rollbackableTasks, array $state): array
{
$results = [];
$errors = [];
if (empty($completedTasks)) {
addLog(lang('rollback_no_completed_tasks'));
return ['results' => $results, 'errors' => $errors];
}
addLog(lang('rollback_checking_tasks'));
$tasksToRollback = array_reverse(
array_intersect($rollbackableTasks, $completedTasks)
);
if (empty($tasksToRollback)) {
addLog(lang('rollback_no_matching_tasks'));
return ['results' => $results, 'errors' => $errors];
}
addLog(lang('rollback_tasks_to_rollback', ['tasks' => implode(', ', $tasksToRollback)]));
foreach ($tasksToRollback as $taskId) {
addLog(lang('rollback_task_rolling_back', ['task' => $taskId]));
if ($taskId === 'db_migrate') {
$result = forceRollbackDbMigrate();
} elseif ($taskId === 'db_seed') {
$result = forceRollbackDbSeed($state);
} else {
$result = rollbackTask($taskId, $state);
}
if ($result['success']) {
$results[] = $taskId . ': ' . $result['message'];
addLog(lang('rollback_task_success', ['task' => $taskId]));
} else {
$errors[] = $taskId . ': ' . $result['message'];
addLog(lang('rollback_task_failed', ['task' => $taskId, 'error' => $result['message']]));
}
}
return ['results' => $results, 'errors' => $errors];
}
/**
* 실패한 작업에 대한 수동 명령어를 생성합니다.
*
* @param string $taskId 작업 ID
* @param string|null $target 대상 (확장 식별자)
* @return array 수동 명령어 배열
*/
function getManualCommands(string $taskId, ?string $target = null): array
{
$commands = [];
$php = getPhpBinary();
$composer = getComposerCommandForDisplay();
switch ($taskId) {
case 'composer_install':
$commands[] = "{$composer} install --no-interaction --prefer-dist --optimize-autoloader";
break;
case 'env_create':
$commands[] = getEnvCopyCommand();
break;
case 'key_generate':
$commands[] = "{$php} artisan key:generate";
break;
case 'db_migrate':
$commands[] = "{$php} artisan migrate --force";
break;
case 'db_seed':
$commands[] = "{$php} artisan db:seed --force";
break;
case 'template_install':
if ($target) {
$commands[] = "{$php} artisan template:install {$target}";
}
break;
case 'template_activate':
if ($target) {
$commands[] = "{$php} artisan template:activate {$target}";
}
break;
case 'module_install':
if ($target) {
$commands[] = "{$php} artisan module:install {$target}";
}
break;
case 'module_activate':
if ($target) {
$commands[] = "{$php} artisan module:activate {$target}";
}
break;
case 'plugin_install':
if ($target) {
$commands[] = "{$php} artisan plugin:install {$target}";
}
break;
case 'plugin_activate':
if ($target) {
$commands[] = "{$php} artisan plugin:activate {$target}";
}
break;
case 'user_template_install':
if ($target) {
$commands[] = "{$php} artisan template:install {$target}";
}
break;
case 'user_template_activate':
if ($target) {
$commands[] = "{$php} artisan template:activate {$target}";
}
break;
case 'create_settings_json':
$commands[] = '# ' . lang('manual_cmd_settings_json');
break;
case 'cache_clear':
$commands[] = "{$php} artisan optimize:clear";
break;
case 'complete_flag':
if (isWindows()) {
$commands[] = 'echo INSTALLER_COMPLETED=true >> .env';
$commands[] = 'type nul > storage\\app\\g7_installed';
} else {
$commands[] = 'echo "INSTALLER_COMPLETED=true" >> .env';
$commands[] = 'touch storage/app/g7_installed';
}
break;
}
return $commands;
}
+153
View File
@@ -0,0 +1,153 @@
<?php
/**
* G7 인스톨러 - 선택된 확장 기능 저장 API
*
* 사용자가 선택한 확장 기능 목록을 state.json에 저장합니다.
*
* @method POST
* @body {
* "admin_templates": ["sirsoft-admin_basic"],
* "user_templates": ["sirsoft-basic"],
* "modules": ["sirsoft-board", "sirsoft-ecommerce"],
* "plugins": ["sirsoft-verification"]
* }
*
* @response {
* "success": true,
* "message": "확장 기능 선택이 저장되었습니다."
* }
*/
// 기본 설정
header('Content-Type: application/json; charset=utf-8');
// 프로젝트 루트 경로
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3));
// 세션 및 설정 포함
require_once dirname(__DIR__) . '/includes/session.php';
require_once dirname(__DIR__) . '/includes/config.php';
require_once dirname(__DIR__) . '/includes/installer-state.php';
require_once dirname(__DIR__) . '/includes/functions.php';
// 다국어 로드
$currentLang = getCurrentLanguage();
$translations = loadTranslations($currentLang);
// POST 요청만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'error' => lang('api_method_not_allowed'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// 요청 본문 파싱
$input = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => lang('api_invalid_request'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// 필드 검증 및 기본값 설정
$adminTemplates = isset($input['admin_templates']) && is_array($input['admin_templates'])
? $input['admin_templates']
: [];
$userTemplates = isset($input['user_templates']) && is_array($input['user_templates'])
? $input['user_templates']
: [];
$modules = isset($input['modules']) && is_array($input['modules'])
? $input['modules']
: [];
$plugins = isset($input['plugins']) && is_array($input['plugins'])
? $input['plugins']
: [];
// 확장 이름 매핑 (identifier → {ko: '...', en: '...'})
$extensionNames = isset($input['extension_names']) && is_array($input['extension_names'])
? $input['extension_names']
: [];
// 관리자 템플릿은 최소 1개 필수
if (empty($adminTemplates)) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => lang('error_admin_template_required'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// 문자열 배열로 정리 (보안)
$adminTemplates = array_values(array_filter(array_map('strval', $adminTemplates)));
$userTemplates = array_values(array_filter(array_map('strval', $userTemplates)));
$modules = array_values(array_filter(array_map('strval', $modules)));
$plugins = array_values(array_filter(array_map('strval', $plugins)));
try {
// 현재 상태 가져오기
$state = getInstallationState();
// selected_extensions 업데이트
$state['selected_extensions'] = [
'admin_templates' => $adminTemplates,
'user_templates' => $userTemplates,
'modules' => $modules,
'plugins' => $plugins,
];
// 확장 이름 매핑 저장 (설치 시 표시용)
$state['extension_names'] = $extensionNames;
// Step 4 완료 표시
$state['step_status']['4'] = 'completed';
// 다음 스텝으로 이동
$state['current_step'] = 5;
// 세션도 동기화 (Step 5로 이동 허용)
$_SESSION['installer_current_step'] = 5;
// 상태 저장
$saved = saveInstallationState($state);
if (!$saved) {
throw new Exception(lang('state_save_failed'));
}
// 로그 기록
addLog(lang('log_extensions_selected', [
'admin' => count($adminTemplates),
'user' => count($userTemplates),
'modules' => count($modules),
'plugins' => count($plugins),
]));
// 성공 응답
echo json_encode([
'success' => true,
'message' => lang('log_extensions_saved'),
'data' => [
'selected_extensions' => $state['selected_extensions'],
'next_step' => 5,
],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage(),
], JSON_UNESCAPED_UNICODE);
}
+315
View File
@@ -0,0 +1,315 @@
<?php
/**
* G7 인스톨러 - 확장 기능 스캔 API
*
* _bundled 디렉토리에서 템플릿, 모듈, 플러그인을 스캔하여 설치 가능한 확장 목록을 반환합니다.
* 모든 확장의 메타데이터는 JSON 매니페스트 파일(template.json, module.json, plugin.json)에서 읽습니다.
*
* @response {
* "success": true,
* "data": {
* "admin_templates": [...],
* "user_templates": [...],
* "modules": [...],
* "plugins": [...]
* }
* }
*/
// 기본 설정
header('Content-Type: application/json; charset=utf-8');
// 프로젝트 루트 경로
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3));
// 세션 및 설정 포함 (Laravel autoload 없이 독립 실행)
// 참고: 이 API는 Laravel 부팅 없이 디렉토리 스캔만 수행
require_once dirname(__DIR__).'/includes/session.php';
require_once dirname(__DIR__).'/includes/config.php';
/**
* 템플릿 디렉토리 스캔
*
* _bundled 디렉토리에서 template.json을 읽어 템플릿 정보를 수집합니다.
*
* @return array ['admin' => [...], 'user' => [...]]
*/
function scanTemplates(): array
{
$templatesDir = BASE_PATH.'/templates/_bundled';
$result = [
'admin' => [],
'user' => [],
];
if (! is_dir($templatesDir)) {
return $result;
}
$dirs = scandir($templatesDir);
foreach ($dirs as $dir) {
if ($dir === '.' || $dir === '..') {
continue;
}
$templateJsonPath = $templatesDir.'/'.$dir.'/template.json';
if (! file_exists($templateJsonPath)) {
continue;
}
$content = @file_get_contents($templateJsonPath);
if ($content === false) {
continue;
}
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE || empty($data)) {
continue;
}
// 필수 필드 확인
$identifier = $data['identifier'] ?? $dir;
$name = $data['name'] ?? ['ko' => $dir, 'en' => $dir];
$version = $data['version'] ?? '1.0.0';
$description = $data['description'] ?? ['ko' => '', 'en' => ''];
$type = $data['type'] ?? 'user'; // admin 또는 user
$author = $data['author']['name'] ?? $data['vendor'] ?? null;
// dependencies 처리: 객체 형태면 모듈/플러그인 키를 배열로 변환
$dependencies = extractDependenciesFromJson($data);
$templateInfo = [
'identifier' => $identifier,
'name' => $name,
'version' => $version,
'description' => $description,
'type' => $type,
'dependencies' => $dependencies,
'author' => $author,
'directory' => $dir,
];
if ($type === 'admin') {
$result['admin'][] = $templateInfo;
} else {
$result['user'][] = $templateInfo;
}
}
return $result;
}
/**
* 모듈 디렉토리 스캔
*
* _bundled 디렉토리에서 module.json을 읽어 모듈 정보를 수집합니다.
*
* @return array 모듈 목록
*/
function scanModules(): array
{
$modulesDir = BASE_PATH.'/modules/_bundled';
$result = [];
if (! is_dir($modulesDir)) {
return $result;
}
$dirs = scandir($modulesDir);
foreach ($dirs as $dir) {
if ($dir === '.' || $dir === '..') {
continue;
}
// module.json 매니페스트에서 메타데이터 읽기
$moduleJsonPath = $modulesDir.'/'.$dir.'/module.json';
if (! file_exists($moduleJsonPath)) {
// module.json이 없으면 module.php만으로 식별 (역호환)
$modulePhpPath = $modulesDir.'/'.$dir.'/module.php';
if (! file_exists($modulePhpPath)) {
continue;
}
// JSON이 없는 경우 기본값으로 등록
$result[] = [
'identifier' => $dir,
'name' => ['ko' => $dir, 'en' => $dir],
'version' => '1.0.0',
'description' => ['ko' => '', 'en' => ''],
'dependencies' => [],
'author' => null,
'directory' => $dir,
];
continue;
}
$content = @file_get_contents($moduleJsonPath);
if ($content === false) {
continue;
}
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE || empty($data)) {
continue;
}
$dependencies = extractDependenciesFromJson($data);
$result[] = [
'identifier' => $data['identifier'] ?? $dir,
'name' => $data['name'] ?? ['ko' => $dir, 'en' => $dir],
'version' => $data['version'] ?? '1.0.0',
'description' => $data['description'] ?? ['ko' => '', 'en' => ''],
'dependencies' => $dependencies,
'author' => $data['vendor'] ?? null,
'directory' => $dir,
];
}
return $result;
}
/**
* 플러그인 디렉토리 스캔
*
* _bundled 디렉토리에서 plugin.json을 읽어 플러그인 정보를 수집합니다.
*
* @return array 플러그인 목록
*/
function scanPlugins(): array
{
$pluginsDir = BASE_PATH.'/plugins/_bundled';
$result = [];
if (! is_dir($pluginsDir)) {
return $result;
}
$dirs = scandir($pluginsDir);
foreach ($dirs as $dir) {
if ($dir === '.' || $dir === '..') {
continue;
}
// plugin.json 매니페스트에서 메타데이터 읽기
$pluginJsonPath = $pluginsDir.'/'.$dir.'/plugin.json';
if (! file_exists($pluginJsonPath)) {
// plugin.json이 없으면 plugin.php만으로 식별 (역호환)
$pluginPhpPath = $pluginsDir.'/'.$dir.'/plugin.php';
if (! file_exists($pluginPhpPath)) {
continue;
}
// JSON이 없는 경우 기본값으로 등록
$result[] = [
'identifier' => $dir,
'name' => ['ko' => $dir, 'en' => $dir],
'version' => '1.0.0',
'description' => ['ko' => '', 'en' => ''],
'dependencies' => [],
'author' => null,
'directory' => $dir,
];
continue;
}
$content = @file_get_contents($pluginJsonPath);
if ($content === false) {
continue;
}
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE || empty($data)) {
continue;
}
$dependencies = extractDependenciesFromJson($data);
$result[] = [
'identifier' => $data['identifier'] ?? $dir,
'name' => $data['name'] ?? ['ko' => $dir, 'en' => $dir],
'version' => $data['version'] ?? '1.0.0',
'description' => $data['description'] ?? ['ko' => '', 'en' => ''],
'dependencies' => $dependencies,
'author' => $data['vendor'] ?? null,
'directory' => $dir,
];
}
return $result;
}
/**
* JSON 매니페스트에서 의존성 배열 추출
*
* dependencies 구조:
* - 객체 형태: { "modules": {"sirsoft-ecommerce": ">=1.0.0"}, "plugins": {...} }
* - 배열 형태: ["module1", "module2"]
*
* @param array $data JSON 매니페스트 데이터
* @return array 의존성 identifier 목록
*/
function extractDependenciesFromJson(array $data): array
{
$rawDeps = $data['dependencies'] ?? [];
$dependencies = [];
if (is_array($rawDeps)) {
if (isset($rawDeps['modules']) || isset($rawDeps['plugins'])) {
// 객체 형태: { modules: {...}, plugins: {...} }
foreach (['modules', 'plugins'] as $depType) {
if (! empty($rawDeps[$depType]) && is_array($rawDeps[$depType])) {
$dependencies = array_merge($dependencies, array_keys($rawDeps[$depType]));
}
}
} else {
// 배열 형태: ['module1', 'module2']
$dependencies = array_values($rawDeps);
}
}
return $dependencies;
}
// ===== 메인 실행 =====
try {
// 템플릿 스캔
$templates = scanTemplates();
// 모듈 스캔
$modules = scanModules();
// 플러그인 스캔
$plugins = scanPlugins();
// Admin 템플릿 필수 검증
if (empty($templates['admin'])) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'no_admin_template',
'error_message' => 'Admin template is required but not found. Please ensure at least one admin template exists in the templates/_bundled directory.',
], JSON_UNESCAPED_UNICODE);
exit;
}
// 결과 반환
echo json_encode([
'success' => true,
'data' => [
'admin_templates' => $templates['admin'],
'user_templates' => $templates['user'],
'modules' => $modules,
'plugins' => $plugins,
],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage(),
], JSON_UNESCAPED_UNICODE);
}
+349
View File
@@ -0,0 +1,349 @@
<?php
/**
* G7 인스톨러 - 설치 상태 관리 통합 API
*
* 설치 상태 조회, 초기화, 중단 기능을 하나의 API로 통합
*
* 엔드포인트:
* - GET ?action=get : 현재 설치 상태 조회 (action 생략 시 기본값)
* - POST ?action=reset : 설치 상태 초기화 (Step 3로 이동)
* - POST ?action=abort : 설치 중단 (현재 작업만 롤백)
*/
/**
* 설치 상태 관리 API 클래스
*/
class StateManagementApi
{
/**
* 요청 처리 메인 메서드
*/
public function handleRequest(): void
{
// JSON 헤더 설정
$this->setJsonHeaders();
// HTTP 메서드 및 action 파라미터 확인
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? ($method === 'GET' ? 'get' : null);
try {
// action에 따라 적절한 메서드 호출
match ($action) {
'get' => $this->getState(),
'reset' => $this->resetState(),
'abort' => $this->abortInstallation(),
default => $this->error400('Invalid action parameter'),
};
} catch (Exception $e) {
$this->error500($e);
}
}
/**
* JSON 응답 헤더 설정
*/
private function setJsonHeaders(): void
{
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
}
/**
* GET ?action=get
* 현재 설치 상태 조회
*
* JavaScript 폴링(1초 간격)으로 호출되어 실시간 진행 상황을 업데이트합니다.
*/
private function getState(): void
{
// GET 메서드만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo json_encode([
'error' => 'Method Not Allowed',
'message' => lang('error_get_method_required'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// 현재 설치 상태 조회
$state = getInstallationState();
// installation_status 값을 status로 매핑
$status = 'pending';
if (isset($state['installation_status'])) {
switch ($state['installation_status']) {
case 'not_started':
case 'ready': // ready도 pending으로 매핑 (설치 대기 상태)
$status = 'pending';
break;
case 'running':
$status = 'running';
break;
case 'completed':
$status = 'completed';
break;
case 'failed':
$status = 'failed';
break;
case 'aborted':
$status = 'aborted';
break;
default:
$status = $state['installation_status'];
}
}
// 로그 파일에서 로그 읽기
$logs = getInstallationLogs();
// API 응답 형식으로 변환
$response = [
'status' => $status,
'current_step' => $state['current_step'] ?? 0,
'current_task' => $state['current_task'] ?? null,
// current_task_name은 제거 (프론트엔드에서 task ID로 번역)
'completed_tasks' => $state['completed_tasks'] ?? [],
'logs' => $logs,
'error' => $state['error'] ?? null,
'last_updated' => $state['last_updated'] ?? null,
// 실패 정보 (새로고침 후에도 표시용)
'failed_task' => $state['failed_task'] ?? null,
// failed_task_name은 제거 (프론트엔드에서 task ID로 번역)
'error_message_key' => $state['error_message_key'] ?? null,
'error_detail' => $state['error_detail'] ?? null,
'rollback_failure' => $state['rollback_failure'] ?? null,
'manual_commands' => $state['manual_commands'] ?? null,
];
// JSON 응답 반환
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
/**
* POST ?action=reset
* 설치 상태 초기화 및 적절한 Step으로 이동
*
* 설치 상태를 초기화하여 설정 페이지로 돌아갈 수 있도록 합니다.
* DB 롤백은 수행하지 않습니다 (사용자가 수동으로 DB 정리 필요).
* (마이그레이션 실패 시 자동 롤백은 install-worker.php에서 처리)
*/
private function resetState(): void
{
// POST 메서드만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => 'Only POST method is allowed',
], JSON_UNESCAPED_UNICODE);
exit;
}
// 현재 상태 조회
$state = getInstallationState();
// 항상 Step 4 (확장 선택)로 이동
$targetStep = 4;
addLog(lang('state_reset_requested'));
addLog(lang('state_reset_db_notice'));
// 상태 초기화 (DB 롤백 없이)
$state['current_step'] = $targetStep;
$_SESSION['installer_current_step'] = $targetStep;
$state['step_status'][$targetStep] = 'pending';
$state['installation_status'] = 'not_started';
$state['completed_tasks'] = [];
$state['current_task'] = null;
$state['error'] = null;
$state['failed_task'] = null;
$state['failed_task_target'] = null;
$state['error_message_key'] = null;
$state['error_detail'] = null;
$state['rollback_failure'] = null;
$state['manual_commands'] = null;
$state['last_updated'] = gmdate('Y-m-d\TH:i:s\Z');
// 상태 저장
$saved = saveInstallationState($state);
if (!$saved) {
throw new Exception(lang('state_save_failed'));
}
addLog(lang('state_reset_completed', ['step' => $targetStep]));
// 성공 응답
http_response_code(200);
echo json_encode([
'success' => true,
'message' => lang('state_reset_completed', ['step' => $targetStep]),
'target_step' => $targetStep,
], JSON_UNESCAPED_UNICODE);
}
/**
* POST ?action=abort
* 설치 중단 (현재 작업만 롤백)
*
* 사용자가 명시적으로 설치 중단 버튼을 클릭했을 때 호출됩니다.
* 현재 진행 중인 작업만 롤백하고, 완료된 작업은 유지합니다.
*/
private function abortInstallation(): void
{
// POST 메서드만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => lang('api_method_not_allowed'),
]);
exit;
}
addLog(lang('abort_api_requested'));
// 설치 상태 가져오기
$state = getInstallationState();
// 디버그: 현재 state 상태 로깅
addLog(lang('abort_api_current_status', ['status' => $state['installation_status'] ?? 'null']));
addLog(lang('abort_api_current_task', ['task' => $state['current_task'] ?? 'null']));
addLog(lang('abort_api_completed_count', ['count' => count($state['completed_tasks'] ?? [])]));
// 설치가 이미 완료된 경우
if (isset($state['installation_status']) && $state['installation_status'] === 'completed') {
addLog(lang('abort_api_already_completed'));
echo json_encode([
'success' => false,
'message' => lang('abort_api_already_completed'),
]);
exit;
}
// 이미 중단된 경우 - 멱등성 보장 (재진입 시 400 에러 방지)
if (isset($state['installation_status']) && $state['installation_status'] === 'aborted') {
addLog(lang('abort_api_already_aborted'));
echo json_encode([
'success' => true,
'message' => lang('abort_api_already_aborted'),
]);
exit;
}
// 설치가 진행 중이 아닌 경우
if (! isset($state['installation_status']) || $state['installation_status'] !== 'running') {
addLog(lang('abort_api_not_running', ['status' => $state['installation_status'] ?? 'null']));
echo json_encode([
'success' => false,
'message' => lang('abort_api_not_running', ['status' => $state['installation_status'] ?? 'null']),
]);
exit;
}
addLog(lang('abort_user_requested'));
// 현재 진행 중인 작업만 롤백 (완료된 작업은 유지)
// 결과는 rollbackCurrentTask()에서 로깅됨
$rollbackResult = rollbackCurrentTask($state);
// 설치 상태를 'aborted'로 변경
addLog(lang('abort_api_status_change'));
$state['installation_status'] = 'aborted';
// current_step은 5를 유지 (중단된 화면을 보여주기 위해 - Step 5 = Installation)
$state['current_task'] = null;
// completed_tasks는 유지 (이미 완료된 작업은 롤백하지 않음)
$state['aborted_at'] = date('Y-m-d H:i:s');
$state['abort_reason'] = 'User requested';
// 롤백 실패 정보 저장 (새로고침 후에도 표시용)
if (isset($rollbackResult['success']) && !$rollbackResult['success']) {
$state['rollback_failure'] = [
'task' => $rollbackResult['task'] ?? null,
'message' => $rollbackResult['message'] ?? null,
'message_key' => 'failed_rollback_manual_cleanup',
'detail_key' => 'failed_rollback_manual_cleanup_detail',
];
}
// 세션도 Step 5를 유지 (중단 화면 표시)
$saveResult = saveInstallationState($state);
addLog(lang('abort_api_save_result', ['result' => $saveResult ? 'success' : 'failed']));
// 저장 후 실제 state.json 확인
$verifyState = getInstallationState();
addLog(lang('abort_api_verify_status', ['status' => $verifyState['installation_status'] ?? 'null']));
addLog(lang('abort_installation_stopped'));
// 성공 응답 (리다이렉트 없음 - 현재 Step 5 유지)
echo json_encode([
'success' => true,
'message' => lang('abort_installation_stopped'),
]);
}
/**
* 400 Bad Request 응답
*/
private function error400(string $message): void
{
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'Bad Request',
'message' => $message,
], JSON_UNESCAPED_UNICODE);
exit;
}
/**
* 500 Internal Server Error 응답
*/
private function error500(Exception $e): void
{
// 에러 로깅
if (function_exists('logInstallationError')) {
logInstallationError(lang('error_state_management'), $e);
} elseif (function_exists('addLog')) {
addLog(lang('error_log_prefix', ['error' => $e->getMessage()]));
}
// 에러 응답
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Internal Server Error',
'message' => $e->getMessage(),
], JSON_UNESCAPED_UNICODE);
exit;
}
}
// ========================================
// 실행 부분
// ========================================
// 필수 파일 로드 (config.php가 BASE_PATH를 정의함)
require_once __DIR__.'/../includes/config.php';
require_once __DIR__.'/../includes/session.php';
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/installer-state.php';
// 롤백 함수 로드 (reset, abort 액션에서 필요)
require_once __DIR__.'/rollback-functions.php';
// 다국어 로드
$currentLang = getCurrentLanguage();
$translations = loadTranslations($currentLang);
// API 인스턴스 생성 및 요청 처리
$api = new StateManagementApi;
$api->handleRequest();
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+168
View File
@@ -0,0 +1,168 @@
<?php
/**
* 그누보드7 웹 인스톨러 설정 파일
*
* 인스톨러의 기본 상수와 설정을 정의합니다.
*
* @package G7\Installer
*/
// 프로젝트 루트 경로 (public/install/includes에서 3단계 상위)
if (!defined('BASE_PATH')) {
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3));
}
// 인스톨러 기본 URL
$installerPath = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
// install이 없으면 추가
if (substr($installerPath, -8) !== '/install') {
$installerPath .= '/install';
}
define('INSTALLER_BASE_URL', $installerPath);
// 인스톨러 버전
define('INSTALLER_VERSION', '1.0.0');
// 소프트웨어 최초 출시 연도 (저작권 표시용)
define('APP_RELEASE_YEAR', '2026');
// 최소 PHP 버전
define('MIN_PHP_VERSION', '8.2.0');
// 필수 PHP 모듈
define('REQUIRED_EXTENSIONS', [
'pdo',
'mbstring',
'openssl',
'tokenizer',
'xml',
'ctype',
'json',
'fileinfo',
'curl',
'dom',
'filter',
'hash',
'pcre',
'session',
]);
// 선택적 PHP 모듈 (설치를 권장하지만 필수는 아님)
define('OPTIONAL_EXTENSIONS', [
'zlib', // gzip 압축 지원 (응답 압축에 사용)
'gd', // 이미지 처리
'imagick', // 고급 이미지 처리
'redis', // Redis 캐시 지원
'intl', // 국제화 지원
]);
// 최소 디스크 공간 (MB)
define('MIN_DISK_SPACE_MB', 500);
// 디렉토리 권한 설정 (8진수)
// chown + chmod 모델: 소유자(www-data) rwx, 그룹(www-data) rwx, 기타 ---
define('REQUIRED_DIRECTORY_PERMISSIONS', 0770);
// 권한 표시용 문자열 (사용자에게 보여줄 형식)
define('REQUIRED_DIRECTORY_PERMISSIONS_DISPLAY', '770');
// 권한 검증이 필요한 디렉토리 목록
// 값이 true인 경우 하위 디렉토리까지 재귀적으로 체크
define('REQUIRED_DIRECTORIES', [
'storage' => true,
'bootstrap/cache' => false,
'vendor' => false,
'modules' => false,
'modules/_pending' => false,
'plugins' => false,
'plugins/_pending' => false,
'templates' => false,
'templates/_pending' => false,
'storage/app/core_pending' => false, // 코어 업데이트 _pending (기본값, 커스텀 경로는 Step 3에서 설정)
]);
// 인스톨러 기본 설정값
define('DEFAULT_INSTALL_CONFIG', [
// Write DB 설정
'db_write_host' => 'localhost',
'db_write_port' => '3306',
'db_write_database' => '',
'db_write_username' => '',
'db_write_password' => '',
'db_prefix' => 'g7_',
// Read DB 설정
'use_read_db' => false,
'db_read_host' => 'localhost',
'db_read_port' => '3306',
'db_read_database' => '',
'db_read_username' => '',
'db_read_password' => '',
// 사이트 설정
'app_name' => '그누보드7',
'app_env' => 'production',
// 관리자 계정 설정
'admin_name' => '관리자',
'admin_email' => '',
'admin_password' => '',
'admin_language' => 'ko',
// 코어 업데이트 설정
'core_update_pending_path' => '', // 빈 값 = 기본값(storage/app/core_pending) 사용
'core_update_github_url' => 'https://github.com/gnuboard/g7',
'core_update_github_token' => '', // GitHub Personal Access Token (프라이빗 저장소용)
// PHP CLI / Composer 경로 설정
'php_binary' => 'php', // PHP CLI 바이너리 경로 (예: /usr/local/php82/bin/php)
'composer_binary' => '', // Composer 바이너리 경로 (빈 값 = 시스템 PATH 사용)
]);
// 설치 단계별 파일 매핑
// Step 5 (installation)에서 완료/실패/중단 화면까지 모두 처리
define('STEP_FILE_MAP', [
0 => 'welcome',
1 => 'license',
2 => 'requirements',
3 => 'configuration',
4 => 'extension-selection',
5 => 'installation',
]);
// 인스톨러 기본 상태 정의
define('DEFAULT_INSTALLATION_STATE', [
'current_step' => 0,
'step_status' => [
'0' => 'pending',
'1' => 'pending',
'2' => 'pending',
'3' => 'pending',
'4' => 'pending',
'5' => 'pending',
],
'completed_tasks' => [],
'current_task' => null,
'current_task_name' => null,
'installation_status' => 'not_started',
'config' => [],
'selected_extensions' => [
'admin_templates' => [],
'user_templates' => [],
'modules' => [],
'plugins' => [],
],
'extension_names' => [], // 확장 이름 매핑 (identifier → {ko: '...', en: '...'})
]);
// 지원 언어 목록 (언어 추가 시 이 한 곳만 수정)
define('SUPPORTED_LANGUAGES', [
'ko' => '한국어 (Korean)',
'en' => 'English',
]);
// 설치 완료 후 인스톨러 파일 삭제 여부
define('DELETE_INSTALLER_AFTER_COMPLETE', true);
File diff suppressed because it is too large. Load diff
+354
View File
@@ -0,0 +1,354 @@
<?php
/**
* G7 인스톨러 상태 관리 시스템
*
* 설치 진행 상태를 storage/installer-state.json에 저장하고 조회합니다.
*/
if (!defined('BASE_PATH')) {
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3)); // public/install/includes에서 프로젝트 루트로
}
define('STATE_PATH', BASE_PATH . '/storage/installer-state.json');
define('INSTALLER_DIR', BASE_PATH . '/storage/installer');
/**
* 설치 상태 조회
*
* @return array 설치 상태 배열
*/
function getInstallationState(): array
{
// 기본 상태 가져오기 (config.php에서 정의)
$defaultState = DEFAULT_INSTALLATION_STATE;
// 런타임 타임스탬프 추가
$defaultState['last_updated'] = date('Y-m-d\TH:i:s\Z');
// 파일 상태 캐시 초기화 (다른 프로세스의 변경 감지를 위해)
clearstatcache(true, STATE_PATH);
// state.json 파일이 없으면 기본 상태 반환
if (!file_exists(STATE_PATH)) {
return $defaultState;
}
// 파일 읽기 권한 체크
if (!is_readable(STATE_PATH)) {
error_log("State file is not readable: " . STATE_PATH);
return $defaultState;
}
// state.json 파일 읽기
$content = @file_get_contents(STATE_PATH);
// 파일 읽기 실패 시 기본 상태 반환
if ($content === false) {
error_log("Failed to read state file: " . STATE_PATH);
return $defaultState;
}
$state = json_decode($content, true);
// JSON 파싱 실패 시 기본 상태 반환 (재귀 호출 제거 - 무한 루프 방지)
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Failed to parse state file JSON: " . json_last_error_msg());
return $defaultState;
}
return $state;
}
/**
* 설치 상태 저장
*
* @param array $state 저장할 상태 배열
* @return bool 저장 성공 여부
*/
function saveInstallationState(array $state): bool
{
// storage 디렉토리 존재 여부 확인 (생성하지 않음)
$storageDir = BASE_PATH . '/storage';
if (!is_dir($storageDir)) {
error_log("Storage directory does not exist: {$storageDir}");
return false;
}
// 디렉토리 쓰기 권한 확인
if (!is_writable($storageDir)) {
error_log("Storage directory is not writable: {$storageDir}");
return false;
}
// last_updated 타임스탬프 업데이트
$state['last_updated'] = date('Y-m-d\TH:i:s\Z');
// JSON 형식으로 저장
$content = json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
// 파일 쓰기
$result = @file_put_contents(STATE_PATH, $content);
if ($result === false) {
error_log("Failed to write state file: " . STATE_PATH);
return false;
}
// 파일 권한 설정
@chmod(STATE_PATH, 0664);
return true;
}
/**
* 설치 완료 여부 확인
*
* @return bool 설치 완료 여부
*/
function isInstallationCompleted(): bool
{
$state = getInstallationState();
// installation_status가 completed인지 확인
if (isset($state['installation_status']) && $state['installation_status'] === 'completed') {
return true;
}
// 또는 current_step이 5(완료 단계)이고 step_status[5]가 completed인지 확인
if (isset($state['current_step']) && $state['current_step'] >= 5) {
if (isset($state['step_status']['5']) && $state['step_status']['5'] === 'completed') {
return true;
}
}
// g7_installed 파일 존재 여부 확인 (추가 안전장치)
$installedFlagPath = BASE_PATH . '/storage/app/g7_installed';
if (file_exists($installedFlagPath)) {
return true;
}
// .env 파일의 INSTALLER_COMPLETED 플래그 확인
$envPath = BASE_PATH . '/.env';
if (file_exists($envPath)) {
$envContent = file_get_contents($envPath);
if (strpos($envContent, 'INSTALLER_COMPLETED=true') !== false) {
return true;
}
}
return false;
}
/**
* 특정 작업을 완료로 표시
*
* @param string $task 작업 식별자
* @return bool 업데이트 성공 여부
*/
function markTaskCompleted(string $task): bool
{
$state = getInstallationState();
// completed_tasks 배열에 추가 (중복 방지)
if (!in_array($task, $state['completed_tasks'])) {
$state['completed_tasks'][] = $task;
}
// 현재 작업이 완료된 작업과 같으면 초기화
if ($state['current_task'] === $task) {
$state['current_task'] = null;
$state['current_task_name'] = null;
}
return saveInstallationState($state);
}
/**
* 특정 작업을 완료 목록에서 제거
*
* @param string $task 작업 식별자
* @return bool 업데이트 성공 여부
*/
function removeTaskCompleted(string $task): bool
{
$state = getInstallationState();
$state['completed_tasks'] = array_values(
array_filter($state['completed_tasks'], fn($t) => $t !== $task)
);
return saveInstallationState($state);
}
/**
* 현재 진행 중인 작업 업데이트
*
* @param string $task 작업 식별자
* @return bool 업데이트 성공 여부
*/
function updateCurrentTask(string $task): bool
{
$state = getInstallationState();
$state['current_task'] = $task;
// current_task_name은 저장하지 않음 (프론트엔드에서 task ID로 번역)
return saveInstallationState($state);
}
/**
* 설치 로그 추가 (별도 파일에 기록)
*
* 페이지 새로고침/재시작 시 로그가 즉시 표시되도록
* fflush() + clearstatcache()를 적용합니다.
*
* @param string $message 로그 메시지
* @return bool 저장 성공 여부
*/
function addLog(string $message): bool
{
$logDir = BASE_PATH . '/storage/logs';
$logFile = $logDir . '/installation.log';
// 로그 디렉토리 확인 및 생성 시도
if (!is_dir($logDir)) {
$created = @mkdir($logDir, 0775, true);
if (!$created) {
error_log("Failed to create log directory: {$logDir} (storage 권한 확인 필요)");
return false;
}
}
// 로그 디렉토리 쓰기 권한 확인
if (!is_writable($logDir)) {
error_log("Log directory is not writable: {$logDir}");
return false;
}
// Windows에서 CP949 인코딩된 메시지를 UTF-8로 변환
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$encoding = mb_detect_encoding($message, ['UTF-8', 'EUC-KR', 'CP949'], true);
if ($encoding && $encoding !== 'UTF-8') {
$message = mb_convert_encoding($message, 'UTF-8', $encoding);
}
}
// 타임스탬프와 함께 로그 작성
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[{$timestamp}] {$message}\n";
// 파일 캐시 초기화 (최신 상태 확인)
clearstatcache(true, $logFile);
// 파일이 없거나 빈 파일이면 UTF-8 BOM 추가 (Windows 텍스트 편집기 호환성)
$isNewFile = !file_exists($logFile) || filesize($logFile) === 0;
if ($isNewFile) {
$utf8Bom = "\xEF\xBB\xBF";
$logEntry = $utf8Bom . $logEntry;
}
// 파일 핸들 열기 (append 모드)
$handle = @fopen($logFile, 'a');
if ($handle === false) {
error_log("Failed to open log file: {$logFile}");
return false;
}
// 배타적 잠금
flock($handle, LOCK_EX);
// 쓰기
$result = fwrite($handle, $logEntry);
// 버퍼 플러시 (즉시 디스크에 기록)
fflush($handle);
// 잠금 해제 및 닫기
flock($handle, LOCK_UN);
fclose($handle);
// Windows 파일 캐시 초기화 (최신 데이터 읽기 보장)
clearstatcache(true, $logFile);
if ($result === false) {
error_log("Failed to write log file: {$logFile}");
return false;
}
return true;
}
/**
* 설치 로그 조회 (파일에서 읽기)
*
* 페이지 새로고침 시 최신 로그를 즉시 표시하기 위해
* clearstatcache()를 적용합니다.
*
* @return array 로그 배열 [{timestamp, message}, ...]
*/
function getInstallationLogs(): array
{
$logFile = BASE_PATH . '/storage/logs/installation.log';
// 파일 캐시 초기화 (최신 데이터 읽기 보장)
clearstatcache(true, $logFile);
// 로그 파일이 없으면 빈 배열 반환
if (!file_exists($logFile)) {
return [];
}
// 로그 파일 읽기
$content = @file_get_contents($logFile);
if ($content === false) {
return [];
}
// 각 라인을 파싱
$lines = explode("\n", trim($content));
$logs = [];
foreach ($lines as $line) {
if (empty($line)) {
continue;
}
// [timestamp] message 형식 파싱
if (preg_match('/^\[(.+?)\] (.+)$/', $line, $matches)) {
$logs[] = [
'timestamp' => $matches[1],
'message' => $matches[2],
];
} else {
// 형식이 맞지 않으면 전체를 메시지로
$logs[] = [
'timestamp' => date('Y-m-d H:i:s'),
'message' => $line,
];
}
}
return $logs;
}
/**
* 마지막 완료된 단계 조회
*
* @return int 마지막 완료된 단계 번호 (0-5)
*/
function getLastCompletedStep(): int
{
$state = getInstallationState();
// step_status를 역순으로 확인
for ($step = 5; $step >= 0; $step--) {
$stepKey = (string)$step;
if (isset($state['step_status'][$stepKey]) && $state['step_status'][$stepKey] === 'completed') {
return $step;
}
}
// 완료된 단계가 없으면 -1 반환
return -1;
}
+241
View File
@@ -0,0 +1,241 @@
<?php
/**
* 그누보드7 웹 인스톨러 요청 처리 핸들러
*
* 모든 POST 요청 및 비즈니스 로직을 처리합니다.
*
* @package G7\Installer
*/
/**
* 설치 흐름 검증 및 리다이렉트
*
* @param int $currentStep 현재 단계
* @param array $state 설치 상태
*/
function validateInstallationFlow(int $currentStep, array $state): void
{
// 설치 완료 시 홈으로 리다이렉트
if (isInstallationCompleted()) {
$translations = loadTranslations(getCurrentLanguage());
showInstallationCompletedAlert();
}
// 설치 진행 중 체크 (Step 5 제외 - Installation 화면)
if (isInstallationRunning() && $currentStep !== 5) {
showInstallationRunningAlert();
}
// 상태 파일의 last_completed_step 가져오기
$lastCompletedStep = getLastCompletedStep();
// 허용된 최대 단계 계산 (마지막 완료 단계 + 1)
$allowedMaxStep = $lastCompletedStep + 1;
// 현재 단계가 허용된 범위를 벗어나면 알림 후 올바른 단계로 리다이렉트
if ($currentStep > $allowedMaxStep) {
showInvalidStepAccessAlert($allowedMaxStep);
}
}
/**
* 잘못된 단계 접근 시 알림 표시
*
* @param int $correctStep 올바른 단계 번호
*/
function showInvalidStepAccessAlert(int $correctStep): void
{
global $translations;
// 번역이 로드되지 않은 경우 로드
if (!isset($translations)) {
$translations = loadTranslations(getCurrentLanguage());
}
// 세션에 올바른 단계 설정
$_SESSION['installer_current_step'] = $correctStep;
showAlertAndRedirect(
lang('error_invalid_step_access'),
lang('error_invalid_step_access_message'),
INSTALLER_BASE_URL . '/'
);
}
/**
* Step 0 POST 처리 (환영 화면)
*/
function handleStep0Post(): void
{
if (isset($_POST['language'])) {
handleLanguageChange($_POST['language']);
}
// 다음 버튼 클릭 시 (언어 선택 변경이 아닌 경우)
if (!isset($_POST['language_change_only'])) {
unset($_SESSION['license_agreed']);
updateStepStatus(0, 1);
redirectToStep(1);
}
redirectToStep(0);
}
/**
* Step 1 POST 처리 (라이선스 동의)
*
* @param string $currentLang 현재 언어
* @param string|null &$error 에러 메시지 (참조)
*/
function handleStep1Post(string $currentLang, ?string &$error = null): void
{
$translations = loadTranslations($currentLang);
if (!isset($_POST['agree']) || $_POST['agree'] !== '1') {
$error = lang('must_agree');
} else {
$_SESSION['license_agreed'] = true;
updateStepStatus(1, 2);
redirectToStep(2);
}
}
/**
* Step 2 POST 처리 (요구사항 검증)
*/
function handleStep2Post(): void
{
if (isset($_POST['proceed'])) {
updateStepStatus(2, 3);
redirectToStep(3);
}
}
/**
* Step 3 POST 처리 (데이터베이스 및 사이트 설정)
*
* @param string $currentLang 현재 언어
* @param array &$formData 폼 데이터 (참조)
* @param array &$errors 에러 배열 (참조)
*/
function handleStep3Post(string $currentLang, array &$formData, array &$errors): void
{
$translations = loadTranslations($currentLang);
$formData = array_merge($formData, $_POST);
$formData['use_read_db'] = isset($_POST['use_read_db']) ? true : false;
// Write DB 검증
if (empty($formData['db_write_host'])) {
$errors['db_write_host'] = lang('error_db_host_required');
}
if (empty($formData['db_write_database'])) {
$errors['db_write_database'] = lang('error_db_name_required');
}
// Read DB 검증 (사용하는 경우)
if (!empty($formData['use_read_db'])) {
if (empty($formData['db_read_host'])) {
$errors['db_read_host'] = lang('error_db_host_required');
}
if (empty($formData['db_read_database'])) {
$errors['db_read_database'] = lang('error_db_name_required');
}
}
// 관리자 정보 검증
if (empty($formData['admin_email']) || !filter_var($formData['admin_email'], FILTER_VALIDATE_EMAIL)) {
$errors['admin_email'] = lang('error_admin_email_invalid');
}
if (!array_key_exists($formData['admin_language'] ?? '', SUPPORTED_LANGUAGES)) {
$errors['admin_language'] = lang('error_admin_language_invalid');
}
if (empty($formData['admin_password']) || strlen($formData['admin_password']) < 8) {
$errors['admin_password'] = lang('error_admin_password_min');
}
if ($formData['admin_password'] !== $formData['admin_password_confirm']) {
$errors['admin_password_confirm'] = lang('error_password_mismatch');
}
// PHP CLI / Composer 경로 처리
$phpBinary = trim($formData['php_binary'] ?? 'php');
$formData['php_binary'] = $phpBinary !== '' ? $phpBinary : 'php';
$formData['composer_binary'] = trim($formData['composer_binary'] ?? '');
// 코어 업데이트 _pending 경로 검증 (입력된 경우만)
$corePendingPath = trim($formData['core_update_pending_path'] ?? '');
if ($corePendingPath !== '') {
// 절대 경로 변환
$absolutePath = str_starts_with($corePendingPath, '/')
? $corePendingPath
: BASE_PATH . '/' . $corePendingPath;
if (file_exists($absolutePath) && !is_dir($absolutePath)) {
$errors['core_update_pending_path'] = lang('error_core_pending_not_directory');
}
}
// DB 테스트 완료 확인
if (empty($errors) && !isset($_SESSION['db_write_tested'])) {
$errors['db_test'] = lang('error_db_not_tested');
}
if (empty($errors) && !empty($formData['use_read_db']) && !isset($_SESSION['db_read_tested'])) {
$errors['db_test'] = lang('error_db_not_tested');
}
// 검증 통과 시 다음 단계로 이동
if (empty($errors)) {
$_SESSION['install_config'] = $formData;
// state.json에는 비밀번호를 저장하지 않음 (보안)
$safeFormData = $formData;
unset($safeFormData['db_write_password'], $safeFormData['db_read_password']);
updateStepStatus(3, 4, [
'config' => $safeFormData,
'installation_status' => 'ready'
]);
redirectToStep(4);
}
}
/**
* POST 요청 라우팅
*
* @param int $currentStep 현재 단계
* @param string $currentLang 현재 언어
* @param array &$formData 폼 데이터 (참조)
* @param array &$errors 에러 배열 (참조)
* @param string|null &$error 에러 메시지 (참조)
*/
function handlePostRequest(int $currentStep, string $currentLang, array &$formData = [], array &$errors = [], ?string &$error = null): void
{
// 단계 이동 처리 (go_to_step POST 파라미터)
if (isset($_POST['go_to_step'])) {
$step = (int)$_POST['go_to_step'];
if ($step >= 0 && $step <= 5) {
$_SESSION['installer_current_step'] = $step;
}
header('Location: ' . INSTALLER_BASE_URL . '/');
exit;
}
// 구 방식 언어 전환 처리 (호환성 유지)
if (isset($_POST['change_language'])) {
$lang = $_POST['lang'] ?? 'ko';
handleLanguageChange($lang);
redirectToStep($currentStep);
}
// Step별 POST 처리
match($currentStep) {
0 => handleStep0Post(),
1 => handleStep1Post($currentLang, $error),
2 => handleStep2Post(),
3 => handleStep3Post($currentLang, $formData, $errors),
default => null
};
}
+213
View File
@@ -0,0 +1,213 @@
<?php
/**
* 세션 관리 및 CSRF 토큰 처리
*
* 그누보드7 웹 인스톨러의 세션 관리와 CSRF 보호 기능을 제공합니다.
*/
// 세션이 이미 시작되지 않았으면 시작
if (session_status() === PHP_SESSION_NONE) {
// 세션 설정
ini_set('session.cookie_httponly', '1');
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_samesite', 'Strict');
// HTTPS 환경에서는 secure 쿠키 사용
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
ini_set('session.cookie_secure', '1');
}
session_start();
// 언어 초기화 우선순위: state.json > 브라우저 언어 > 기본값(ko)
// 주의: localStorage는 클라이언트에서만 접근 가능하므로 0-welcome.php에서 동기화 처리
if (!isset($_SESSION['g7_locale'])) {
$detectedLang = null;
// 1. state.json에서 복원 시도 (다른 브라우저에서 재개 지원)
$stateFile = dirname(__DIR__, 3) . '/storage/installer-state.json';
if (file_exists($stateFile) && is_readable($stateFile)) {
$stateContent = @file_get_contents($stateFile);
if ($stateContent !== false) {
$state = json_decode($stateContent, true);
if (json_last_error() === JSON_ERROR_NONE && isset($state['g7_locale'])) {
$detectedLang = $state['g7_locale'];
error_log("[세션 초기화] state.json에서 언어 복원: {$detectedLang}");
}
}
}
// 2. state.json에 없으면 브라우저 언어 감지
if ($detectedLang === null) {
require_once __DIR__ . '/functions.php';
$browserLang = detectBrowserLanguage();
if ($browserLang !== null) {
$detectedLang = $browserLang;
error_log("[세션 초기화] 브라우저에서 언어 감지: {$browserLang}");
}
}
// 3. 최종 기본값
$_SESSION['g7_locale'] = $detectedLang ?? 'ko';
error_log("[세션 초기화] 최종 설정 언어: {$_SESSION['g7_locale']}");
} else {
error_log("[세션 초기화] g7_locale 이미 존재: {$_SESSION['g7_locale']}");
}
}
/**
* CSRF 토큰 생성
*
* 세션에 CSRF 토큰이 없으면 새로 생성합니다.
*
* @return string 생성된 CSRF 토큰
*/
function generateCsrfToken(): string
{
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
/**
* CSRF 토큰 반환
*
* 현재 세션의 CSRF 토큰을 반환합니다.
* 토큰이 없으면 새로 생성합니다.
*
* @return string CSRF 토큰
*/
function getCsrfToken(): string
{
return generateCsrfToken();
}
/**
* CSRF 토큰 검증
*
* POST 요청의 csrf_token과 세션의 토큰을 비교하여 검증합니다.
* 검증 실패 시 403 에러를 반환하고 스크립트를 종료합니다.
*
* @return bool 검증 성공 여부 (성공 시 true, 실패 시 스크립트 종료)
*/
function verifyCsrfToken(): bool
{
// POST 요청이 아니면 검증하지 않음
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
return true;
}
// POST 데이터에서 CSRF 토큰 가져오기
$requestToken = $_POST['csrf_token'] ?? '';
// 세션의 CSRF 토큰
$sessionToken = $_SESSION['csrf_token'] ?? '';
// 토큰 비교 (타이밍 공격 방지를 위해 hash_equals 사용)
if (!hash_equals($sessionToken, $requestToken)) {
// 토큰 불일치 시 403 에러
http_response_code(403);
// 다국어 메시지 (언어 설정이 있으면 사용)
$lang = $_SESSION['g7_locale'] ?? 'ko';
$errorMessages = [
'ko' => 'CSRF 토큰이 유효하지 않습니다. 페이지를 새로고침한 후 다시 시도해주세요.',
'en' => 'Invalid CSRF token. Please refresh the page and try again.',
];
$message = $errorMessages[$lang] ?? $errorMessages['ko'];
// JSON 응답 또는 HTML 응답
if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
header('Content-Type: application/json');
echo json_encode([
'success' => false,
'message' => $message,
]);
} else {
// 403 에러 페이지 템플릿 표시
include __DIR__ . '/../views/403-forbidden.php';
}
exit;
}
return true;
}
/**
* 세션 데이터 저장
*
* 세션에 키-값 쌍을 저장합니다.
*
* @param string $key 키
* @param mixed $value 값
* @return void
*/
function setSessionData(string $key, $value): void
{
$_SESSION[$key] = $value;
}
/**
* 세션 데이터 조회
*
* 세션에서 키에 해당하는 값을 조회합니다.
*
* @param string $key 키
* @param mixed $default 기본값 (키가 없을 때 반환)
* @return mixed 세션 값 또는 기본값
*/
function getSessionData(string $key, $default = null)
{
return $_SESSION[$key] ?? $default;
}
/**
* 세션 데이터 삭제
*
* 세션에서 특정 키를 삭제합니다.
*
* @param string $key 키
* @return void
*/
function deleteSessionData(string $key): void
{
if (isset($_SESSION[$key])) {
unset($_SESSION[$key]);
}
}
/**
* 세션 초기화
*
* 모든 세션 데이터를 삭제하고 세션을 종료합니다.
*
* @return void
*/
function destroySession(): void
{
$_SESSION = [];
// 세션 쿠키도 삭제
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
session_destroy();
}
+404
View File
@@ -0,0 +1,404 @@
<?php
/**
* 입력값 검증 함수
*
* 그누보드7 웹 인스톨러의 입력값 검증 기능을 제공합니다.
*/
/**
* 검증 에러 메시지를 다국어로 반환
*
* @param string $key 번역 키
* @param string $lang 언어 코드
* @param array $replacements 치환할 플레이스홀더 배열
* @return string 번역된 메시지
*/
function getValidationMessage(string $key, string $lang, array $replacements = []): string
{
$langFile = __DIR__ . "/../lang/{$lang}.php";
if (!file_exists($langFile)) {
return $key;
}
$translations = require $langFile;
$message = $translations[$key] ?? $key;
foreach ($replacements as $placeholder => $value) {
$message = str_replace(":{$placeholder}", $value, $message);
}
return $message;
}
/**
* 입력값 검증
*
* 주어진 규칙에 따라 입력값을 검증합니다.
*
* @param string $field 필드명
* @param mixed $value 검증할 값
* @param array $rules 검증 규칙 배열 (예: ['required', 'email', 'min:8'])
* @param array $data 전체 데이터 배열 (confirmed 규칙에 필요)
* @param string $lang 언어 코드 (ko 또는 en)
* @return array 검증 에러 배열 (빈 배열이면 검증 성공)
*/
function validateInput(string $field, $value, array $rules, array $data = [], string $lang = 'ko'): array
{
$errors = [];
foreach ($rules as $rule) {
// 규칙과 파라미터 분리 (예: 'min:8' => ['min', '8'])
$ruleParts = explode(':', $rule, 2);
$ruleName = $ruleParts[0];
$ruleParam = $ruleParts[1] ?? null;
// 각 규칙 검증
$errorMessage = null;
switch ($ruleName) {
case 'required':
$errorMessage = validateRequired($field, $value, $lang);
break;
case 'email':
$errorMessage = validateEmail($field, $value, $lang);
break;
case 'min':
$errorMessage = validateMin($field, $value, $ruleParam, $lang);
break;
case 'max':
$errorMessage = validateMax($field, $value, $ruleParam, $lang);
break;
case 'url':
$errorMessage = validateUrl($field, $value, $lang);
break;
case 'alpha_num':
$errorMessage = validateAlphaNum($field, $value, $lang);
break;
case 'confirmed':
$errorMessage = validateConfirmed($field, $value, $data, $lang);
break;
case 'numeric':
$errorMessage = validateNumeric($field, $value, $lang);
break;
case 'integer':
$errorMessage = validateInteger($field, $value, $lang);
break;
case 'in':
$allowedValues = $ruleParam ? explode(',', $ruleParam) : [];
$errorMessage = validateIn($field, $value, $allowedValues, $lang);
break;
default:
// 알 수 없는 규칙은 무시
break;
}
// 에러 메시지가 있으면 배열에 추가
if ($errorMessage !== null) {
$errors[] = $errorMessage;
}
}
return $errors;
}
/**
* 필수 입력 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateRequired(string $field, $value, string $lang): ?string
{
$isEmpty = $value === null
|| $value === ''
|| (is_array($value) && empty($value));
if ($isEmpty) {
$fieldLabel = getFieldLabel($field, $lang);
return getValidationMessage('validation_required', $lang, ['field' => $fieldLabel]);
}
return null;
}
/**
* 이메일 형식 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateEmail(string $field, $value, string $lang): ?string
{
// 빈 값은 required 규칙에서 처리
if ($value === null || $value === '') {
return null;
}
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$fieldLabel = getFieldLabel($field, $lang);
return getValidationMessage('validation_email', $lang, ['field' => $fieldLabel]);
}
return null;
}
/**
* 최소 길이 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param string|int $min 최소 길이
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateMin(string $field, $value, $min, string $lang): ?string
{
// 빈 값은 required 규칙에서 처리
if ($value === null || $value === '') {
return null;
}
$length = is_string($value) ? mb_strlen($value) : (is_numeric($value) ? $value : 0);
if ($length < (int) $min) {
$fieldLabel = getFieldLabel($field, $lang);
return getValidationMessage('validation_min', $lang, ['field' => $fieldLabel, 'min' => $min]);
}
return null;
}
/**
* 최대 길이 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param string|int $max 최대 길이
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateMax(string $field, $value, $max, string $lang): ?string
{
// 빈 값은 required 규칙에서 처리
if ($value === null || $value === '') {
return null;
}
$length = is_string($value) ? mb_strlen($value) : (is_numeric($value) ? $value : 0);
if ($length > (int) $max) {
$fieldLabel = getFieldLabel($field, $lang);
return getValidationMessage('validation_max', $lang, ['field' => $fieldLabel, 'max' => $max]);
}
return null;
}
/**
* URL 형식 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateUrl(string $field, $value, string $lang): ?string
{
// 빈 값은 required 규칙에서 처리
if ($value === null || $value === '') {
return null;
}
if (!filter_var($value, FILTER_VALIDATE_URL)) {
$fieldLabel = getFieldLabel($field, $lang);
return getValidationMessage('validation_url', $lang, ['field' => $fieldLabel]);
}
return null;
}
/**
* 영문자와 숫자만 허용 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateAlphaNum(string $field, $value, string $lang): ?string
{
// 빈 값은 required 규칙에서 처리
if ($value === null || $value === '') {
return null;
}
if (!ctype_alnum((string) $value)) {
$fieldLabel = getFieldLabel($field, $lang);
return getValidationMessage('validation_alpha_num', $lang, ['field' => $fieldLabel]);
}
return null;
}
/**
* 확인 필드 일치 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param array $data 전체 데이터
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateConfirmed(string $field, $value, array $data, string $lang): ?string
{
// 빈 값은 required 규칙에서 처리
if ($value === null || $value === '') {
return null;
}
$confirmField = $field . '_confirmation';
$confirmValue = $data[$confirmField] ?? null;
if ($value !== $confirmValue) {
$fieldLabel = getFieldLabel($field, $lang);
return getValidationMessage('validation_confirmed', $lang, ['field' => $fieldLabel]);
}
return null;
}
/**
* 숫자 형식 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateNumeric(string $field, $value, string $lang): ?string
{
// 빈 값은 required 규칙에서 처리
if ($value === null || $value === '') {
return null;
}
if (!is_numeric($value)) {
$fieldLabel = getFieldLabel($field, $lang);
return getValidationMessage('validation_numeric', $lang, ['field' => $fieldLabel]);
}
return null;
}
/**
* 정수 형식 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateInteger(string $field, $value, string $lang): ?string
{
// 빈 값은 required 규칙에서 처리
if ($value === null || $value === '') {
return null;
}
if (!filter_var($value, FILTER_VALIDATE_INT)) {
$fieldLabel = getFieldLabel($field, $lang);
return getValidationMessage('validation_integer', $lang, ['field' => $fieldLabel]);
}
return null;
}
/**
* 허용된 값 목록 검증
*
* @param string $field 필드명
* @param mixed $value 값
* @param array $allowedValues 허용된 값 목록
* @param string $lang 언어
* @return string|null 에러 메시지 (성공 시 null)
*/
function validateIn(string $field, $value, array $allowedValues, string $lang): ?string
{
// 빈 값은 required 규칙에서 처리
if ($value === null || $value === '') {
return null;
}
if (!in_array($value, $allowedValues, true)) {
$fieldLabel = getFieldLabel($field, $lang);
$allowedList = implode(', ', $allowedValues);
return getValidationMessage('validation_in', $lang, ['field' => $fieldLabel, 'values' => $allowedList]);
}
return null;
}
/**
* 필드 라벨 반환
*
* 다국어 파일에서 필드 라벨을 가져옵니다.
*
* @param string $field 필드명
* @param string $lang 언어 코드 (ko 또는 en)
* @return string 필드 라벨
*/
function getFieldLabel(string $field, string $lang): string
{
// 다국어 파일 경로
$langFile = __DIR__ . "/../lang/{$lang}.php";
// 다국어 파일이 존재하지 않으면 필드명 반환
if (!file_exists($langFile)) {
return $field;
}
$translations = require $langFile;
// fields 키에서 해당 필드 반환 (없으면 필드명 반환)
return $translations['fields'][$field] ?? $field;
}
/**
* 여러 필드 일괄 검증
*
* @param array $data 검증할 데이터
* @param array $rules 필드별 검증 규칙 (예: ['email' => ['required', 'email']])
* @param string $lang 언어 코드
* @return array 필드별 에러 배열 (빈 배열이면 검증 성공)
*/
function validateMultiple(array $data, array $rules, string $lang = 'ko'): array
{
$errors = [];
foreach ($rules as $field => $fieldRules) {
$value = $data[$field] ?? null;
$fieldErrors = validateInput($field, $value, $fieldRules, $data, $lang);
if (!empty($fieldErrors)) {
$errors[$field] = $fieldErrors;
}
}
return $errors;
}
+168
View File
@@ -0,0 +1,168 @@
<?php
/**
* 그누보드7 웹 인스톨러 메인 라우터
*
* @author sirsoft
*/
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/session.php';
require_once __DIR__ . '/includes/installer-state.php';
require_once __DIR__ . '/includes/request-handler.php';
$currentLang = getCurrentLanguage();
// 세션 기반 단계 관리 (URL 파라미터 무시)
if (!isset($_SESSION['installer_current_step'])) {
// 세션이 없으면 state.json에서 현재 step 가져오기
$state = getInstallationState();
// 설치가 진행 중이거나 중단/실패 상태면 state의 current_step 사용
if (isset($state['installation_status']) &&
in_array($state['installation_status'], ['running', 'aborted', 'failed', 'pending'])) {
$_SESSION['installer_current_step'] = $state['current_step'] ?? 0;
} else {
// 그 외에는 0부터 시작
$_SESSION['installer_current_step'] = 0;
}
}
$currentStep = $_SESSION['installer_current_step'];
// URL 파라미터로 step 접근 시 알림 후 리다이렉트
if (isset($_GET['step'])) {
$urlStep = (int)$_GET['step'];
// 번역 로드
if (!isset($translations)) {
$translations = loadTranslations($currentLang);
}
// URL 파라미터의 step과 세션 step이 다른 경우
if ($urlStep !== $currentStep) {
showAlertAndRedirect(
lang('url_parameter_not_supported'),
lang('url_parameter_redirect_message', [
'requested' => $urlStep,
'current' => $currentStep
]),
INSTALLER_BASE_URL . '/'
);
}
// 같은 경우에도 깔끔한 URL로 리다이렉트
header('Location: ' . INSTALLER_BASE_URL . '/');
exit;
}
$state = getInstallationState();
$errors = [];
$formData = [];
$error = null;
// Step 3 기본값 설정
if ($currentStep === 3) {
$defaults = DEFAULT_INSTALL_CONFIG;
$defaults['app_url'] = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
$defaults['admin_language'] = getCurrentLanguage();
// state.json에서 비밀번호 제외된 config 복원 (세션에서 비밀번호를 사전 입력하지 않음)
$savedConfig = $state['config'] ?? $defaults;
unset($savedConfig['db_write_password'], $savedConfig['db_read_password']);
$formData = array_merge($defaults, $savedConfig);
}
// 설치 흐름 검증
validateInstallationFlow($currentStep, $state);
// POST 요청 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
handlePostRequest($currentStep, $currentLang, $formData, $errors, $error);
}
// 번역 로드
if (!isset($translations)) {
$translations = loadTranslations($currentLang);
}
// Step 범위 체크 (0: welcome ~ 6: complete)
if ($currentStep < 0 || $currentStep > 6) {
$currentStep = 0;
}
$stepFile = __DIR__ . '/views/' . $currentStep . '-' . (STEP_FILE_MAP[$currentStep] ?? 'welcome') . '.php';
?>
<!DOCTYPE html>
<html lang="<?= $currentLang ?>">
<script>
// 다크모드 즉시 적용 - 렌더링 전 실행 (FOUC 깜빡임 방지)
(function(){
try {
const theme = localStorage.getItem('g7_color_scheme')
|| (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', theme);
} catch(e) {
// localStorage 접근 실패 시 기본값(light) 사용
document.documentElement.setAttribute('data-theme', 'light');
}
})();
</script>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><?= lang('welcome_title') ?> - 그누보드7</title>
<!-- CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="<?= INSTALLER_BASE_URL ?>/assets/css/installer.css?v=<?= time() ?>">
</head>
<body>
<?php if ($currentStep > 0): ?>
<!-- Installer Header Bar -->
<div class="installer-header-bar">
<div class="installer-header-content">
<div class="installer-header-left">
<span class="installer-logo">그누보드7</span>
</div>
<div class="installer-header-right">
<span class="installer-step-indicator">
[<?= $currentStep ?>/5] <?= lang(getStepName($currentStep)) ?>
</span>
<button
id="theme-toggle-btn"
class="theme-toggle"
type="button"
aria-label="<?= lang('toggle_theme') ?>"
title="<?= lang('toggle_theme') ?>"
>
<span id="theme-toggle-icon">🌙</span>
</button>
</div>
</div>
</div>
<?php endif; ?>
<!-- Main Content -->
<?php
if (file_exists($stepFile)) {
require_once $stepFile;
} else {
showStepFileNotFoundError($currentStep);
}
?>
<!-- Installer Footer -->
<footer class="installer-footer">
<p>&copy; <?= APP_RELEASE_YEAR ?> Gnuboard7. All rights reserved.</p>
</footer>
<!-- JavaScript -->
<script>
window.INSTALLER_BASE_URL = '<?= INSTALLER_BASE_URL ?>';
window.CURRENT_STEP = <?= $currentStep ?>;
window.INSTALLER_LANG = <?= json_encode($translations ?? [], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
window.INSTALLER_STATE_LOCALE = <?= json_encode($state['g7_locale'] ?? null) ?>;
</script>
<script src="<?= INSTALLER_BASE_URL ?>/assets/js/installer.js?v=<?= time() ?>"></script>
</body>
</html>
+785
View File
@@ -0,0 +1,785 @@
<?php
// /install/lang/en.php
return [
// Common
'next' => 'Next',
'previous' => 'Previous',
'install' => 'Install',
'cancel' => 'Cancel',
'yes' => 'Yes',
'no' => 'No',
'loading' => 'Loading...',
'saving' => 'Saving...',
'save_failed' => 'Save failed',
'error' => 'Error',
// Step 0: Welcome
'welcome_title' => 'Getting Started with Gnuboard7',
'welcome_desc' => 'Welcome to Gnuboard7. This is the first step of the installation.<br>Follow the guided steps in order to complete the required environment setup quickly and reliably.',
'select_language' => 'Select Language',
'storage_permission_check' => 'Directory Permission Check',
'storage_permission_required' => 'Storage Folder Permission Required',
'storage_permission_failed' => 'Insufficient storage folder permissions',
'storage_not_exists' => 'Storage Folder Not Found',
'storage_not_exists_message' => 'The storage folder does not exist. Please create a storage folder in the project root.',
'storage_not_writable' => 'Storage Folder Not Writable',
'storage_not_writable_message' => 'The storage folder is not writable. Please check the folder owner or group permissions.',
'storage_permission_guide' => 'Please grant <strong>:permissions</strong> permission to the Storage folder.',
'storage_permission_guide_detail' => 'Run the command below or change permissions via FTP:',
'storage_permission_command_linux' => 'chmod -R :permissions :path',
'current_owner' => 'Owner',
'current_group' => 'Group',
'current_permissions' => 'Permissions',
'required_permissions' => 'Required',
'unknown' => 'Unknown',
'recheck_permission' => 'Recheck',
'permission_checking' => 'Checking permissions...',
// Step 1: License
'license_title' => 'License Agreement',
'license_agreement' => 'License Terms',
'i_agree' => 'I agree to the above license terms',
'must_agree' => 'You must agree to the license to continue.',
'license_not_found' => 'License information not found.',
// Step 2: Requirements
'checking_requirements' => 'Checking server requirements...',
'php_version' => 'PHP Version',
'php_modules' => 'PHP Modules',
'directory_permissions' => 'Directory Permissions',
'disk_space' => 'Disk Space',
'https_enabled' => 'HTTPS Enabled',
'required' => 'Required',
'enabled' => 'Enabled',
'not_enabled' => 'Not Enabled',
'recommended' => 'Recommended',
'needs_fix' => 'Needs Fix',
'requirements_check_failed' => 'Requirements check failed',
'all_requirements_met' => 'All requirements are met.',
'some_requirements_failed' => 'Some requirements are not met. Please check your server configuration.',
'recheck' => 'Recheck',
'requirements_not_met' => 'Required conditions are not met. Please check your environment and try again.',
'badge_required' => 'Required',
'badge_optional' => 'Optional',
'or_above' => 'or above',
'fix_permission' => 'Insufficient write permission',
'including_subdirectories' => 'including subdirectories',
'and_more' => 'and :count more',
'error_php_version' => 'PHP Version',
'error_missing_extensions' => 'Missing required PHP extensions',
'error_disk_space' => 'Disk Space',
'error_directory_permissions' => 'Insufficient directory write permissions',
'error_required_files' => 'Required files missing',
'required_files' => 'Required Files',
'file_exists' => 'Exists',
'file_missing' => 'Missing',
'file_not_writable' => 'Not Writable',
'required_files_fix_guide' => 'Run the following command in your project root:',
'minimum' => 'minimum',
'required_text' => 'required',
// Step 3: Configuration
'database_settings' => 'Database Settings',
'database_type' => 'Database Type',
'db_host' => 'Database Host',
'db_port' => 'Port',
'db_name' => 'Database Name',
'db_username' => 'Username',
'db_password' => 'Password',
'db_prefix' => 'Table Prefix',
'db_prefix_hint' => 'Prefix added to all table names. (e.g., g7_users, g7_posts)',
'db_prefix_placeholder' => 'g7_',
'test_write_db_connection' => 'Test Write DB Connection',
'test_read_db_connection' => 'Test Read DB Connection',
'use_read_db' => 'Use Read DB Settings',
'database_settings_read' => 'Database Settings (Read DB) - Optional',
'site_settings' => 'Site Settings',
'app_name' => 'Site Name',
'app_url' => 'Site URL',
'admin_account' => 'Admin Account',
'admin_name' => 'Admin Name',
'admin_language' => 'Admin Language',
'admin_email' => 'Admin Email',
'admin_password' => 'Admin Password',
'admin_password_confirm' => 'Confirm Password',
'start_installation' => 'Start Installation',
// Step 5: Installation
'installation_title' => 'Installation in Progress',
'installation_in_progress' => 'Installing Gnuboard7. Please wait...',
'installation_in_progress_message' => 'Installation is in progress. Redirecting to installation page.',
'overall_progress' => 'Overall Progress',
'preparing' => 'Preparing...',
'waiting_installation' => 'Waiting for installation to start...',
'processing' => 'Processing...',
'installation_complete' => 'Installation Complete',
'installation_failed' => 'Installation Failed',
'retry_installation' => 'Retry',
'do_not_close_page' => 'Do not close this page until the installation is complete.',
'installation_log' => 'Installation Log',
'hide_log' => 'Hide Log',
'show_log' => 'Show Log',
'back_to_settings' => 'Back to Settings',
'progress_status' => 'Installation List',
'hide_progress' => 'Hide Installation List',
'show_progress' => 'Show Installation List',
'installation_completed' => 'Installation Complete!',
'recommendations' => 'Post-Installation Recommendations',
'recommendation_env_permission' => 'Set .env file permissions to 600 or 644',
'recommendation_https' => 'Use HTTPS in production environment',
// Step 5: Complete
'installation_info' => 'Installation Information',
'installation_complete_message' => 'Gnuboard7 has been successfully installed!',
'site_url' => 'Site URL',
'installed_at' => 'Installed At',
'go_to_admin_login' => 'Admin Login',
// Re-entry
'completed_tasks' => 'Completed Tasks',
'interrupted_task' => 'Interrupted Task',
'pending_tasks' => 'Pending Tasks',
'interrupted_during_execution' => 'Interrupted during execution',
'resume_continue' => 'Continue',
'installation_resuming' => 'Installation Resuming',
// Error Messages - Common
'error_occurred' => 'An error occurred',
'please_try_again' => 'Please try again.',
'invalid_input' => 'Invalid input.',
// Error Messages - Validation (Database)
'error_db_host_required' => 'Database host is required.',
'error_db_name_required' => 'Database name is required.',
'error_db_username_required' => 'Database username is required.',
'error_db_credentials_required' => 'Database name and username are required.',
'error_db_connection_failed' => 'Database connection failed.',
'error_db_privileges_insufficient' => 'Insufficient database privileges.',
'error_db_not_tested' => 'Please test the database connection first.',
'error_write_db_not_tested' => 'Please test Write DB connection first.',
'error_read_db_not_tested' => 'Please test Read DB connection first.',
// Error Messages - Validation (Database) (detailed)
'error_db_privileges_insufficient_detail' => 'Insufficient privileges for :type database: :missing',
'error_db_connection_failed_detail' => ':type database connection failed: :error',
'error_db_test_failed' => 'Error occurred during database testing',
// Error Messages - Validation (Admin Account)
'error_admin_email_invalid' => 'Please enter a valid email address.',
'error_admin_language_invalid' => 'Please select a valid language.',
'error_admin_name_required' => 'Please enter admin name.',
'error_admin_password_required' => 'Please enter admin password.',
'error_admin_password_min' => 'Password must be at least 8 characters long.',
'error_admin_password_confirm_required' => 'Please enter password confirmation.',
'error_password_mismatch' => 'Passwords do not match.',
'error_app_name_required' => 'Please enter site name.',
'error_app_url_required' => 'Please enter site URL.',
'error_field_required' => 'This field is required.',
// Error Messages - System (Requirements)
'error_requirements_check_failed' => 'An error occurred while checking requirements.',
'error_php_version_insufficient' => 'PHP version does not meet requirements.',
'error_php_extensions_missing' => 'Some required PHP extensions are not installed.',
'error_disk_space_insufficient' => 'Insufficient disk space.',
'error_disk_space_unknown' => 'Unable to determine disk space.',
'error_directory_not_writable' => 'Some directories are not writable.',
// Error Messages - System (Requirements) (detailed)
'error_php_version_insufficient_detail' => 'PHP version does not meet requirements (current: :current, required: :min+)',
'error_disk_space_insufficient_detail' => 'Insufficient disk space (current: :current MB, required: :min MB)',
'error_directory_not_writable_detail' => 'Some directories are not writable. Please set permissions to :permissions.',
'error_required_files_missing' => 'Required files are missing.',
'error_step_file_not_found' => 'Step file not found. Installation files may be corrupted.',
'error_state_file_creation_failed' => 'Unable to create installation state file (state.json). Please check write permissions for the storage/installer directory.',
'error_invalid_step_access' => 'Invalid step access',
'error_invalid_step_access_message' => 'Please follow the installation steps in order.',
// Success Messages - Database
'success_db_write_connected' => 'Write database connection and privileges verified successfully.',
'success_db_read_connected' => 'Read database connection and privileges verified successfully.',
// Success Messages - Requirements
'success_requirements_met' => 'All requirements are met.',
'success_php_version' => 'PHP version meets requirements.',
'success_php_extensions' => 'All required PHP extensions are installed.',
'success_disk_space' => 'Sufficient disk space available.',
'success_directories_writable' => 'All directories are writable.',
'success_required_files' => 'All required files exist.',
// Success Messages - Requirements (detailed)
'success_php_version_detail' => 'PHP version meets requirements (current: :current, required: :min+)',
'success_disk_space_detail' => 'Sufficient disk space available (current: :current MB, required: :min MB)',
// HTTPS Messages
'https_enabled' => 'HTTPS is enabled (recommended)',
'https_disabled' => 'HTTPS is disabled. We recommend using HTTPS for security.',
// API Response Messages
'api_method_not_allowed' => 'Only POST requests are allowed.',
'api_invalid_request' => 'Invalid request data.',
'api_unexpected_error' => 'An unexpected error occurred.',
// Step Names (for helper functions)
'step_0_welcome' => 'Welcome',
'step_1_license' => 'License Agreement',
'step_2_requirements' => 'Requirements Check',
'step_3_configuration' => 'Configuration',
'step_4_extension_selection' => 'Extension Selection',
'step_5_installation' => 'Installation',
'step_6_complete' => 'Complete',
'step_unknown' => 'Unknown Step',
// Task Names (for helper functions)
'task_composer_check' => 'Checking Package Manager',
'task_composer_install' => 'Installing Required Packages',
'task_env_create' => 'Creating Configuration File',
'task_env_update' => 'Updating Configuration File',
'task_key_generate' => 'Generating Security Key',
'task_db_migrate' => 'Creating Database Tables',
'task_db_seed' => 'Initializing Default Data',
'task_template_install' => 'Installing Admin Template',
'task_template_activate' => 'Activating Admin Template',
'task_module_install' => 'Installing Module',
'task_module_activate' => 'Activating Module',
'task_plugin_install' => 'Installing Plugin',
'task_plugin_activate' => 'Activating Plugin',
'task_user_template_install' => 'Installing User Template',
'task_user_template_activate' => 'Activating User Template',
'task_cache_clear' => 'Cleaning Up Temporary Files',
'task_create_settings_json' => 'Creating Settings Files',
'task_complete_flag' => 'Finalizing Installation',
'task_unknown' => 'Unknown Task',
// Task Group Names
'task_group_environment' => 'Environment Setup',
'task_group_database' => 'Database',
'task_group_admin_templates' => 'Admin Templates',
'task_group_modules' => 'Modules',
'task_group_plugins' => 'Plugins',
'task_group_user_templates' => 'User Templates',
'task_group_finalize' => 'Finalize',
// Group Status Labels
'status_pending' => 'Pending',
'status_in_progress' => 'In Progress',
'status_completed' => 'Completed',
'status_failed' => 'Failed',
'status_aborted' => 'Aborted',
// Error Messages - Worker (Composer)
'error_composer_not_installed' => 'Composer is not installed.',
'error_composer_install_failed' => 'Composer dependency installation failed',
// Log Messages - Worker (Composer)
'log_composer_check_success' => 'Composer check completed',
'log_composer_already_installed' => 'Composer dependencies are already installed',
'log_composer_install_success' => 'Composer dependency installation completed',
'log_composer_vendor_without_lock' => 'vendor directory exists but composer.lock is missing (incomplete state)',
'log_composer_removing_vendor' => 'Removing vendor directory and reinstalling...',
'log_composer_vendor_deleted' => 'vendor directory deleted',
'log_composer_vendor_delete_failed' => 'Failed to delete vendor directory (continuing anyway)',
'log_composer_installing_from_lock' => 'Installing dependencies from composer.lock...',
'log_composer_fresh_install' => 'Installing new Composer dependencies...',
'log_composer_cache_cleared' => 'Cleared previous package cache',
// Error Messages - Worker (.env)
'error_env_example_not_found' => '.env.example file not found',
'error_env_create_failed' => '.env file creation failed',
'error_env_not_found' => '.env file not found.',
// Log Messages - Worker (.env)
'log_env_create_success' => '.env file creation completed',
'log_env_update_success' => '.env file updated successfully',
'log_env_readonly_skip' => '.env file is read-only, skipping update.',
'log_env_flag_skipped' => '.env file is read-only, skipping installation completion flag.',
// Error Messages - Worker (Key)
'error_key_generate_failed' => 'Application key generation failed',
// Log Messages - Worker (Key)
'log_key_generate_success' => 'Application key generation completed',
// Error Messages - Worker (Database)
'error_db_migrate_failed' => 'Database table creation failed',
'error_db_seed_failed' => 'Default data initialization failed',
// Log Messages - Worker (Database)
'log_db_migrate_success' => 'Database migration completed',
'log_db_seed_success' => 'Database seeding completed',
// Error Messages - Worker (Template)
'error_template_install_failed' => 'Template installation failed',
'error_template_activate_failed' => 'Template activation failed',
// Log Messages - Worker (Template)
'log_template_install_success' => 'Template installation completed',
'log_template_activate_success' => 'Template activation completed',
// Error Messages - Worker (Module)
'error_module_install_failed' => 'Module installation failed',
'error_module_activate_failed' => 'Module activation failed',
// Log Messages - Worker (Module)
'log_module_install_success' => 'Module installation completed',
'log_module_activate_success' => 'Module activation completed',
// Error Messages - Worker (Plugin)
'error_plugin_install_failed' => 'Plugin installation failed',
'error_plugin_activate_failed' => 'Plugin activation failed',
// Log Messages - Worker (Plugin)
'log_plugin_install_success' => 'Plugin installation completed',
'log_plugin_activate_success' => 'Plugin activation completed',
// Error Messages - Worker (User Template)
'error_user_template_install_failed' => 'User template installation failed',
'error_user_template_activate_failed' => 'User template activation failed',
// Log Messages - Worker (User Template)
'log_user_template_install_success' => 'User template installation completed',
'log_user_template_activate_success' => 'User template activation completed',
// Error Messages - Worker (Cache)
'error_cache_clear_failed' => 'Cache clearing failed',
// Log Messages - Worker (Cache)
'log_cache_clear_success' => 'Cache clearing completed',
// Error Messages - Worker (Settings JSON)
'error_settings_json_failed' => 'Settings file creation failed',
// Log Messages - Worker (Settings JSON)
'log_creating_settings' => 'Creating settings JSON files...',
'log_settings_json_created' => 'Settings JSON files created successfully',
// Error Messages - Worker (Admin)
'error_autoload_not_found' => 'vendor/autoload.php file not found',
'error_app_bootstrap_not_found' => 'bootstrap/app.php file not found',
// Log Messages - Worker (Complete)
'log_complete_flag_success' => 'Installation completion flag set successfully',
'log_installation_completed' => 'Installation completed successfully',
'log_installation_failed' => 'Installation failed',
'log_installation_task_failed' => '[Failed] :task: :message',
'log_installation_exception' => '[Failed] Installation error occurred: :error',
// Worker Log Messages (Task Progress)
'log_task_in_progress' => ':task in progress...',
'log_task_completed' => ':task completed',
'log_task_skipped' => ':task (already exists, skipped)',
'manual_commands_guide' => '💡 You can run the following commands manually:',
'log_separator' => '========================================',
'log_error_occurred' => '❌ Error occurred: :error',
'log_env_file_created' => '.env file created successfully',
'log_env_flag_added' => 'Installation complete flag added to .env file',
'log_installed_flag_created' => 'g7_installed flag file created',
'log_state_updated' => 'Installation state updated successfully',
'log_all_tasks_completed' => '🎉 All installation tasks completed successfully!',
'log_already_completed' => ':task (already completed)',
// Worker Abort Messages
'abort_connection_lost' => '[Aborted] Browser connection lost.',
'abort_rollback_start' => "[Aborted] Starting rollback for current task ':task'.",
'abort_rollback_success' => '[Aborted] Rollback completed: :message',
'abort_rollback_failed' => '[Aborted] Rollback failed: :message (continuing)',
'abort_no_rollback_needed' => '[Aborted] No rollback needed. (current_task is null or already completed)',
'abort_by_user' => "[Aborted] User aborted installation. (Current task: :task)",
'abort_installation_stopped' => 'Installation aborted.',
// Worker Failed Task Rollback Messages
'failed_rollback_start' => "[Failed] Starting rollback for failed task ':task'.",
'failed_rollback_success' => '[Failed] Rollback completed: :message',
'failed_rollback_failed' => '[Failed] Rollback failed: :message',
'failed_rollback_manual_cleanup' => '[Notice] Rollback failed. Please manually clean up the database and try installation again.',
'failed_rollback_manual_cleanup_detail' => 'Use a database management tool (such as phpMyAdmin) to delete created tables or reset the database, then retry installation.',
'failed_rollback_db_restart' => '[Notice] Database has been rolled back. On retry, installation will restart from database setup.',
'failed_rollback_retry' => '[Notice] The task failed. Please try the installation again.',
'failed_rollback_retry_detail' => 'On retry, installation will resume from the failed task. If the problem persists, refer to the manual commands above.',
// Worker SSE Connection Messages
'sse_connection_established' => 'SSE connection established',
'sse_method_not_allowed' => 'Method not allowed. SSE requires GET request.',
// DB Task No Abort Messages
'db_task_no_abort' => 'Cannot abort during database operations. The abort will happen after the current task completes.',
'db_task_in_progress' => 'Database operation in progress...',
// Worker Error Detail Messages
'error_composer_process_failed' => 'Failed to start composer install process',
'error_composer_exit_code' => 'Composer install failed with exit code: :code',
'error_env_example_not_found_detail' => '.env.example file not found at: :path',
'error_env_write_failed' => 'Failed to write .env file at: :path',
'error_complete_flag_failed' => 'Installation completion flag setting failed',
'error_unexpected_exception' => 'An unexpected error has occurred',
// install-process.php Messages
'error_method_not_allowed' => 'Only POST requests are allowed.',
'error_config_not_in_session' => 'Configuration not found in session. Please complete Step 3 first.',
'error_required_fields_missing' => 'Required fields are missing: :fields',
'log_installation_config_saved' => 'Installation configuration saved - Waiting for SSE connection',
'success_installation_started' => 'Installation started successfully.',
'error_installation_start_failed' => 'Installation process start failed',
'error_installation_start_exception' => 'Error occurred while starting installation: :error',
// get-install-state.php Messages
'error_get_method_required' => 'Only GET requests are allowed.',
'error_state_query_failed' => 'An error occurred while querying installation state.',
// Page Refresh/Leave Warnings (Browser shows default message, but clarifying intent)
'confirm_leave_installation' => 'Installation is in progress. Leaving this page may cause installation issues.',
'confirm_resume_installation' => 'Installation was in progress. Would you like to resume the installation?',
'resume_installation_btn' => 'Resume Installation',
'cancel_installation_btn' => 'Cancel',
// Installation Already Completed Messages
'installation_already_completed' => 'Installation Complete',
'installation_already_completed_message' => 'Gnuboard7 is already installed. Redirecting to homepage...',
// URL Parameter Access Messages
'url_parameter_not_supported' => 'URL Parameter Not Supported',
'url_parameter_redirect_message' => 'The installation process is managed by sessions. Redirecting to the current Step :current instead of requested Step :requested.',
// Installation Abort Related
'abort_installation' => 'Abort Installation',
'aborting' => 'Aborting',
'confirm_abort_installation' => 'Are you sure you want to abort the installation? The current installation progress will be preserved, and you can resume from where you left off later.',
'installation_aborted' => 'Installation Aborted',
'installation_aborted_message' => 'The installation was interrupted due to browser closure or refresh. You can resume the installation from where it was interrupted.',
'clean_state' => 'Clean State',
'cleaning' => 'Cleaning',
'state_cleaned' => 'State has been cleaned',
'clean_failed' => 'Clean failed',
'clean_error' => 'Error occurred while cleaning',
'resuming' => 'Resuming',
'resume_failed' => 'Resume failed',
'resume_error' => 'Error occurred while resuming',
'abort_failed' => 'Abort failed',
'abort_error_occurred' => 'Error occurred while aborting',
// Validation Error Messages (validation.php)
'validation_required' => ':field is required.',
'validation_email' => ':field must be a valid email address.',
'validation_min' => ':field must be at least :min characters.',
'validation_max' => ':field must not exceed :max characters.',
'validation_url' => ':field must be a valid URL.',
'validation_alpha_num' => ':field may only contain letters and numbers.',
'validation_alpha_num_underscore' => ':field may only contain lowercase letters, numbers, and underscores (_).',
'validation_starts_with_alpha' => ':field must start with a lowercase letter.',
'validation_confirmed' => ':field confirmation does not match.',
'validation_numeric' => ':field must be a number.',
'validation_integer' => ':field must be an integer.',
'validation_in' => ':field must be one of: :values',
// Field Labels (validation.php)
'fields' => [
'db_host' => 'Database Host',
'db_port' => 'Database Port',
'db_database' => 'Database Name',
'db_username' => 'Database Username',
'db_password' => 'Database Password',
'db_write_host' => 'Write Database Host',
'db_write_port' => 'Write Database Port',
'db_write_database' => 'Write Database Name',
'db_write_username' => 'Write Database Username',
'db_write_password' => 'Write Database Password',
'db_prefix' => 'Table Prefix',
'db_read_host' => 'Read Database Host',
'db_read_port' => 'Read Database Port',
'db_read_database' => 'Read Database Name',
'db_read_username' => 'Read Database Username',
'db_read_password' => 'Read Database Password',
'app_name' => 'Site Name',
'app_url' => 'Site URL',
'admin_name' => 'Admin Name',
'admin_language' => 'Admin Language',
'admin_email' => 'Admin Email',
'admin_password' => 'Admin Password',
'admin_password_confirmation' => 'Admin Password Confirmation',
'email' => 'Email',
'password' => 'Password',
'password_confirmation' => 'Password Confirmation',
],
// JavaScript Client Messages (installer.js)
'testing_connection' => 'Testing connection...',
'connection_failed_prefix' => 'Connection failed:',
'validation_incomplete_alert' => 'Please complete all required fields and database connection tests.',
'validation_incomplete_title' => 'Please complete the following items:',
'confirm_leave_page' => 'Settings have not been saved. Are you sure you want to leave this page?',
'installation_in_progress_alert' => 'Installation is in progress. Do you want to go back to the settings page?',
'confirm_go_to_settings' => "Do you want to go back to the settings page?",
'confirm_go_to_settings_simple' => "Do you want to go back to the settings page?\n\nInstallation state will be reset and all tasks will start from the beginning.\n\n⚠️ Database tables will NOT be deleted automatically.\nPlease clean up manually using phpMyAdmin if needed.",
'confirm_go_to_settings_title' => 'Go to Settings Page',
'confirm_go_to_settings_desc' => 'Installation state will be reset and all tasks will start from the beginning.\n\n⚠️ Database tables will NOT be deleted automatically. Please clean up manually using phpMyAdmin if needed.',
'confirm_go_to_settings_btn' => 'Go',
'reset_db_checkbox_label' => 'Reset database (delete created tables)',
'error_state_reset_failed' => 'Failed to reset state.\n\n:message\n\nPlease refresh the page and try again.',
'confirm_force_go_to_settings' => 'An error occurred while resetting state.\n\nDo you still want to go to the settings page?',
'view_error_details' => 'View error details',
'installation_error_occurred' => 'An error occurred during installation.',
'installation_start_error' => 'Error starting installation',
'installation_start_failed' => 'Unable to start installation.',
'unknown_error_occurred' => 'An unknown error has occurred.',
// SSE connection failure messages
'sse_connection_timeout' => 'SSE real-time connection failed. Please check server configuration or refresh the page.',
'sse_server_config_guide' => 'If you are the server administrator, please check the following settings:
[Nginx Configuration]
location /install/api/ {
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 600s;
}
[Apache Configuration]
# .htaccess or httpd.conf
<Location /install/api/>
SetEnv no-gzip 1
</Location>
[PHP Configuration]
// Add to the top of install-worker-sse.php
ini_set(\'output_buffering\', \'off\');
ini_set(\'zlib.output_compression\', \'off\');
@apache_setenv(\'no-gzip\', 1);
[Shared Hosting]
Contact your hosting provider about SSE (Server-Sent Events) support.
Firewalls or proxies may be blocking long-lived HTTP connections.',
// Dark Mode
'toggle_theme' => 'Toggle Theme',
'dark_mode' => 'Dark Mode',
'light_mode' => 'Light Mode',
// Step 4: Extension Selection
'extension_selection_description' => 'Select the extensions to install. Admin template is required.',
'loading_extensions' => 'Loading extensions...',
'admin_templates' => 'Admin Templates',
'admin_templates_description' => 'Select a template for the admin panel.',
'user_templates' => 'User Templates',
'user_templates_description' => 'Select a template for the front pages.',
'modules' => 'Modules',
'modules_description' => 'Select modules to install. Modules provide major features like boards and e-commerce.',
'plugins' => 'Plugins',
'plugins_description' => 'Select plugins to install. Plugins provide additional features like payments and notifications.',
'optional' => 'Optional',
'no_extensions_found' => 'No extensions available.',
'no_user_templates' => 'No user templates available.',
'no_modules' => 'No modules available.',
'no_plugins' => 'No plugins available.',
'extension_load_failed' => 'Failed to load extension list.',
'no_admin_template_error' => 'Admin template is required but not found. Please ensure at least one admin template exists in the templates directory.',
'selection_summary' => 'Selection Summary',
'selected_count' => ':count selected',
'admin_template_required' => 'At least one admin template must be selected.',
'proceed_to_installation' => 'Proceed to Installation',
'version' => 'Version',
'select' => 'Select',
'selected' => 'Selected',
'dependencies' => 'Dependencies',
'dependency_type_module' => 'Module',
'dependency_type_plugin' => 'Plugin',
'dependency_type_admin_template' => 'Admin Template',
'dependency_type_user_template' => 'User Template',
'dependency_type_other' => 'Other',
'author' => 'Author',
'retry' => 'Retry',
'select_all' => 'Select All',
'deselect_all' => 'Deselect All',
// install-worker.php i18n keys
'db_task_abort_detected_before_start' => '[DB Task] Abort detected before start - skipping task.',
'db_task_failed_rollback_start' => '[DB Task] :task failed - starting rollback.',
'db_task_abort_reason_connection' => 'Connection lost',
'db_task_abort_reason_user' => 'User requested',
'db_task_completed_abort_detected' => '[DB Task] Abort detected after :task completed (:reason) - starting rollback.',
'db_task_completed_rollback_start' => '[Aborted] Starting rollback after :task completed.',
'log_removing_state_file' => 'Removing installer state file...',
'log_state_file_removed' => 'Installer state file removed successfully.',
'log_state_file_remove_failed' => 'Warning: Failed to remove installer state file.',
'error_worker_exception' => 'Installation worker SSE exception',
// rollback-functions.php i18n keys
'log_prefix_rollback' => '[Rollback]',
'log_prefix_force_rollback' => '[Force Rollback]',
'rollback_not_needed_recreatable' => 'Rollback not needed (can be recreated)',
'rollback_not_needed_overwritable' => 'Rollback not needed (can be overwritten on reinstall/reactivation)',
'rollback_unknown_task' => 'Unknown task: :task',
'rollback_error' => '[Rollback Error] :task: :error',
'rollback_exception' => 'Exception during rollback: :error',
'rollback_migrate_start' => 'Starting migration rollback (migrate:rollback).',
'rollback_migrate_result' => 'migrate:rollback result: :result',
'rollback_migrate_success' => 'Migration rollback completed',
'rollback_migrate_failed_code' => 'Migration rollback failed (returnCode: :code)',
'rollback_migrate_failed' => 'Migration rollback failed',
'rollback_migrate_error' => 'Error during migration rollback: :error',
'rollback_seed_no_config' => 'No DB configuration found. Skipping seed rollback.',
'rollback_seed_already_done' => 'Seed already completed (rollback not needed)',
'rollback_seed_interrupted' => 'Seed was interrupted. Truncating tables.',
'rollback_seed_force_truncate' => 'Force truncating seed data.',
'rollback_table_truncated' => "Table ':table' truncated.",
'rollback_table_truncate_skipped' => "Table ':table' TRUNCATE skipped: :error",
'rollback_seed_data_deleted' => 'Seed data deleted.',
'rollback_db_connection_failed' => 'DB connection failed: :error',
'rollback_db_connection_failed_skip' => 'DB connection failed. Skipping seed rollback.',
'rollback_seed_error' => 'Error during seed processing: :error',
'rollback_env_flag_removed' => 'Removed INSTALLER_COMPLETED from .env.',
'rollback_installed_flag_removed' => 'Deleted g7_installed file.',
'rollback_complete_flag_removed' => 'Installation completion flags removed: :details',
'rollback_complete_flag_error' => 'Error removing completion flag: :error',
'rollback_no_current_task' => 'No current task to rollback. (current_task is null)',
'rollback_task_already_completed' => "':task' is already completed. (rollback not needed)",
'rollback_current_task_start' => "[Aborted] Starting rollback for current task ':task'.",
'rollback_no_completed_tasks' => 'No completed tasks to rollback.',
'rollback_checking_tasks' => 'Checking rollbackable tasks...',
'rollback_no_matching_tasks' => 'No tasks to rollback. (no matching tasks in rollbackable list)',
'rollback_tasks_to_rollback' => 'Tasks to rollback: :tasks',
'rollback_task_rolling_back' => "Rolling back ':task'...",
'rollback_task_success' => "':task' rollback succeeded",
'rollback_task_failed' => "':task' rollback failed: :error",
'manual_cmd_settings_json' => 'settings.json is generated automatically. Please retry the installation.',
// state-management.php i18n keys
'state_reset_requested' => 'Requested navigation to settings page.',
'state_reset_db_notice' => 'DB is not automatically reset. Please clean up manually if needed.',
'state_save_failed' => 'Failed to save state file.',
'state_reset_completed' => 'Installation state has been reset. (Moving to Step :step)',
'abort_api_requested' => '[Abort API] Abort requested - user requested installation abort',
'abort_api_current_status' => '[Abort API] Current installation_status: :status',
'abort_api_current_task' => '[Abort API] Current current_task: :task',
'abort_api_completed_count' => '[Abort API] Completed task count: :count',
'abort_api_already_completed' => 'Installation is already completed and cannot be aborted.',
'abort_api_already_aborted' => 'Installation is already aborted.',
'abort_api_not_running' => 'No installation to abort.',
'abort_user_requested' => 'User requested installation abort.',
'abort_api_status_change' => '[Abort API] Changing installation_status to "aborted".',
'abort_api_save_result' => '[Abort API] state.json save result: :result',
'abort_api_verify_status' => '[Abort API] Verify after save - installation_status: :status',
'api_method_not_allowed' => 'Method not allowed.',
'error_state_management' => 'State management error',
'error_log_prefix' => '[Error] :error',
// functions.php i18n keys
'error_db_name_username_required' => 'Database name and username are required.',
'error_db_connection_failed' => 'Database connection failed: :error',
'error_privilege_check_failed' => 'Error occurred during privilege check',
// Required file setup (Step 5)
'file_setup_title' => 'Create Required Files',
'file_setup_description' => 'The following files are required in the project root to proceed with installation.',
'file_setup_guide' => 'Run the following command in your terminal from the project root directory:',
'file_check_button' => 'Verify files',
'file_checking' => 'Checking...',
'files_not_found_yet' => 'Required files not found yet. Please create the files and try again.',
'copy_command' => 'Copy',
'copied' => 'Copied!',
// Step 2 permission guidance
'permission_fix_guide' => 'Run the following command in your terminal to fix permissions:',
'ownership_fix_guide' => 'Change the ownership to the web server user:',
'ownership_fix_hint' => '※ www-data is the web server user/group. Change it to nginx, apache, etc. depending on your environment.',
'ownership_detected_hint' => '※ Current web server user: :user (auto-detected)',
'permission_windows_hint' => '※ On Windows, open Command Prompt (cmd) as Administrator and run the command. Alternatively, you can set permissions via folder Properties → Security tab.',
'directory_create_guide' => 'Run the following command to create the missing directories:',
// Directory names (Step 2)
'dir_bootstrap_cache' => 'Bootstrap cache directory',
'dir_vendor' => 'Packages directory',
'dir_modules' => 'Modules directory',
'dir_modules_pending' => 'Modules pending directory',
'dir_plugins' => 'Plugins directory',
'dir_plugins_pending' => 'Plugins pending directory',
'dir_templates' => 'Templates directory',
'dir_templates_pending' => 'Templates pending directory',
// save-extensions.php i18n keys
'log_extensions_selected' => 'Extension selection complete: :admin admin template(s), :user user template(s), :modules module(s), :plugins plugin(s)',
'log_extensions_saved' => 'Extension selection has been saved.',
'error_admin_template_required' => 'Please select at least one admin template.',
// Core update settings
'core_update_settings' => 'Core Update Settings (Optional)',
'core_update_pending_path' => 'Update Pending Directory Path',
'core_update_pending_path_help' => 'Leave empty to use the default (storage/app/core_pending). Enter an absolute path or a path relative to the Gnuboard7 root to use a custom location.',
'core_update_github_url' => 'GitHub Repository URL',
'core_update_github_url_help' => 'GitHub repository URL to check for core updates.',
'core_update_github_token' => 'GitHub Access Token',
'core_update_github_token_help' => 'A GitHub Personal Access Token is required for private repositories. Leave empty for public repositories.',
'check_core_pending_path' => 'Check Path',
'dir_core_pending' => 'Core update pending directory',
'core_pending_will_be_created' => 'Directory does not exist. It will be created automatically during installation.',
'core_pending_path_ok' => 'Path is valid.',
'core_pending_info' => 'Owner: :owner, Group: :group, Permissions: :permissions',
'error_core_pending_not_directory' => 'The specified path is not a directory.',
'error_core_pending_not_writable' => 'Directory (:path) is not writable.',
'error_core_pending_parent_not_writable' => 'Parent directory (:path) is not writable, cannot create automatically.',
'error_path_required' => 'Please enter a path.',
// PHP CLI / Composer Settings
'php_cli_settings' => 'PHP CLI Settings (Optional)',
'php_cli_settings_required' => 'PHP CLI Settings (Required)',
'php_cli_settings_help' => 'If PHP CLI is not in the system PATH or has a different version on your hosting environment, you can specify the path directly. No changes needed for typical environments.',
'php_cli_settings_help_required' => 'The default php command is not available on this server. Please specify the correct PHP CLI path and verify it.',
'php_binary_path' => 'PHP CLI Path',
'php_binary_path_help' => 'e.g. /usr/local/php82/bin/php (default: php)',
'composer_binary_path' => 'Composer Path',
'composer_binary_path_help' => 'Leave empty to auto-detect from system PATH. .phar file paths are also supported.',
'verify_version' => 'Verify Version',
'auto_detect_php' => 'Auto-detect PHP',
'detecting_php' => 'Scanning for PHP binaries...',
'detected_php_binaries' => 'Detected PHP binaries (click to select):',
'no_php_detected' => 'No PHP binaries found on this server.',
'php_detected_count' => ':count PHP binary(ies) found.',
'success_php_binary_version' => ':path — PHP :version ✓',
'error_php_path_empty' => 'PHP binary path is empty.',
'error_php_path_not_exists' => 'File does not exist: :path',
'error_php_exec_failed' => 'PHP execution failed: :path',
'error_php_version_too_low' => ':path — PHP :version (minimum :min required)',
'error_php_version_parse_failed' => 'Failed to parse PHP version.',
'error_php_cli_not_verified' => 'PHP CLI path has not been verified. Please click the "Verify Version" button.',
'error_composer_not_verified' => 'Composer execution has not been verified. Please click the "Verify Version" button.',
'error_composer_path_not_exists' => 'File does not exist: :path',
'error_composer_exec_failed' => 'Composer execution failed: :path',
'error_composer_version_parse_failed' => 'Failed to parse Composer version.',
'success_composer_version' => ':path — Composer :version ✓',
'composer_install_guide_title' => 'Composer Installation Guide',
'composer_install_guide_message' => 'Composer is not installed. You can install it using the following methods:',
'composer_install_guide_global' => 'Global installation (recommended):',
'composer_install_guide_local' => 'Local installation (project directory):',
'composer_install_guide_hosting' => 'Hosting environment installation (if above methods fail):',
'composer_install_guide_pwd_hint' => 'After installation, check the absolute path of the current directory with the command below:',
'composer_install_guide_phar_hint' => 'Enter the full execution command with absolute path in the Composer path field above. Example: /usr/local/php84/bin/php /home/user/g7/composer.phar',
'composer_install_guide_link' => 'For detailed instructions, visit <a href="https://getcomposer.org/download/" target="_blank" rel="noopener">getcomposer.org</a>.',
'composer_checking' => 'Checking Composer...',
'cli_status_checking' => 'Checking...',
'cli_status_verified' => '✓ Verified',
'cli_status_not_verified' => '✗ Not verified',
// Environment Check Enhancements
'required_functions' => 'Required Functions',
'required_functions_available' => 'Available',
'required_functions_disabled' => ':count disabled',
'success_required_functions' => 'Required functions (exec, proc_open, shell_exec) are all available.',
'error_disabled_functions' => 'The following functions are disabled and installation cannot proceed: :functions. Please ask your hosting provider to enable them.',
'php_cli_version' => 'PHP CLI Version',
'php_cli_version_check_skipped' => 'exec function is disabled, CLI version check skipped.',
'php_cli_version_unknown' => 'Unable to determine PHP CLI version.',
'php_cli_version_matched' => 'Matched (Web: :web, CLI: :cli)',
'php_cli_version_mismatch' => 'Mismatch (Web: :web, CLI: :cli)',
'php_cli_version_mismatch_hint' => 'Please specify the correct PHP CLI path in Step 3.',
'success_core_pending_path' => 'Path is valid and writable.',
// Combined .env guidance
'required_files_fix_guide_combined' => '.env file creation and permission setup required. Run the following command:',
// Relative path alternative
'or_relative_path' => 'Or from the G7 root directory:',
];
?>
+785
View File
@@ -0,0 +1,785 @@
<?php
// /install/lang/ko.php
return [
// 공통
'next' => '다음',
'previous' => '이전',
'install' => '설치하기',
'cancel' => '취소',
'yes' => '예',
'no' => '아니오',
'loading' => '로딩 중...',
'saving' => '저장 중...',
'save_failed' => '저장 실패',
'error' => '오류',
// Step 0: 환영
'welcome_title' => '그누보드7 시작하기',
'welcome_desc' => '그누보드7에 오신 것을 환영합니다. 이곳은 설치 첫 단계이며,<br>순서대로 안내를 따라 하시면 필요한 환경 설정을 빠르고 안정적으로 완료하실 수 있습니다.',
'select_language' => '언어를 선택하세요',
'storage_permission_check' => '디렉토리 권한 체크',
'storage_permission_required' => 'Storage 폴더 권한 설정 필요',
'storage_permission_failed' => 'Storage 폴더 권한이 부족합니다',
'storage_not_exists' => 'Storage 폴더가 없습니다',
'storage_not_exists_message' => 'Storage 폴더가 존재하지 않습니다. 프로젝트 루트에 storage 폴더를 생성해주세요.',
'storage_not_writable' => 'Storage 폴더 쓰기 권한 없음',
'storage_not_writable_message' => 'Storage 폴더에 쓰기 권한이 없습니다. 폴더 소유자 또는 그룹 권한을 확인해주세요.',
'storage_permission_guide' => 'Storage 폴더에 <strong>:permissions</strong> 권한을 부여해주세요.',
'storage_permission_guide_detail' => '아래 명령어를 실행하거나 FTP를 통해 권한을 변경하세요:',
'storage_permission_command_linux' => 'chmod -R :permissions :path',
'current_owner' => '현재 소유자',
'current_group' => '현재 소유그룹',
'current_permissions' => '현재 권한',
'required_permissions' => '필요 권한',
'unknown' => '알 수 없음',
'recheck_permission' => '다시 확인',
'permission_checking' => '권한 확인 중...',
// Step 1: 라이선스
'license_title' => '라이선스 동의',
'license_agreement' => '라이선스 약관',
'i_agree' => '위 라이선스 약관에 동의합니다',
'must_agree' => '계속하려면 라이선스에 동의해 주십시오.',
'license_not_found' => '라이선스 정보를 찾을 수 없습니다.',
// Step 2: 설치 환경 확인
'checking_requirements' => '서버 요구사항을 확인하는 중...',
'php_version' => 'PHP 버전',
'php_modules' => 'PHP 모듈',
'directory_permissions' => '디렉토리 권한',
'disk_space' => '디스크 공간',
'https_enabled' => 'HTTPS 활성화',
'required' => '필수',
'enabled' => '활성화됨',
'not_enabled' => '비활성화됨',
'recommended' => '권장사항',
'needs_fix' => '수정 필요',
'requirements_check_failed' => '요구사항 검증 실패',
'all_requirements_met' => '모든 요구사항이 충족되었습니다.',
'some_requirements_failed' => '일부 요구사항이 충족되지 않았습니다. 서버 설정을 확인하세요.',
'recheck' => '다시 검증',
'requirements_not_met' => '필수 요구사항을 충족하지 못했습니다. 환경을 확인하고 다시 시도해주세요.',
'badge_required' => '필수',
'badge_optional' => '선택',
'or_above' => '이상',
'fix_permission' => '쓰기 권한 부족',
'including_subdirectories' => '하위 포함',
'and_more' => '외 :count개',
'error_php_version' => 'PHP 버전',
'error_missing_extensions' => '필수 PHP 확장 미설치',
'error_disk_space' => '디스크 공간',
'error_directory_permissions' => '디렉토리 쓰기 권한 부족',
'error_required_files' => '필수 파일 누락',
'required_files' => '필수 파일',
'file_exists' => '존재',
'file_missing' => '누락',
'file_not_writable' => '쓰기 불가',
'required_files_fix_guide' => '아래 명령어를 프로젝트 루트에서 실행하세요:',
'minimum' => '최소',
'required_text' => '필요',
// Step 3: 설정
'database_settings' => '데이터베이스 설정',
'database_type' => '데이터베이스 타입',
'db_host' => '데이터베이스 호스트',
'db_port' => '포트',
'db_name' => '데이터베이스 이름',
'db_username' => '사용자명',
'db_password' => '비밀번호',
'db_prefix' => '테이블 접두사',
'db_prefix_hint' => '모든 테이블명 앞에 붙는 접두사입니다. (예: g7_users, g7_posts)',
'db_prefix_placeholder' => 'g7_',
'test_write_db_connection' => 'Write DB 연결 테스트',
'test_read_db_connection' => 'Read DB 연결 테스트',
'use_read_db' => 'Read DB 설정 사용',
'database_settings_read' => '데이터베이스 설정 (Read DB) - 선택사항',
'site_settings' => '사이트 설정',
'app_name' => '사이트 이름',
'app_url' => '사이트 URL',
'admin_account' => '관리자 계정',
'admin_name' => '관리자 이름',
'admin_language' => '관리자 언어',
'admin_email' => '관리자 이메일',
'admin_password' => '관리자 비밀번호',
'admin_password_confirm' => '비밀번호 확인',
'start_installation' => '설치 시작',
// Step 5: 설치
'installation_title' => '설치 진행 중',
'installation_in_progress' => '그누보드7을 설치하고 있습니다. 잠시만 기다려 주세요...',
'installation_in_progress_message' => '설치가 진행 중입니다. 설치 화면으로 이동합니다.',
'overall_progress' => '전체 진행률',
'preparing' => '준비 중...',
'waiting_installation' => '설치 시작을 기다리는 중...',
'processing' => '처리 중...',
'installation_complete' => '설치 완료',
'installation_failed' => '설치 실패',
'retry_installation' => '재시도',
'do_not_close_page' => '설치가 완료될 때까지 페이지를 닫지 마세요.',
'installation_log' => '설치 로그',
'hide_log' => '로그 숨기기',
'show_log' => '로그 보기',
'back_to_settings' => '설정으로 돌아가기',
'progress_status' => '설치 목록',
'hide_progress' => '설치 목록 숨기기',
'show_progress' => '설치 목록 보기',
'installation_completed' => '설치가 완료되었습니다!',
'recommendations' => '설치 후 권장사항',
'recommendation_env_permission' => '.env 파일 권한을 600 또는 644로 설정하세요',
'recommendation_https' => '프로덕션 환경에서는 반드시 HTTPS를 사용하세요',
// Step 5: 완료
'installation_info' => '설치 정보',
'installation_complete_message' => '그누보드7이 성공적으로 설치되었습니다!',
'site_url' => '사이트 URL',
'installed_at' => '설치 완료 일시',
'go_to_admin_login' => '관리자 로그인',
// 재진입
'completed_tasks' => '완료된 작업',
'interrupted_task' => '중단된 작업',
'pending_tasks' => '미완료 작업',
'interrupted_during_execution' => '진행 중 중단됨',
'resume_continue' => '계속 진행',
'installation_resuming' => '설치 재개',
// 에러 메시지 - 공통
'error_occurred' => '오류가 발생했습니다',
'please_try_again' => '다시 시도해 주세요.',
'invalid_input' => '입력값이 올바르지 않습니다.',
// 에러 메시지 - 검증 (데이터베이스)
'error_db_host_required' => '데이터베이스 호스트는 필수입니다.',
'error_db_name_required' => '데이터베이스 이름은 필수입니다.',
'error_db_username_required' => '데이터베이스 사용자명을 입력해주세요.',
'error_db_credentials_required' => '데이터베이스명과 사용자명은 필수입니다.',
'error_db_connection_failed' => '데이터베이스 연결에 실패했습니다.',
'error_db_privileges_insufficient' => '데이터베이스에 필요한 권한이 부족합니다.',
'error_db_not_tested' => '데이터베이스 연결 테스트를 먼저 수행해주세요.',
'error_write_db_not_tested' => 'Write DB 연결 테스트를 먼저 수행해주세요.',
'error_read_db_not_tested' => 'Read DB 연결 테스트를 먼저 수행해주세요.',
// 에러 메시지 - 검증 (데이터베이스) (상세)
'error_db_privileges_insufficient_detail' => ':type 데이터베이스에 필요한 권한이 부족합니다: :missing',
'error_db_connection_failed_detail' => ':type 데이터베이스 연결 실패: :error',
'error_db_test_failed' => '데이터베이스 테스트 중 오류 발생',
// 에러 메시지 - 검증 (관리자 계정)
'error_admin_email_invalid' => '유효한 이메일 주소를 입력해주세요.',
'error_admin_language_invalid' => '올바른 언어를 선택해주세요.',
'error_admin_name_required' => '관리자 이름을 입력해주세요.',
'error_admin_password_required' => '관리자 비밀번호를 입력해주세요.',
'error_admin_password_min' => '비밀번호는 최소 8자 이상이어야 합니다.',
'error_admin_password_confirm_required' => '비밀번호 확인을 입력해주세요.',
'error_password_mismatch' => '비밀번호가 일치하지 않습니다.',
'error_app_name_required' => '사이트 이름을 입력해주세요.',
'error_app_url_required' => '사이트 URL을 입력해주세요.',
'error_field_required' => '이 필드는 필수입니다.',
// 에러 메시지 - 시스템 (요구사항)
'error_requirements_check_failed' => '요구사항 검증 중 오류가 발생했습니다.',
'error_php_version_insufficient' => 'PHP 버전이 요구사항을 충족하지 않습니다.',
'error_php_extensions_missing' => '일부 필수 PHP 확장이 설치되어 있지 않습니다.',
'error_disk_space_insufficient' => '디스크 공간이 부족합니다.',
'error_disk_space_unknown' => '디스크 공간을 확인할 수 없습니다.',
'error_directory_not_writable' => '일부 디렉토리에 쓰기 권한이 없습니다.',
// 에러 메시지 - 시스템 (요구사항) (상세)
'error_php_version_insufficient_detail' => 'PHP 버전이 요구사항을 충족하지 않습니다. (현재: :current, 요구: :min+)',
'error_disk_space_insufficient_detail' => '디스크 공간이 부족합니다. (현재: :current MB, 요구: :min MB)',
'error_directory_not_writable_detail' => '일부 디렉토리에 쓰기 권한이 없습니다. 권한을 :permissions로 설정해주세요.',
'error_required_files_missing' => '필수 파일이 누락되었습니다.',
'error_step_file_not_found' => '단계 파일을 찾을 수 없습니다. 설치 파일이 손상되었을 수 있습니다.',
'error_state_file_creation_failed' => '설치 상태 파일(state.json)을 생성할 수 없습니다. storage/installer 디렉토리의 쓰기 권한을 확인해주세요.',
'error_invalid_step_access' => '올바르지 않은 단계 접근입니다',
'error_invalid_step_access_message' => '올바른 설치 순서대로 진행해주세요.',
// 성공 메시지 - 데이터베이스
'success_db_write_connected' => 'Write 데이터베이스 연결 및 권한 검증에 성공했습니다.',
'success_db_read_connected' => 'Read 데이터베이스 연결 및 권한 검증에 성공했습니다.',
// 성공 메시지 - 요구사항
'success_requirements_met' => '모든 요구사항이 충족되었습니다.',
'success_php_version' => 'PHP 버전이 요구사항을 충족합니다.',
'success_php_extensions' => '모든 필수 PHP 확장이 설치되어 있습니다.',
'success_disk_space' => '디스크 공간이 충분합니다.',
'success_directories_writable' => '모든 디렉토리가 쓰기 가능합니다.',
'success_required_files' => '필수 파일이 모두 존재합니다.',
// 성공 메시지 - 요구사항 (상세)
'success_php_version_detail' => 'PHP 버전이 요구사항을 충족합니다. (현재: :current, 요구: :min+)',
'success_disk_space_detail' => '디스크 공간이 충분합니다. (현재: :current MB, 요구: :min MB)',
// HTTPS 메시지
'https_enabled' => 'HTTPS가 활성화되어 있습니다. (권장)',
'https_disabled' => 'HTTPS가 비활성화되어 있습니다. 보안을 위해 HTTPS 사용을 권장합니다.',
// API 응답 메시지
'api_method_not_allowed' => 'POST 요청만 허용됩니다.',
'api_invalid_request' => '잘못된 요청 데이터입니다.',
'api_unexpected_error' => '예상치 못한 오류가 발생했습니다.',
// 단계명 (헬퍼 함수용)
'step_0_welcome' => '환영',
'step_1_license' => '라이선스 동의',
'step_2_requirements' => '설치 환경 확인',
'step_3_configuration' => '설치 정보 입력',
'step_4_extension_selection' => '확장 기능 선택',
'step_5_installation' => '설치 진행',
'step_6_complete' => '완료',
'step_unknown' => '알 수 없는 단계',
// 작업명 (헬퍼 함수용)
'task_composer_check' => '패키지 관리자 확인',
'task_composer_install' => '필수 패키지 설치',
'task_env_create' => '환경 설정 파일 생성',
'task_env_update' => '환경 설정 파일 업데이트',
'task_key_generate' => '보안 키 생성',
'task_db_migrate' => '데이터베이스 테이블 생성',
'task_db_seed' => '기본 데이터 생성',
'task_template_install' => '관리자 템플릿 설치',
'task_template_activate' => '관리자 템플릿 활성화',
'task_module_install' => '모듈 설치',
'task_module_activate' => '모듈 활성화',
'task_plugin_install' => '플러그인 설치',
'task_plugin_activate' => '플러그인 활성화',
'task_user_template_install' => '사용자 템플릿 설치',
'task_user_template_activate' => '사용자 템플릿 활성화',
'task_cache_clear' => '임시 파일 정리',
'task_create_settings_json' => '설정 파일 생성',
'task_complete_flag' => '설치 완료 처리',
'task_unknown' => '알 수 없는 작업',
// 작업 그룹명
'task_group_environment' => '환경 설정',
'task_group_database' => '데이터베이스',
'task_group_admin_templates' => '관리자 템플릿',
'task_group_modules' => '모듈',
'task_group_plugins' => '플러그인',
'task_group_user_templates' => '사용자 템플릿',
'task_group_finalize' => '마무리',
// 그룹 상태 레이블
'status_pending' => '대기',
'status_in_progress' => '진행 중',
'status_completed' => '완료',
'status_failed' => '실패',
'status_aborted' => '중단',
// 에러 메시지 - Worker (Composer)
'error_composer_not_installed' => 'Composer가 설치되어 있지 않습니다.',
'error_composer_install_failed' => 'Composer 의존성 설치에 실패했습니다',
// 로그 메시지 - Worker (Composer)
'log_composer_check_success' => 'Composer 확인 완료',
'log_composer_already_installed' => 'Composer 의존성이 이미 설치되어 있습니다',
'log_composer_install_success' => 'Composer 의존성 설치 완료',
'log_composer_vendor_without_lock' => 'vendor 디렉토리는 있지만 composer.lock 파일이 없습니다 (불완전 상태)',
'log_composer_removing_vendor' => 'vendor 디렉토리를 삭제하고 재설치합니다...',
'log_composer_vendor_deleted' => 'vendor 디렉토리 삭제 완료',
'log_composer_vendor_delete_failed' => 'vendor 디렉토리 삭제 실패 (계속 진행합니다)',
'log_composer_installing_from_lock' => 'composer.lock 파일을 사용하여 의존성을 설치합니다...',
'log_composer_fresh_install' => '새로운 Composer 의존성을 설치합니다...',
'log_composer_cache_cleared' => '이전 패키지 캐시를 삭제했습니다',
// 에러 메시지 - Worker (.env)
'error_env_example_not_found' => '.env.example 파일을 찾을 수 없습니다',
'error_env_create_failed' => '.env 파일 생성에 실패했습니다',
'error_env_not_found' => '.env 파일이 존재하지 않습니다.',
// 로그 메시지 - Worker (.env)
'log_env_create_success' => '.env 파일 생성 완료',
'log_env_update_success' => '.env 파일 업데이트 완료',
'log_env_readonly_skip' => '.env 파일에 쓰기 권한이 없어 업데이트를 건너뜁니다.',
'log_env_flag_skipped' => '.env 파일에 쓰기 권한이 없어 설치 완료 플래그를 건너뜁니다.',
// 에러 메시지 - Worker (Key)
'error_key_generate_failed' => 'Application Key 생성에 실패했습니다',
// 로그 메시지 - Worker (Key)
'log_key_generate_success' => 'Application Key 생성 완료',
// 에러 메시지 - Worker (Database)
'error_db_migrate_failed' => '데이터베이스 테이블 생성에 실패했습니다',
'error_db_seed_failed' => '기본 데이터 입력에 실패했습니다',
// 로그 메시지 - Worker (Database)
'log_db_migrate_success' => '데이터베이스 마이그레이션 완료',
'log_db_seed_success' => '데이터베이스 시딩 완료',
// 에러 메시지 - Worker (Template)
'error_template_install_failed' => '템플릿 설치에 실패했습니다',
'error_template_activate_failed' => '템플릿 활성화에 실패했습니다',
// 로그 메시지 - Worker (Template)
'log_template_install_success' => '템플릿 설치 완료',
'log_template_activate_success' => '템플릿 활성화 완료',
// 에러 메시지 - Worker (Module)
'error_module_install_failed' => '모듈 설치에 실패했습니다',
'error_module_activate_failed' => '모듈 활성화에 실패했습니다',
// 로그 메시지 - Worker (Module)
'log_module_install_success' => '모듈 설치 완료',
'log_module_activate_success' => '모듈 활성화 완료',
// 에러 메시지 - Worker (Plugin)
'error_plugin_install_failed' => '플러그인 설치에 실패했습니다',
'error_plugin_activate_failed' => '플러그인 활성화에 실패했습니다',
// 로그 메시지 - Worker (Plugin)
'log_plugin_install_success' => '플러그인 설치 완료',
'log_plugin_activate_success' => '플러그인 활성화 완료',
// 에러 메시지 - Worker (User Template)
'error_user_template_install_failed' => '사용자 템플릿 설치에 실패했습니다',
'error_user_template_activate_failed' => '사용자 템플릿 활성화에 실패했습니다',
// 로그 메시지 - Worker (User Template)
'log_user_template_install_success' => '사용자 템플릿 설치 완료',
'log_user_template_activate_success' => '사용자 템플릿 활성화 완료',
// 에러 메시지 - Worker (Cache)
'error_cache_clear_failed' => '캐시 클리어에 실패했습니다',
// 로그 메시지 - Worker (Cache)
'log_cache_clear_success' => '캐시 클리어 완료',
// 에러 메시지 - Worker (Settings JSON)
'error_settings_json_failed' => '설정 파일 생성에 실패했습니다',
// 로그 메시지 - Worker (Settings JSON)
'log_creating_settings' => '설정 JSON 파일 생성 중...',
'log_settings_json_created' => '설정 JSON 파일 생성 완료',
// 에러 메시지 - Worker (Admin)
'error_autoload_not_found' => 'vendor/autoload.php 파일을 찾을 수 없습니다',
'error_app_bootstrap_not_found' => 'bootstrap/app.php 파일을 찾을 수 없습니다',
// 로그 메시지 - Worker (Complete)
'log_complete_flag_success' => '설치 완료 플래그 설정 완료',
'log_installation_completed' => '설치가 성공적으로 완료되었습니다',
'log_installation_failed' => '설치 실패',
'log_installation_task_failed' => '[실패] :task: :message',
'log_installation_exception' => '[실패] 설치 중 오류 발생: :error',
// Worker 로그 메시지 (작업 진행)
'log_task_in_progress' => ':task 작업 중...',
'log_task_completed' => ':task 작업 완료',
'log_task_skipped' => ':task (이미 존재하여 건너뜀)',
'manual_commands_guide' => '💡 아래 명령어를 수동으로 실행할 수 있습니다:',
'log_separator' => '========================================',
'log_error_occurred' => '❌ 오류 발생: :error',
'log_env_file_created' => '.env 파일 생성 완료',
'log_env_flag_added' => '.env 파일에 설치 완료 플래그 추가',
'log_installed_flag_created' => 'g7_installed 플래그 파일 생성',
'log_state_updated' => '설치 상태 업데이트 완료',
'log_all_tasks_completed' => '🎉 모든 설치 작업이 완료되었습니다!',
'log_already_completed' => ':task (이미 완료됨)',
// Worker 중단 관련 메시지
'abort_connection_lost' => '[중단] 브라우저 연결이 끊어졌습니다.',
'abort_rollback_start' => "[중단] 현재 작업 ':task' 롤백을 시작합니다.",
'abort_rollback_success' => '[중단] 롤백 완료: :message',
'abort_rollback_failed' => '[중단] 롤백 실패: :message (계속 진행)',
'abort_no_rollback_needed' => '[중단] 롤백할 작업이 없습니다. (current_task가 null이거나 이미 완료됨)',
'abort_by_user' => "[중단] 사용자가 설치를 중단했습니다. (현재 작업: :task)",
'abort_installation_stopped' => '설치가 중단되었습니다.',
// Worker 실패 시 롤백 관련 메시지
'failed_rollback_start' => "[실패] 실패한 작업 ':task' 롤백을 시작합니다.",
'failed_rollback_success' => '[실패] 롤백 완료: :message',
'failed_rollback_failed' => '[실패] 롤백 실패: :message',
'failed_rollback_manual_cleanup' => '[안내] 롤백에 실패했습니다. 데이터베이스를 수동으로 정리한 후 다시 설치를 시도해주세요.',
'failed_rollback_manual_cleanup_detail' => '데이터베이스 관리 도구(phpMyAdmin 등)를 사용하여 생성된 테이블을 삭제하거나, 데이터베이스를 초기화한 후 다시 설치를 진행하세요.',
'failed_rollback_db_restart' => '[안내] 데이터베이스가 롤백되었습니다. 재시도 시 데이터베이스 설치부터 다시 진행됩니다.',
'failed_rollback_retry' => '[안내] 작업에 실패했습니다. 설치를 다시 시도해주세요.',
'failed_rollback_retry_detail' => '재시도 시 실패한 작업부터 다시 진행됩니다. 문제가 지속되면 수동 명령어를 참고하세요.',
// Worker SSE 연결 메시지
'sse_connection_established' => 'SSE 연결이 설정되었습니다',
'sse_method_not_allowed' => '허용되지 않는 메서드입니다. SSE는 GET 요청이 필요합니다.',
// DB 작업 중 중단 불가 메시지
'db_task_no_abort' => '데이터베이스 작업 중에는 중단할 수 없습니다. 작업 완료 후 중단됩니다.',
'db_task_in_progress' => '데이터베이스 작업 중...',
// Worker 에러 상세 메시지
'error_composer_process_failed' => 'Composer 설치 프로세스 시작 실패',
'error_composer_exit_code' => 'Composer 설치 실패 (종료 코드: :code)',
'error_env_example_not_found_detail' => '.env.example 파일을 찾을 수 없습니다: :path',
'error_env_write_failed' => '.env 파일 쓰기 실패: :path',
'error_complete_flag_failed' => '설치 완료 플래그 설정 실패',
'error_unexpected_exception' => '예기치 않은 오류가 발생했습니다',
// install-process.php 메시지
'error_method_not_allowed' => 'POST 요청만 허용됩니다.',
'error_config_not_in_session' => '설정 정보가 세션에 없습니다. Step 3에서 설정을 먼저 완료해주세요.',
'error_required_fields_missing' => '필수 설정 항목이 누락되었습니다: :fields',
'log_installation_config_saved' => '설치 설정 저장 완료 - SSE 연결 대기 중',
'success_installation_started' => '설치가 시작되었습니다.',
'error_installation_start_failed' => '설치 프로세스 시작 실패',
'error_installation_start_exception' => '설치 시작 중 오류가 발생했습니다: :error',
// get-install-state.php 메시지
'error_get_method_required' => 'GET 요청만 허용됩니다.',
'error_state_query_failed' => '설치 상태 조회 중 오류가 발생했습니다.',
// 새로고침/페이지 이탈 경고 (브라우저가 기본 메시지로 표시하지만, 의도 명확화)
'confirm_leave_installation' => '설치가 진행 중입니다. 페이지를 나가면 설치에 문제가 발생할 수 있습니다.',
'confirm_resume_installation' => '설치가 진행 중이었습니다. 설치를 재개하시겠습니까?',
'resume_installation_btn' => '설치 재개',
'cancel_installation_btn' => '취소',
// 설치 완료 후 재접근 메시지
'installation_already_completed' => '설치 완료',
'installation_already_completed_message' => '그누보드7이 이미 설치되었습니다. 홈페이지로 이동합니다.',
// URL 파라미터 접근 메시지
'url_parameter_not_supported' => 'URL 파라미터 사용 불가',
'url_parameter_redirect_message' => '설치 과정은 세션 기반으로 관리됩니다. 요청하신 Step :requested 대신 현재 진행 중인 Step :current(으)로 이동합니다.',
// 설치 중단 관련
'abort_installation' => '설치 중단',
'aborting' => '중단 중',
'confirm_abort_installation' => '정말 설치를 중단하시겠습니까? 중단 시 현재까지의 설치 내용은 유지되며, 나중에 중단된 지점부터 다시 시작할 수 있습니다.',
'installation_aborted' => '설치가 중단되었습니다',
'installation_aborted_message' => '설치 도중 브라우저가 닫혔거나 새로고침되었습니다. 중단된 지점부터 다시 설치할 수 있습니다.',
'clean_state' => '상태 초기화',
'cleaning' => '초기화 중',
'state_cleaned' => '상태가 초기화되었습니다',
'clean_failed' => '초기화 실패',
'clean_error' => '초기화 중 오류 발생',
'resuming' => '재개 중',
'resume_failed' => '재개 실패',
'resume_error' => '재개 중 오류 발생',
'abort_failed' => '중단 실패',
'abort_error_occurred' => '중단 중 오류 발생',
// 검증 에러 메시지 (validation.php)
'validation_required' => ':field은(는) 필수 항목입니다.',
'validation_email' => ':field의 형식이 올바르지 않습니다.',
'validation_min' => ':field은(는) 최소 :min자 이상이어야 합니다.',
'validation_max' => ':field은(는) 최대 :max자까지 입력 가능합니다.',
'validation_url' => ':field은(는) 올바른 URL 형식이어야 합니다.',
'validation_alpha_num' => ':field은(는) 영문자와 숫자만 입력 가능합니다.',
'validation_alpha_num_underscore' => ':field은(는) 영문 소문자, 숫자, 언더스코어(_)만 입력 가능합니다.',
'validation_starts_with_alpha' => ':field은(는) 영문 소문자로 시작해야 합니다.',
'validation_confirmed' => ':field 확인이 일치하지 않습니다.',
'validation_numeric' => ':field은(는) 숫자여야 합니다.',
'validation_integer' => ':field은(는) 정수여야 합니다.',
'validation_in' => ':field은(는) 다음 중 하나여야 합니다: :values',
// 필드명 레이블 (validation.php)
'fields' => [
'db_host' => '데이터베이스 호스트',
'db_port' => '데이터베이스 포트',
'db_database' => '데이터베이스명',
'db_username' => '데이터베이스 사용자명',
'db_password' => '데이터베이스 비밀번호',
'db_write_host' => 'Write 데이터베이스 호스트',
'db_write_port' => 'Write 데이터베이스 포트',
'db_write_database' => 'Write 데이터베이스명',
'db_write_username' => 'Write 데이터베이스 사용자명',
'db_write_password' => 'Write 데이터베이스 비밀번호',
'db_prefix' => '테이블 접두사',
'db_read_host' => 'Read 데이터베이스 호스트',
'db_read_port' => 'Read 데이터베이스 포트',
'db_read_database' => 'Read 데이터베이스명',
'db_read_username' => 'Read 데이터베이스 사용자명',
'db_read_password' => 'Read 데이터베이스 비밀번호',
'app_name' => '사이트 이름',
'app_url' => '사이트 URL',
'admin_name' => '관리자 이름',
'admin_language' => '관리자 언어',
'admin_email' => '관리자 이메일',
'admin_password' => '관리자 비밀번호',
'admin_password_confirmation' => '관리자 비밀번호 확인',
'email' => '이메일',
'password' => '비밀번호',
'password_confirmation' => '비밀번호 확인',
],
// JavaScript 클라이언트 메시지 (installer.js)
'testing_connection' => '연결을 테스트하는 중...',
'connection_failed_prefix' => '연결 실패:',
'validation_incomplete_alert' => '필수 항목을 모두 입력하고 DB 연결 테스트를 완료해주세요.',
'validation_incomplete_title' => '다음 항목을 완료해주세요:',
'confirm_leave_page' => '설정이 저장되지 않았습니다. 페이지를 나가시겠습니까?',
'installation_in_progress_alert' => '설치가 진행 중입니다. 설정 페이지로 돌아가시겠습니까?',
'confirm_go_to_settings' => "설정 페이지로 이동하시겠습니까?",
'confirm_go_to_settings_simple' => "설정 페이지로 이동하시겠습니까?\n\n설치 상태가 초기화되며, 모든 작업이 처음부터 다시 실행됩니다.\n\n⚠️ 데이터베이스에 생성된 테이블은 자동으로 삭제되지 않습니다.\n필요 시 phpMyAdmin 등을 통해 수동으로 정리해주세요.",
'confirm_go_to_settings_title' => '설정 페이지로 이동',
'confirm_go_to_settings_desc' => '설치 상태가 초기화되며, 모든 작업이 처음부터 다시 실행됩니다.\n\n⚠️ 데이터베이스에 생성된 테이블은 자동으로 삭제되지 않습니다. 필요 시 phpMyAdmin 등을 통해 수동으로 정리해주세요.',
'confirm_go_to_settings_btn' => '이동',
'reset_db_checkbox_label' => '데이터베이스 초기화 (생성된 테이블 삭제)',
'error_state_reset_failed' => '상태 초기화에 실패했습니다.\n\n:message\n\n페이지를 새로고침 후 다시 시도해주세요.',
'confirm_force_go_to_settings' => '상태 초기화 중 오류가 발생했습니다.\n\n그래도 설정 페이지로 이동하시겠습니까?',
'view_error_details' => '오류 상세 보기',
'installation_error_occurred' => '설치 중 오류가 발생했습니다.',
'installation_start_error' => '설치 시작 중 오류 발생',
'installation_start_failed' => '설치를 시작할 수 없습니다.',
'unknown_error_occurred' => '알 수 없는 오류가 발생했습니다.',
// SSE 연결 실패 메시지
'sse_connection_timeout' => 'SSE 실시간 연결에 실패했습니다. 서버 설정을 확인하거나 페이지를 새로고침해주세요.',
'sse_server_config_guide' => '서버 관리자이신 경우 아래 설정을 확인해주세요:
[Nginx 설정]
location /install/api/ {
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 600s;
}
[Apache 설정]
# .htaccess 또는 httpd.conf
<Location /install/api/>
SetEnv no-gzip 1
</Location>
[PHP 설정]
// install-worker-sse.php 최상단에 추가
ini_set(\'output_buffering\', \'off\');
ini_set(\'zlib.output_compression\', \'off\');
@apache_setenv(\'no-gzip\', 1);
[공유 호스팅]
호스팅 제공업체에 SSE(Server-Sent Events) 지원 여부를 문의해주세요.
방화벽이나 프록시에서 long-lived HTTP 연결을 차단하고 있을 수 있습니다.',
// 다크모드
'toggle_theme' => '테마 전환',
'dark_mode' => '다크 모드',
'light_mode' => '라이트 모드',
// Step 4: 확장 기능 선택
'extension_selection_description' => '설치할 확장 기능을 선택하세요. 관리자 템플릿은 필수 선택입니다.',
'loading_extensions' => '확장 기능을 불러오는 중...',
'admin_templates' => '관리자 템플릿',
'admin_templates_description' => '관리자 페이지에서 사용할 템플릿을 선택하세요.',
'user_templates' => '사용자 템플릿',
'user_templates_description' => '프론트 페이지에서 사용할 템플릿을 선택하세요.',
'modules' => '모듈',
'modules_description' => '설치할 모듈을 선택하세요. 모듈은 게시판, 이커머스 등 주요 기능을 제공합니다.',
'plugins' => '플러그인',
'plugins_description' => '설치할 플러그인을 선택하세요. 플러그인은 결제, 알림 등 부가 기능을 제공합니다.',
'optional' => '선택',
'no_extensions_found' => '사용 가능한 확장이 없습니다.',
'no_user_templates' => '사용 가능한 사용자 템플릿이 없습니다.',
'no_modules' => '사용 가능한 모듈이 없습니다.',
'no_plugins' => '사용 가능한 플러그인이 없습니다.',
'extension_load_failed' => '확장 기능 목록을 불러오는데 실패했습니다.',
'no_admin_template_error' => '관리자 템플릿이 필요하지만 찾을 수 없습니다. templates 디렉토리에 최소 1개 이상의 관리자 템플릿이 있는지 확인해주세요.',
'selection_summary' => '선택 요약',
'selected_count' => ':count개 선택됨',
'admin_template_required' => '관리자 템플릿은 최소 1개 이상 선택해야 합니다.',
'proceed_to_installation' => '설치 진행',
'version' => '버전',
'select' => '선택',
'selected' => '선택됨',
'dependencies' => '의존성',
'dependency_type_module' => '모듈',
'dependency_type_plugin' => '플러그인',
'dependency_type_admin_template' => '관리자 템플릿',
'dependency_type_user_template' => '사용자 템플릿',
'dependency_type_other' => '기타',
'author' => '제작자',
'retry' => '재시도',
'select_all' => '전체 선택',
'deselect_all' => '전체 해제',
// install-worker.php 다국어 키
'db_task_abort_detected_before_start' => '[DB 작업] 시작 전 중단 상태 감지 - 작업을 건너뜁니다.',
'db_task_failed_rollback_start' => '[DB 작업] :task 실패 - 롤백을 시작합니다.',
'db_task_abort_reason_connection' => '연결 끊김',
'db_task_abort_reason_user' => '사용자 요청',
'db_task_completed_abort_detected' => '[DB 작업] :task 완료 후 중단 감지 (:reason) - 롤백을 시작합니다.',
'db_task_completed_rollback_start' => '[중단] :task 완료 후 롤백을 시작합니다.',
'log_removing_state_file' => '인스톨러 상태 파일을 제거합니다...',
'log_state_file_removed' => '인스톨러 상태 파일이 제거되었습니다.',
'log_state_file_remove_failed' => '경고: 인스톨러 상태 파일 제거에 실패했습니다.',
'error_worker_exception' => '설치 워커 SSE 예외 발생',
// rollback-functions.php 다국어 키
'log_prefix_rollback' => '[롤백]',
'log_prefix_force_rollback' => '[강제 롤백]',
'rollback_not_needed_recreatable' => '롤백 불필요 (새로 생성 가능)',
'rollback_not_needed_overwritable' => '롤백 불필요 (재설치/재활성화 시 덮어쓰기 가능)',
'rollback_unknown_task' => '알 수 없는 작업: :task',
'rollback_error' => '[롤백 오류] :task: :error',
'rollback_exception' => '롤백 중 예외 발생: :error',
'rollback_migrate_start' => '마이그레이션 롤백을 시작합니다 (migrate:rollback).',
'rollback_migrate_result' => 'migrate:rollback 실행 결과: :result',
'rollback_migrate_success' => '마이그레이션 롤백 완료',
'rollback_migrate_failed_code' => '마이그레이션 롤백 실패 (returnCode: :code)',
'rollback_migrate_failed' => '마이그레이션 롤백 실패',
'rollback_migrate_error' => '마이그레이션 롤백 중 오류: :error',
'rollback_seed_no_config' => 'DB 설정 정보가 없어 시드 롤백을 건너뜁니다.',
'rollback_seed_already_done' => '시드 이미 완료됨 (롤백 불필요)',
'rollback_seed_interrupted' => '시드가 중단되었습니다. 테이블을 비웁니다.',
'rollback_seed_force_truncate' => '시드 데이터를 무조건 삭제합니다.',
'rollback_table_truncated' => "테이블 ':table'을 비웠습니다.",
'rollback_table_truncate_skipped' => "테이블 ':table' TRUNCATE 건너뜀: :error",
'rollback_seed_data_deleted' => '시드 데이터를 삭제했습니다.',
'rollback_db_connection_failed' => 'DB 연결 실패: :error',
'rollback_db_connection_failed_skip' => 'DB 연결 실패. 시드 롤백을 건너뜁니다.',
'rollback_seed_error' => '시드 처리 중 오류: :error',
'rollback_env_flag_removed' => '.env에서 INSTALLER_COMPLETED를 제거했습니다.',
'rollback_installed_flag_removed' => 'g7_installed 파일을 삭제했습니다.',
'rollback_complete_flag_removed' => '설치 완료 플래그를 제거했습니다: :details',
'rollback_complete_flag_error' => '완료 플래그 제거 중 오류: :error',
'rollback_no_current_task' => '롤백할 현재 작업이 없습니다. (current_task가 null)',
'rollback_task_already_completed' => "':task'은(는) 이미 완료된 작업입니다. (롤백 불필요)",
'rollback_current_task_start' => "[중단] 현재 작업 ':task' 롤백을 시작합니다.",
'rollback_no_completed_tasks' => '롤백할 완료된 작업이 없습니다.',
'rollback_checking_tasks' => '롤백 가능한 작업들을 확인합니다...',
'rollback_no_matching_tasks' => '롤백할 작업이 없습니다. (rollbackable 목록과 매칭되는 작업 없음)',
'rollback_tasks_to_rollback' => '롤백할 작업: :tasks',
'rollback_task_rolling_back' => "':task' 작업을 롤백합니다...",
'rollback_task_success' => "':task' 롤백 성공",
'rollback_task_failed' => "':task' 롤백 실패: :error",
'manual_cmd_settings_json' => 'settings.json은 자동으로 생성됩니다. 설치를 다시 시도하세요.',
// state-management.php 다국어 키
'state_reset_requested' => '설정 페이지로 이동을 요청했습니다.',
'state_reset_db_notice' => 'DB는 자동으로 초기화되지 않습니다. 필요 시 수동으로 정리해주세요.',
'state_save_failed' => '상태 파일 저장에 실패했습니다.',
'state_reset_completed' => '설치 상태가 초기화되었습니다. (Step :step(으)로 이동)',
'abort_api_requested' => '[중단 API] abort 요청됨 - 사용자가 설치 중단 요청',
'abort_api_current_status' => '[중단 API] 현재 installation_status: :status',
'abort_api_current_task' => '[중단 API] 현재 current_task: :task',
'abort_api_completed_count' => '[중단 API] 완료된 작업 수: :count',
'abort_api_already_completed' => '설치가 이미 완료되어 중단할 수 없습니다.',
'abort_api_already_aborted' => '설치가 이미 중단되었습니다.',
'abort_api_not_running' => '중단할 설치가 없습니다.',
'abort_user_requested' => '사용자가 설치 중단을 요청했습니다.',
'abort_api_status_change' => '[중단 API] installation_status를 "aborted"로 변경합니다.',
'abort_api_save_result' => '[중단 API] state.json 저장 결과: :result',
'abort_api_verify_status' => '[중단 API] 저장 후 확인 - installation_status: :status',
'api_method_not_allowed' => '허용되지 않는 메서드입니다.',
'error_state_management' => '상태 관리 오류',
'error_log_prefix' => '[오류] :error',
// functions.php 다국어 키
'error_db_name_username_required' => '데이터베이스 이름과 사용자명은 필수입니다.',
'error_db_connection_failed' => '데이터베이스 연결 실패: :error',
'error_privilege_check_failed' => '권한 검증 중 오류 발생',
// 필수 파일 생성 안내 (Step 5)
'file_setup_title' => '필수 파일 생성',
'file_setup_description' => '설치를 진행하려면 아래 파일이 프로젝트 루트에 필요합니다.',
'file_setup_guide' => '터미널에서 아래 명령어를 프로젝트 루트 디렉토리에서 실행하세요:',
'file_check_button' => '파일 확인',
'file_checking' => '확인 중...',
'files_not_found_yet' => '필수 파일을 아직 찾을 수 없습니다. 파일을 생성한 후 다시 확인해주세요.',
'copy_command' => '복사',
'copied' => '복사됨!',
// Step 2 권한 안내
'permission_fix_guide' => '아래 명령어를 터미널에서 실행하여 권한을 수정하세요:',
'ownership_fix_guide' => '소유자와 그룹을 웹 서버 사용자로 변경하세요:',
'ownership_fix_hint' => '※ www-data는 웹 서버 사용자/그룹입니다. 사용 환경에 따라 nginx, apache 등으로 변경하세요.',
'ownership_detected_hint' => '※ 현재 웹 서버 사용자: :user (자동 감지)',
'permission_windows_hint' => '※ Windows 환경에서는 관리자 권한으로 명령 프롬프트(cmd)를 열고 실행하세요. 또는 폴더 속성 → 보안 탭에서 권한을 설정할 수 있습니다.',
'directory_create_guide' => '아래 명령어를 실행하여 누락된 디렉토리를 생성하세요:',
// 디렉토리명 (Step 2)
'dir_bootstrap_cache' => '부트스트랩 캐시 디렉토리',
'dir_vendor' => '패키지 디렉토리',
'dir_modules' => '모듈 디렉토리',
'dir_modules_pending' => '모듈 대기 디렉토리',
'dir_plugins' => '플러그인 디렉토리',
'dir_plugins_pending' => '플러그인 대기 디렉토리',
'dir_templates' => '템플릿 디렉토리',
'dir_templates_pending' => '템플릿 대기 디렉토리',
// save-extensions.php 다국어 키
'log_extensions_selected' => '확장 기능 선택 완료: 관리자 템플릿 :admin개, 사용자 템플릿 :user개, 모듈 :modules개, 플러그인 :plugins개',
'log_extensions_saved' => '확장 기능 선택이 저장되었습니다.',
'error_admin_template_required' => '관리자 템플릿을 최소 1개 이상 선택해주세요.',
// 코어 업데이트 설정
'core_update_settings' => '코어 업데이트 설정 (선택)',
'core_update_pending_path' => '업데이트 대기 디렉토리 경로',
'core_update_pending_path_help' => '비워두면 기본값(storage/app/core_pending)을 사용합니다. 외부 경로를 사용하려면 절대 경로 또는 그누보드7 루트 기준 상대 경로를 입력하세요.',
'core_update_github_url' => 'GitHub 저장소 URL',
'core_update_github_url_help' => '코어 업데이트를 확인할 GitHub 저장소 URL입니다.',
'core_update_github_token' => 'GitHub 액세스 토큰',
'core_update_github_token_help' => '프라이빗 저장소인 경우 GitHub Personal Access Token이 필요합니다. 공개 저장소인 경우 비워둘 수 있습니다.',
'check_core_pending_path' => '경로 확인',
'dir_core_pending' => '코어 업데이트 대기 디렉토리',
'core_pending_will_be_created' => '디렉토리가 존재하지 않습니다. 설치 시 자동으로 생성됩니다.',
'core_pending_path_ok' => '경로가 유효합니다.',
'core_pending_info' => '소유자: :owner, 그룹: :group, 퍼미션: :permissions',
'error_core_pending_not_directory' => '지정한 경로가 디렉토리가 아닙니다.',
'error_core_pending_not_writable' => '디렉토리(:path)에 쓰기 권한이 없습니다.',
'error_core_pending_parent_not_writable' => '상위 디렉토리(:path)에 쓰기 권한이 없어 자동 생성이 불가합니다.',
'error_path_required' => '경로를 입력해주세요.',
// PHP CLI / Composer 설정
'php_cli_settings' => 'PHP CLI 설정 (선택)',
'php_cli_settings_required' => 'PHP CLI 설정 (필수)',
'php_cli_settings_help' => '호스팅 환경에서 PHP CLI가 시스템 PATH에 없거나 버전이 다른 경우 직접 경로를 지정할 수 있습니다. 일반적인 환경에서는 변경할 필요가 없습니다.',
'php_cli_settings_help_required' => '기본 php 명령어로 PHP CLI를 실행할 수 없습니다. 올바른 PHP CLI 경로를 지정하고 버전을 확인해주세요.',
'php_binary_path' => 'PHP CLI 경로',
'php_binary_path_help' => '예: /usr/local/php82/bin/php (기본값: php)',
'composer_binary_path' => 'Composer 경로',
'composer_binary_path_help' => '비워두면 시스템 PATH에서 자동 탐색합니다. .phar 파일 경로도 지원합니다.',
'verify_version' => '버전 확인',
'auto_detect_php' => 'PHP 자동 감지',
'detecting_php' => 'PHP 바이너리를 탐색 중입니다...',
'detected_php_binaries' => '감지된 PHP 바이너리 (클릭하여 선택):',
'no_php_detected' => '서버에서 PHP 바이너리를 찾을 수 없습니다.',
'php_detected_count' => ':count개의 PHP 바이너리를 발견했습니다.',
'success_php_binary_version' => ':path — PHP :version ✓',
'error_php_path_empty' => 'PHP 바이너리 경로가 비어있습니다.',
'error_php_path_not_exists' => '파일이 존재하지 않습니다: :path',
'error_php_exec_failed' => 'PHP 실행 실패: :path',
'error_php_version_too_low' => ':path — PHP :version (최소 :min 필요)',
'error_php_version_parse_failed' => 'PHP 버전을 파싱할 수 없습니다.',
'error_php_cli_not_verified' => 'PHP CLI 경로가 확인되지 않았습니다. "버전 확인" 버튼을 클릭해주세요.',
'error_composer_not_verified' => 'Composer 실행이 확인되지 않았습니다. "버전 확인" 버튼을 클릭해주세요.',
'error_composer_path_not_exists' => '파일이 존재하지 않습니다: :path',
'error_composer_exec_failed' => 'Composer 실행 실패: :path',
'error_composer_version_parse_failed' => 'Composer 버전을 파싱할 수 없습니다.',
'success_composer_version' => ':path — Composer :version ✓',
'composer_install_guide_title' => 'Composer 설치 안내',
'composer_install_guide_message' => 'Composer가 설치되어 있지 않습니다. 아래 방법으로 설치할 수 있습니다:',
'composer_install_guide_global' => '전역 설치 (권장):',
'composer_install_guide_local' => '로컬 설치 (프로젝트 디렉토리):',
'composer_install_guide_hosting' => '호스팅 환경 설치 (위 방법이 안 될 경우):',
'composer_install_guide_pwd_hint' => '설치 후 아래 명령어로 현재 디렉토리의 절대 경로를 확인하세요:',
'composer_install_guide_phar_hint' => '위 Composer 경로 입력란에 절대 경로를 포함한 전체 실행 명령어를 입력하세요. 예: /usr/local/php84/bin/php /home/user/g7/composer.phar',
'composer_install_guide_link' => '자세한 설치 방법은 <a href="https://getcomposer.org/download/" target="_blank" rel="noopener">getcomposer.org</a>를 참조하세요.',
'composer_checking' => 'Composer를 확인하는 중입니다...',
'cli_status_checking' => '확인 중...',
'cli_status_verified' => '✓ 확인됨',
'cli_status_not_verified' => '✗ 미확인',
// 환경 체크 강화
'required_functions' => '필수 함수',
'required_functions_available' => '사용 가능',
'required_functions_disabled' => ':count개 비활성화',
'success_required_functions' => '필수 함수(exec, proc_open, shell_exec)가 모두 사용 가능합니다.',
'error_disabled_functions' => '다음 함수가 비활성화되어 있어 설치를 진행할 수 없습니다: :functions. 호스팅 관리자에게 활성화를 요청하세요.',
'php_cli_version' => 'PHP CLI 버전',
'php_cli_version_check_skipped' => 'exec 함수가 비활성화되어 CLI 버전 확인을 건너뛰었습니다.',
'php_cli_version_unknown' => 'PHP CLI 버전을 확인할 수 없습니다.',
'php_cli_version_matched' => '일치 (웹: :web, CLI: :cli)',
'php_cli_version_mismatch' => '불일치 (웹: :web, CLI: :cli)',
'php_cli_version_mismatch_hint' => 'Step 3에서 올바른 PHP CLI 경로를 지정해주세요.',
'success_core_pending_path' => '경로가 유효하고 쓰기 권한이 있습니다.',
// .env 통합 안내
'required_files_fix_guide_combined' => '.env 파일 생성 및 권한 설정이 필요합니다. 아래 명령어를 실행해주세요:',
// 상대경로 병기 안내
'or_relative_path' => '또는 그누보드7 루트 디렉토리에서:',
];
?>
+290
View File
@@ -0,0 +1,290 @@
<?php
/**
* Step 0: 환영 화면 (언어 선택)
*
* POST 처리는 index.php에서 수행됩니다.
*
*/
$selectedLang = getCurrentLanguage();
// Storage 폴더 권한 체크 (재귀 체크 포함)
$storageCheck = checkDirectoryPermissions(['storage' => false]);
$storagePermissionPassed = $storageCheck['all_passed'];
$storageResult = $storageCheck['results']['storage'] ?? null;
?>
<div class="welcome-wrapper">
<div class="installer-container" id="welcome-step">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
<h1 class="installer-title" style="margin-bottom: 0;">
<?= lang('welcome_title') ?>
</h1>
<button
id="theme-toggle-btn"
class="theme-toggle"
type="button"
aria-label="<?= lang('toggle_theme') ?>"
title="<?= lang('toggle_theme') ?>"
style="margin: 0;"
>
<span id="theme-toggle-icon">🌙</span>
</button>
</div>
<p class="installer-description">
<?= lang('welcome_desc') ?>
</p>
<!-- Storage 권한 체크 경고 (권한 없을 시만 표시) -->
<?php if (!$storagePermissionPassed && $storageResult): ?>
<div class="alert alert-error" id="permission-warning">
<div class="alert-header">
<div class="alert-icon">
<?= getSvgIcon('error') ?>
</div>
<h3 class="alert-title">
<?php
// 에러 타입에 따른 제목 표시
if ($storageResult['error_type'] === 'not_exists') {
echo lang('storage_not_exists');
} elseif ($storageResult['error_type'] === 'not_writable') {
echo lang('storage_not_writable');
} else {
echo lang('storage_permission_required');
}
?>
</h3>
</div>
<p class="alert-message">
<?php
// 에러 타입에 따른 메시지 표시
if ($storageResult['error_type'] === 'not_exists') {
echo lang('storage_not_exists_message');
} elseif ($storageResult['error_type'] === 'not_writable') {
echo lang('storage_not_writable_message');
} else {
echo lang('storage_permission_failed');
}
?>
</p>
<div class="alert-details">
<?php
$detectedUser = getWebServerUser();
$webGroup = getWebServerGroup() ?? getWebServerUser() ?? 'www-data';
$storagePath = BASE_PATH . '/storage';
?>
<?php $relativeStorage = './storage'; ?>
<?php if ($storageResult['error_type'] === 'not_exists'): ?>
<!-- 디렉토리 미존재: mkdir 명령어 안내 -->
<p class="fix-guide-label"><?= lang('directory_create_guide') ?></p>
<div class="code-box">
<?php if (isWindows()): ?>
<pre class="fix-command"><?= htmlspecialchars('mkdir "' . str_replace('/', '\\', $storagePath) . '"') ?></pre>
<?php else: ?>
<pre class="fix-command"><?= htmlspecialchars('mkdir -p ' . $storagePath) ?></pre>
<?php endif; ?>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-hint"><?= lang('or_relative_path') ?></p>
<div class="code-box">
<?php if (isWindows()): ?>
<pre class="fix-command"><?= htmlspecialchars('mkdir "' . str_replace('/', '\\', $relativeStorage) . '"') ?></pre>
<?php else: ?>
<pre class="fix-command"><?= htmlspecialchars('mkdir -p ' . $relativeStorage) ?></pre>
<?php endif; ?>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<?php elseif (in_array($storageResult['error_type'], ['not_writable', 'permission_too_low', 'permission_low_but_writable', 'subdirectory_issues'])): ?>
<?php if (isWindows()): ?>
<!-- Windows: icacls 명령어 안내 -->
<p class="fix-guide-label"><?= lang('permission_fix_guide') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('icacls "' . str_replace('/', '\\', $storagePath) . '" /grant Everyone:(OI)(CI)F /T') ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-hint"><?= lang('or_relative_path') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('icacls "' . str_replace('/', '\\', $relativeStorage) . '" /grant Everyone:(OI)(CI)F /T') ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-hint"><?= lang('permission_windows_hint') ?></p>
<?php else: ?>
<!-- Linux/Mac: chmod (+ chown if owner ≠ web user) 명령어 안내 -->
<?php $ownerIsWebUser = $detectedUser && ($storageResult['owner'] ?? null) === $detectedUser; ?>
<?php if ($ownerIsWebUser): ?>
<p class="fix-guide-label"><?= lang('permission_fix_guide') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('chmod -R 2770 ' . $storagePath) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-hint"><?= lang('or_relative_path') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('chmod -R 2770 ' . $relativeStorage) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<?php else: ?>
<p class="fix-guide-label"><?= lang('ownership_fix_guide') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('sudo chown -R ' . $webGroup . ':' . $webGroup . ' ' . $storagePath . ' && sudo chmod -R 2770 ' . $storagePath) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-hint"><?= lang('or_relative_path') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('sudo chown -R ' . $webGroup . ':' . $webGroup . ' ' . $relativeStorage . ' && sudo chmod -R 2770 ' . $relativeStorage) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<?php if ($detectedUser): ?>
<p class="fix-guide-hint"><?= lang('ownership_detected_hint', ['user' => htmlspecialchars($detectedUser)]) ?></p>
<?php else: ?>
<p class="fix-guide-hint"><?= lang('ownership_fix_hint') ?></p>
<?php endif; ?>
<?php endif; ?>
<?php endif; ?>
<?php endif; ?>
<div class="permission-details">
<span class="permission-label"><?= lang('current_owner') ?>:</span>
<span class="permission-badge badge-current"><?= htmlspecialchars($storageResult['owner'] ?? lang('unknown')) ?></span>
<span class="permission-label"><?= lang('current_group') ?>:</span>
<span class="permission-badge badge-current"><?= htmlspecialchars($storageResult['group'] ?? lang('unknown')) ?></span>
<span class="permission-label"><?= lang('current_permissions') ?>:</span>
<span class="permission-badge badge-current"><?= $storageResult['permissions'] ?></span>
<?php if (in_array($storageResult['error_type'], ['permission_too_low', 'permission_low_but_writable'])): ?>
<span class="permission-arrow">→</span>
<span class="permission-label"><?= lang('required_permissions') ?>:</span>
<span class="permission-badge badge-required"><?= $storageResult['required_permissions'] ?></span>
<?php endif; ?>
</div>
</div>
</div>
<?php endif; ?>
<!-- 언어 선택 및 다음 버튼 폼 -->
<form method="POST" id="language-form">
<div class="form-group mb-4">
<label class="form-label">
<?= lang('select_language') ?>
</label>
<div class="form-field">
<select name="language"
id="language-select"
class="form-select">
<?php foreach (SUPPORTED_LANGUAGES as $code => $label): ?>
<option value="<?= $code ?>" <?= $selectedLang === $code ? 'selected' : '' ?>>
<?= htmlspecialchars($label) ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="btn-group">
<?php if (!$storagePermissionPassed): ?>
<!-- 권한 없을 때: 다시 확인 버튼 -->
<button type="button" onclick="recheckPermission()" class="btn btn-secondary" id="recheck-btn">
<?= lang('recheck_permission') ?>
</button>
<?php else: ?>
<!-- 권한 있을 때: 설치하기 버튼 -->
<button type="submit" class="btn btn-primary" id="install-btn">
<?= lang('install') ?>
</button>
<?php endif; ?>
</div>
</form>
</div>
</div>
<script>
/**
* 언어 선택 변경 시 localStorage 저장 후 자동 제출
*/
document.addEventListener('DOMContentLoaded', function() {
const languageSelect = document.getElementById('language-select');
const form = languageSelect.closest('form');
if (languageSelect && form) {
const serverLocale = languageSelect.value; // PHP에서 렌더링된 값
// 페이지 로드 시 localStorage와 서버 값 동기화
if (window.installerLocale) {
const savedLocale = window.installerLocale.get();
if (savedLocale && savedLocale !== serverLocale) {
// localStorage 값으로 select 업데이트
languageSelect.value = savedLocale;
// 서버와 동기화 (한 번만 실행)
const syncKey = 'installer_locale_synced';
const alreadySynced = sessionStorage.getItem(syncKey);
if (!alreadySynced) {
sessionStorage.setItem(syncKey, '1');
// 언어 변경만 하고 다음 단계로 이동하지 않음을 표시
let hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.name = 'language_change_only';
hiddenInput.value = '1';
form.appendChild(hiddenInput);
// 자동 제출하여 세션 및 state.json 동기화
form.submit();
return;
}
}
}
// 언어 선택 변경 이벤트
languageSelect.addEventListener('change', function() {
const selectedLang = this.value;
// localStorage에 저장
if (window.installerLocale) {
window.installerLocale.set(selectedLang);
}
// 언어 변경만 하고 다음 단계로 이동하지 않음을 표시
let hiddenInput = form.querySelector('input[name="language_change_only"]');
if (!hiddenInput) {
hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.name = 'language_change_only';
form.appendChild(hiddenInput);
}
hiddenInput.value = '1';
// 폼 자동 제출 (세션 및 state.json 동기화)
form.submit();
});
}
});
/**
* Storage 권한 재확인
*/
function recheckPermission() {
const btn = document.getElementById('recheck-btn');
const originalText = btn.textContent;
btn.disabled = true;
btn.textContent = '<?= lang('permission_checking') ?>';
// 페이지 새로고침 (권한이 변경되었을 수 있으므로)
setTimeout(function() {
window.location.reload();
}, 500);
}
/**
* chmod 명령어 복사
*/
function copyWelcomeCommand(btn) {
const command = btn.previousElementSibling.textContent;
navigator.clipboard.writeText(command).then(function() {
const originalText = btn.textContent;
btn.textContent = '<?= lang('copied') ?>';
setTimeout(function() { btn.textContent = originalText; }, 2000);
});
}
</script>
+52
View File
@@ -0,0 +1,52 @@
<?php
/**
* Step 1: 라이선스 동의
*
* G7 라이선스를 표시하고 사용자 동의를 받습니다.
*/
// $error 변수는 index.php의 POST 처리에서 설정될 수 있음
if (!isset($error)) {
$error = null;
}
// LICENSE 파일 읽기
$licenseContent = loadLicenseFile($currentLang);
// 라이선스 동의 여부 확인 (세션 기반)
$isLicenseAgreed = isset($_SESSION['license_agreed']) && $_SESSION['license_agreed'] === true;
?>
<div class="welcome-wrapper">
<div class="installer-container installer-container-wide">
<h1 class="installer-title"><?= htmlspecialchars(lang('license_title')) ?></h1>
<!-- 라이선스 본문 -->
<div class="license-box">
<pre class="license-text"><?= htmlspecialchars($licenseContent) ?></pre>
</div>
<?php if ($error): ?>
<div class="alert alert-error">
<?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>
<form method="POST" class="installer-form">
<label class="form-checkbox" style="justify-content: flex-end;">
<span><?= htmlspecialchars(lang('i_agree')) ?></span>
<input type="checkbox" name="agree" value="1" id="license-agree" class="checkbox-input" <?= $isLicenseAgreed ? 'checked' : '' ?>>
</label>
<div id="navigation-buttons" class="btn-group btn-group-spread">
<button type="button" onclick="goToStep(0)" class="btn btn-secondary">
<?= htmlspecialchars(lang('previous')) ?>
</button>
<button type="submit" id="next-btn" class="btn btn-primary">
<?= htmlspecialchars(lang('next')) ?>
</button>
</div>
</form>
</div>
</div>
+37
View File
@@ -0,0 +1,37 @@
<?php
/**
* Step 2: 요구사항 검증
*
* 서버 요구사항을 검증하고 결과를 표시합니다.
*/
?>
<div class="installer-container installer-container-wide">
<h1 class="installer-title"><?= htmlspecialchars(lang('step_2_requirements')) ?></h1>
<div id="requirements-result" class="requirements-list">
<!-- AJAX 로딩 중 -->
<div class="loading-box">
<div class="spinner"></div>
<p class="loading-text"><?= htmlspecialchars(lang('checking_requirements')) ?></p>
</div>
</div>
<div id="navigation-buttons" class="btn-group btn-group-spread hidden">
<button type="button" onclick="goToStep(1)" class="btn btn-secondary">
<?= htmlspecialchars(lang('previous')) ?>
</button>
<div class="btn-group-right">
<button onclick="recheckRequirements()" id="recheck-btn" class="btn btn-danger hidden">
<?= htmlspecialchars(lang('recheck')) ?>
</button>
<form method="POST" class="form-inline">
<button type="submit" name="proceed" id="next-btn" disabled class="btn btn-primary hidden">
<?= htmlspecialchars(lang('next')) ?>
</button>
</form>
</div>
</div>
</div>
+833
View File
@@ -0,0 +1,833 @@
<?php
/**
* Step 3: 데이터베이스 및 사이트 설정
*
* 데이터베이스 설정, 사이트 설정, 관리자 계정을 입력받습니다.
* $formData는 index.php에서 준비됨
*/
if (!isset($errors)) {
$errors = [];
}
// DB 테스트 플래그
$dbWriteTested = isset($_SESSION['db_write_tested']) && $_SESSION['db_write_tested'] === true;
$dbReadTested = isset($_SESSION['db_read_tested']) && $_SESSION['db_read_tested'] === true;
// DB 필드 해시값 계산 (변경 감지용)
$dbWriteHash = getDatabaseFieldHash($formData, 'db_write');
$dbReadHash = getDatabaseFieldHash($formData, 'db_read');
?>
<div class="installer-container installer-container-wide">
<h1 class="installer-title"><?= htmlspecialchars(lang('step_3_configuration')) ?></h1>
<?php if (!empty($errors)): ?>
<div class="alert alert-error">
<ul class="alert-list">
<?php foreach ($errors as $error): ?>
<li><?= htmlspecialchars($error) ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" id="config-form" class="installer-form">
<!-- 데이터베이스 설정 (Write DB) -->
<div class="requirement-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title"><?= htmlspecialchars(lang('database_settings')) ?> (Write Server)</h3>
</div>
<div class="requirement-card-body">
<div class="form-grid">
<div class="form-group form-group-full">
<label class="form-label"><?= htmlspecialchars(lang('database_type')) ?></label>
<select name="db_type" class="form-select" disabled>
<option value="mysql" selected>MySQL</option>
</select>
<input type="hidden" name="db_type" value="mysql">
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_host')) ?> *</label>
<input type="text" name="db_write_host" value="<?= htmlspecialchars($formData['db_write_host']) ?>"
class="form-input" required>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_port')) ?></label>
<input type="text" name="db_write_port" value="<?= htmlspecialchars($formData['db_write_port']) ?>"
class="form-input">
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_name')) ?> *</label>
<input type="text" name="db_write_database" value="<?= htmlspecialchars($formData['db_write_database']) ?>"
class="form-input" required>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_prefix')) ?></label>
<input type="text" name="db_prefix" id="db_prefix"
value="<?= htmlspecialchars($formData['db_prefix']) ?>"
class="form-input"
placeholder="<?= htmlspecialchars(lang('db_prefix_placeholder')) ?>"
pattern="^[a-z][a-z0-9_]*$"
aria-invalid="false"
aria-describedby="db_prefix-error db_prefix-hint">
<small id="db_prefix-hint" class="form-hint">
<?= htmlspecialchars(lang('db_prefix_hint')) ?>
</small>
<div id="db_prefix-error" class="field-error" role="alert"></div>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_username')) ?> *</label>
<input type="text" name="db_write_username" value="<?= htmlspecialchars($formData['db_write_username']) ?>"
class="form-input" required>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_password')) ?></label>
<input type="password" name="db_write_password" value="<?= htmlspecialchars($formData['db_write_password']) ?>"
class="form-input">
</div>
</div>
<div class="test-db-wrapper">
<button type="button" onclick="testDatabaseConnection('write')" class="btn btn-success">
<?= htmlspecialchars(lang('test_write_db_connection')) ?>
</button>
</div>
<div id="db-write-test-result" class="test-result hidden"></div>
</div>
</div>
<!-- 데이터베이스 설정 (Read DB) -->
<div class="requirement-card">
<div class="requirement-card-header" style="cursor: pointer;">
<label for="use-read-db" style="cursor: pointer; display: flex; align-items: center; gap: var(--spacing-sm); flex: 1;">
<h3 class="requirement-card-title" style="margin: 0;"><?= htmlspecialchars(lang('use_read_db')) ?></h3>
</label>
<input type="checkbox" name="use_read_db" id="use-read-db" value="1"
<?= !empty($formData['use_read_db']) ? 'checked' : '' ?>
class="toggle-switch">
</div>
<div id="read-db-section" class="requirement-card-body <?= empty($formData['use_read_db']) ? 'hidden' : '' ?>" style="transition: all 0.3s ease-out;">
<div class="form-grid">
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_host')) ?> *</label>
<input type="text" name="db_read_host" value="<?= htmlspecialchars($formData['db_read_host']) ?>"
class="form-input">
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_port')) ?></label>
<input type="text" name="db_read_port" value="<?= htmlspecialchars($formData['db_read_port']) ?>"
class="form-input">
</div>
<div class="form-group form-group-full">
<label class="form-label"><?= htmlspecialchars(lang('db_name')) ?> *</label>
<input type="text" name="db_read_database" value="<?= htmlspecialchars($formData['db_read_database']) ?>"
class="form-input">
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_username')) ?> *</label>
<input type="text" name="db_read_username" value="<?= htmlspecialchars($formData['db_read_username']) ?>"
class="form-input">
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('db_password')) ?></label>
<input type="password" name="db_read_password" value="<?= htmlspecialchars($formData['db_read_password']) ?>"
class="form-input">
</div>
</div>
<div class="test-db-wrapper">
<button type="button" onclick="testDatabaseConnection('read')" class="btn btn-success">
<?= htmlspecialchars(lang('test_read_db_connection')) ?>
</button>
</div>
<div id="db-read-test-result" class="test-result hidden"></div>
</div>
</div>
<!-- 사이트 설정 -->
<div class="requirement-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title"><?= htmlspecialchars(lang('site_settings')) ?></h3>
</div>
<div class="requirement-card-body">
<div class="form-fields">
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('app_name')) ?> *</label>
<input type="text" name="app_name" id="app_name" value="<?= htmlspecialchars($formData['app_name']) ?>"
class="form-input" required
aria-invalid="false" aria-describedby="app_name-error">
<div id="app_name-error" class="field-error" role="alert"></div>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('app_url')) ?> *</label>
<input type="url" name="app_url" id="app_url" value="<?= htmlspecialchars($formData['app_url']) ?>"
class="form-input" required
aria-invalid="false" aria-describedby="app_url-error">
<div id="app_url-error" class="field-error" role="alert"></div>
</div>
</div>
</div>
</div>
<!-- 관리자 설정 -->
<div class="requirement-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title"><?= htmlspecialchars(lang('admin_account')) ?></h3>
</div>
<div class="requirement-card-body">
<div class="form-grid">
<div class="form-group form-group-full">
<label class="form-label"><?= htmlspecialchars(lang('admin_email')) ?> *</label>
<input type="email" name="admin_email" id="admin_email" value="<?= htmlspecialchars($formData['admin_email']) ?>"
class="form-input" required
aria-invalid="false" aria-describedby="admin_email-error">
<div id="admin_email-error" class="field-error" role="alert"></div>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('admin_name')) ?> *</label>
<input type="text" name="admin_name" id="admin_name" value="<?= htmlspecialchars($formData['admin_name']) ?>"
class="form-input" required
aria-invalid="false" aria-describedby="admin_name-error">
<div id="admin_name-error" class="field-error" role="alert"></div>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('admin_language')) ?> *</label>
<select name="admin_language" id="admin_language" class="form-select" required>
<?php
$selectedAdminLang = $formData['admin_language'] ?? getCurrentLanguage();
foreach (SUPPORTED_LANGUAGES as $code => $label): ?>
<option value="<?= $code ?>" <?= $selectedAdminLang === $code ? 'selected' : '' ?>>
<?= htmlspecialchars($label) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('admin_password')) ?> *</label>
<input type="password" name="admin_password" id="admin_password"
class="form-input" required minlength="8"
aria-invalid="false" aria-describedby="admin_password-error">
<div id="admin_password-error" class="field-error" role="alert"></div>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('admin_password_confirm')) ?> *</label>
<input type="password" name="admin_password_confirm" id="admin_password_confirm"
class="form-input" required
aria-invalid="false" aria-describedby="admin_password_confirm-error">
<div id="admin_password_confirm-error" class="field-error" role="alert"></div>
</div>
</div>
</div>
</div>
<!-- 코어 업데이트 설정 (선택) -->
<div class="requirement-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title"><?= htmlspecialchars(lang('core_update_settings')) ?></h3>
</div>
<div class="requirement-card-body">
<div class="form-fields">
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('core_update_pending_path')) ?></label>
<input type="text" name="core_update_pending_path"
value="<?= htmlspecialchars($formData['core_update_pending_path'] ?? '') ?>"
class="form-input"
placeholder="storage/app/core_pending"
aria-describedby="core_update_pending_path-help">
<p id="core_update_pending_path-help" class="form-help">
<?= htmlspecialchars(lang('core_update_pending_path_help')) ?>
</p>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('core_update_github_url')) ?></label>
<input type="url" name="core_update_github_url"
value="<?= htmlspecialchars($formData['core_update_github_url'] ?? 'https://github.com/gnuboard/g7') ?>"
class="form-input"
placeholder="https://github.com/gnuboard/g7">
<p class="form-help">
<?= htmlspecialchars(lang('core_update_github_url_help')) ?>
</p>
</div>
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('core_update_github_token')) ?></label>
<input type="password" name="core_update_github_token"
value="<?= htmlspecialchars($formData['core_update_github_token'] ?? '') ?>"
class="form-input"
placeholder="ghp_xxxxxxxxxxxxxxxxxxxx"
autocomplete="off">
<p class="form-help">
<?= htmlspecialchars(lang('core_update_github_token_help')) ?>
</p>
</div>
</div>
<!-- 커스텀 경로 입력 시 퍼미션/소유자 체크 버튼 -->
<div id="core-pending-check-wrapper" class="test-db-wrapper" style="display:none;">
<button type="button" onclick="checkCorePendingPath()" class="btn btn-success">
<?= htmlspecialchars(lang('check_core_pending_path')) ?>
</button>
</div>
<div id="core-pending-check-result" class="test-result hidden"></div>
</div>
</div>
<!-- PHP CLI / Composer 설정 -->
<div class="requirement-card" id="php-cli-card">
<div class="requirement-card-header" style="cursor: pointer;">
<label for="show-php-cli-settings" style="cursor: pointer; display: flex; align-items: center; gap: var(--spacing-sm); flex: 1;">
<h3 class="requirement-card-title" style="margin: 0;" id="php-cli-title"><?= htmlspecialchars(lang('php_cli_settings')) ?></h3>
</label>
<input type="checkbox" id="show-php-cli-settings" value="1"
<?= (!empty($formData['php_binary']) && $formData['php_binary'] !== 'php') || !empty($formData['composer_binary']) ? 'checked' : '' ?>
class="toggle-switch">
</div>
<div id="php-cli-section" class="requirement-card-body <?= (empty($formData['php_binary']) || $formData['php_binary'] === 'php') && empty($formData['composer_binary']) ? 'hidden' : '' ?>" style="transition: all 0.3s ease-out;">
<p class="form-help" style="margin-bottom: var(--spacing-md);" id="php-cli-help-text">
<?= htmlspecialchars(lang('php_cli_settings_help')) ?>
</p>
<!-- 검증 상태 요약 -->
<div id="cli-status-summary" class="alert alert-info" style="display: none; margin-bottom: var(--spacing-md);">
<div style="display: flex; gap: var(--spacing-lg); flex-wrap: wrap;">
<span>PHP CLI: <strong id="cli-php-status"><?= htmlspecialchars(lang('cli_status_not_verified')) ?></strong></span>
<span>Composer: <strong id="cli-composer-status"><?= htmlspecialchars(lang('cli_status_not_verified')) ?></strong></span>
</div>
</div>
<div class="form-fields">
<!-- PHP CLI 경로 -->
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('php_binary_path')) ?></label>
<div style="display: flex; gap: var(--spacing-sm);">
<input type="text" name="php_binary" id="php_binary"
value="<?= htmlspecialchars($formData['php_binary'] ?? 'php') ?>"
class="form-input" style="flex: 1;"
placeholder="php">
<button type="button" onclick="testPhpBinary()" class="btn btn-success" style="white-space: nowrap;">
<?= htmlspecialchars(lang('verify_version')) ?>
</button>
</div>
<p class="form-help">
<?= htmlspecialchars(lang('php_binary_path_help')) ?>
</p>
<div id="php-binary-test-result" class="test-result hidden"></div>
</div>
<!-- Composer 경로 -->
<div class="form-group">
<label class="form-label"><?= htmlspecialchars(lang('composer_binary_path')) ?></label>
<div style="display: flex; gap: var(--spacing-sm);">
<input type="text" name="composer_binary" id="composer_binary"
value="<?= htmlspecialchars($formData['composer_binary'] ?? '') ?>"
class="form-input" style="flex: 1;"
placeholder="composer">
<button type="button" onclick="testComposer()" class="btn btn-success" style="white-space: nowrap;">
<?= htmlspecialchars(lang('verify_version')) ?>
</button>
</div>
<p class="form-help">
<?= htmlspecialchars(lang('composer_binary_path_help')) ?>
</p>
<div id="composer-test-result" class="test-result hidden"></div>
</div>
</div>
<!-- Composer 미설치 시 설치 안내 -->
<div id="composer-install-guide" class="alert alert-warning" style="display: none; margin-top: var(--spacing-md);">
<div class="alert-header">
<div class="alert-icon"><?= getSvgIcon('warning') ?></div>
<h3 class="alert-title"><?= htmlspecialchars(lang('composer_install_guide_title')) ?></h3>
</div>
<p class="alert-message"><?= htmlspecialchars(lang('composer_install_guide_message')) ?></p>
<div class="alert-details" id="composer-install-commands">
<!-- JS에서 PHP 경로 반영하여 동적 생성 -->
</div>
</div>
<div class="test-db-wrapper">
<button type="button" onclick="detectPhpBinaries()" class="btn btn-secondary">
<?= htmlspecialchars(lang('auto_detect_php')) ?>
</button>
</div>
<div id="php-detect-result" class="test-result hidden"></div>
</div>
</div>
<!-- 네비게이션 -->
<div class="btn-group btn-group-spread">
<button type="button" onclick="goToStep(2)" class="btn btn-secondary">
<?= htmlspecialchars(lang('previous')) ?>
</button>
<button type="submit" id="submit-btn" class="btn btn-primary">
<?= htmlspecialchars(lang('next')) ?>
</button>
</div>
</form>
</div>
<script>
// Step 3 전용 데이터 전달 (DB 테스트 상태)
window.DB_TEST_FLAGS = {
write: <?= $dbWriteTested ? 'true' : 'false' ?>,
read: <?= $dbReadTested ? 'true' : 'false' ?>,
writeHash: <?= json_encode($dbWriteHash) ?>,
readHash: <?= json_encode($dbReadHash) ?>
};
// ========================================================================
// PHP CLI / Composer 검증 상태 관리
// ========================================================================
/**
* CLI 검증 상태 추적 객체
*/
window.CliValidator = {
phpVerified: false,
composerVerified: false,
cliRequired: false, // 기본 php 사용 불가 시 true
setPhpVerified(verified) {
this.phpVerified = verified;
this.updateStatusDisplay();
this.updateSubmitButton();
},
setComposerVerified(verified) {
this.composerVerified = verified;
this.updateStatusDisplay();
this.updateSubmitButton();
},
isValid() {
// CLI 섹션이 열려 있으면 (필수이든 선택이든) 검증 필요
const section = document.getElementById('php-cli-section');
if (section && section.classList.contains('hidden')) {
// 섹션이 닫혀 있고 필수가 아니면 검증 불필요
if (!this.cliRequired) return true;
}
return this.phpVerified && this.composerVerified;
},
updateStatusDisplay() {
const summary = document.getElementById('cli-status-summary');
const phpStatus = document.getElementById('cli-php-status');
const composerStatus = document.getElementById('cli-composer-status');
if (!summary || !phpStatus || !composerStatus) return;
summary.style.display = '';
phpStatus.textContent = this.phpVerified
? '<?= lang("cli_status_verified") ?>'
: '<?= lang("cli_status_not_verified") ?>';
phpStatus.style.color = this.phpVerified ? 'var(--success-color)' : 'var(--error-color)';
composerStatus.textContent = this.composerVerified
? '<?= lang("cli_status_verified") ?>'
: '<?= lang("cli_status_not_verified") ?>';
composerStatus.style.color = this.composerVerified ? 'var(--success-color)' : 'var(--error-color)';
},
updateSubmitButton() {
// submit 버튼 상태는 validateStep3Form에서 최종 체크하므로 여기서는 시각적 힌트만
}
};
// PHP CLI 설정 토글
document.getElementById('show-php-cli-settings')?.addEventListener('change', function() {
const section = document.getElementById('php-cli-section');
if (this.checked) {
section.classList.remove('hidden');
// 토글을 켰을 때 자동 감지 실행
initCliDetection();
} else {
section.classList.add('hidden');
}
});
// PHP CLI / Composer 입력 변경 시 검증 상태 무효화
document.getElementById('php_binary')?.addEventListener('input', function() {
window.CliValidator.setPhpVerified(false);
// Composer도 PHP 경로에 의존하므로 (.phar 실행) 재검증 필요
window.CliValidator.setComposerVerified(false);
const phpResult = document.getElementById('php-binary-test-result');
if (phpResult) { phpResult.classList.add('hidden'); phpResult.innerHTML = ''; }
const composerResult = document.getElementById('composer-test-result');
if (composerResult) { composerResult.classList.add('hidden'); composerResult.innerHTML = ''; }
});
document.getElementById('composer_binary')?.addEventListener('input', function() {
window.CliValidator.setComposerVerified(false);
const composerResult = document.getElementById('composer-test-result');
if (composerResult) { composerResult.classList.add('hidden'); composerResult.innerHTML = ''; }
// Composer 설치 안내 숨기기
const guide = document.getElementById('composer-install-guide');
if (guide) guide.style.display = 'none';
});
/**
* 페이지 로드 시 PHP CLI / Composer 자동 감지
*/
async function initCliDetection() {
const phpStatus = document.getElementById('cli-php-status');
const composerStatus = document.getElementById('cli-composer-status');
const summary = document.getElementById('cli-status-summary');
if (summary) summary.style.display = '';
if (phpStatus) { phpStatus.textContent = '<?= lang("cli_status_checking") ?>'; phpStatus.style.color = ''; }
if (composerStatus) { composerStatus.textContent = '<?= lang("cli_status_checking") ?>'; composerStatus.style.color = ''; }
// PHP 감지 먼저 실행 (composer 감지 결과 포함) → Composer 검증
const composerData = await detectAndVerifyPhp();
await detectAndVerifyComposer(composerData);
}
/**
* PHP CLI 자동 감지 및 검증
*/
async function detectAndVerifyPhp() {
try {
const response = await fetch('api/check-configuration.php?action=detect-php');
const data = await response.json();
if (!data.default_php_available) {
// 기본 php 사용 불가 → 필수 모드로 전환
switchToRequiredMode();
// 감지된 바이너리가 있으면 첫 번째로 자동 선택
if (data.success && data.binaries && data.binaries.length > 0) {
const phpInput = document.getElementById('php_binary');
if (phpInput && (phpInput.value === 'php' || phpInput.value === '')) {
phpInput.value = data.binaries[0].path;
}
// 자동 감지 결과 표시
showDetectResult(data);
// 자동 선택된 경로로 검증
await testPhpBinary();
}
} else {
// 기본 php 사용 가능
if (data.success && data.binaries) {
showDetectResult(data);
}
// 현재 입력된 경로로 검증
await testPhpBinary();
}
return data.composer || null;
} catch (e) {
// 감지 실패 시 수동 입력 유도
switchToRequiredMode();
return null;
}
}
/**
* Composer 자동 감지 및 검증
* detect-php API 응답의 composer 결과를 사용하여 사전 입력
*/
async function detectAndVerifyComposer(composerData) {
const composerInput = document.getElementById('composer_binary');
// detect-php 응답에 composer 감지 결과가 있으면 사전 입력
if (composerData && composerData.found && composerInput) {
if (!composerInput.value.trim()) {
composerInput.value = composerData.path === 'composer' ? '' : composerData.path;
}
}
await testComposer();
}
/**
* 기본 php 미감지 시 필수 모드로 전환
*/
function switchToRequiredMode() {
window.CliValidator.cliRequired = true;
const title = document.getElementById('php-cli-title');
if (title) title.textContent = '<?= lang("php_cli_settings_required") ?>';
const helpText = document.getElementById('php-cli-help-text');
if (helpText) helpText.textContent = '<?= lang("php_cli_settings_help_required") ?>';
// 섹션 강제 오픈 + 토글 비활성화
const section = document.getElementById('php-cli-section');
if (section) section.classList.remove('hidden');
const toggle = document.getElementById('show-php-cli-settings');
if (toggle) {
toggle.checked = true;
toggle.disabled = true;
toggle.style.opacity = '0.5';
toggle.style.cursor = 'not-allowed';
}
}
// PHP 바이너리 버전 확인
async function testPhpBinary() {
const path = document.getElementById('php_binary').value.trim() || 'php';
const resultDiv = document.getElementById('php-binary-test-result');
resultDiv.className = 'test-result';
resultDiv.innerHTML = '<span class="loading-spinner"></span> ' + '<?= lang("checking") ?>';
try {
const response = await fetch('api/check-configuration.php?action=test-php-binary', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: path })
});
const data = await response.json();
if (data.success) {
resultDiv.className = 'test-result test-success';
resultDiv.innerHTML = data.message;
window.CliValidator.setPhpVerified(true);
} else {
resultDiv.className = 'test-result test-error';
resultDiv.innerHTML = data.message;
window.CliValidator.setPhpVerified(false);
}
} catch (e) {
resultDiv.className = 'test-result test-error';
resultDiv.innerHTML = '<?= lang("error_check_failed") ?>';
window.CliValidator.setPhpVerified(false);
}
}
// Composer 버전 확인
async function testComposer() {
const composerPath = document.getElementById('composer_binary').value.trim();
const phpPath = document.getElementById('php_binary').value.trim() || 'php';
const resultDiv = document.getElementById('composer-test-result');
resultDiv.className = 'test-result';
resultDiv.innerHTML = '<span class="loading-spinner"></span> ' + '<?= lang("composer_checking") ?>';
try {
const response = await fetch('api/check-configuration.php?action=test-composer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: composerPath, php_path: phpPath })
});
const data = await response.json();
if (data.success) {
resultDiv.className = 'test-result test-success';
resultDiv.innerHTML = data.message;
window.CliValidator.setComposerVerified(true);
// 설치 안내 숨기기
const guide = document.getElementById('composer-install-guide');
if (guide) guide.style.display = 'none';
} else {
resultDiv.className = 'test-result test-error';
resultDiv.innerHTML = data.message;
window.CliValidator.setComposerVerified(false);
showComposerInstallGuide();
}
} catch (e) {
resultDiv.className = 'test-result test-error';
resultDiv.innerHTML = '<?= lang("error_check_failed") ?>';
window.CliValidator.setComposerVerified(false);
showComposerInstallGuide();
}
}
/**
* Composer 설치 안내를 PHP 경로 반영하여 동적 생성
*/
function showComposerInstallGuide() {
const guide = document.getElementById('composer-install-guide');
if (!guide) return;
const phpPath = document.getElementById('php_binary').value.trim() || 'php';
const commandsDiv = document.getElementById('composer-install-commands');
if (!commandsDiv) return;
let html = '';
// 표준 설치 안내 (항상 표시)
html += '<p class="fix-guide-label"><?= lang("composer_install_guide_global") ?></p>';
html += '<div class="code-box">';
html += '<pre class="fix-command">curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer</pre>';
html += '<button type="button" class="btn-copy" onclick="copyCliCommand(this)"><?= lang("copy_command") ?></button>';
html += '</div>';
html += '<p class="fix-guide-label" style="margin-top: var(--spacing-sm);"><?= lang("composer_install_guide_local") ?></p>';
html += '<div class="code-box">';
html += '<pre class="fix-command">curl -sS https://getcomposer.org/installer | php</pre>';
html += '<button type="button" class="btn-copy" onclick="copyCliCommand(this)"><?= lang("copy_command") ?></button>';
html += '</div>';
// 호스팅 환경 안내 (항상 표시 — 표준 방법 실패 시 대안)
html += '<p class="fix-guide-label" style="margin-top: var(--spacing-md);"><?= lang("composer_install_guide_hosting") ?></p>';
html += '<div class="code-box">';
html += '<pre class="fix-command">curl -o composer-setup.php https://getcomposer.org/installer</pre>';
html += '<button type="button" class="btn-copy" onclick="copyCliCommand(this)"><?= lang("copy_command") ?></button>';
html += '</div>';
html += '<div class="code-box" style="margin-top: var(--spacing-xs);">';
html += '<pre class="fix-command">' + escapeHtml(phpPath) + ' -d allow_url_fopen=On composer-setup.php</pre>';
html += '<button type="button" class="btn-copy" onclick="copyCliCommand(this)"><?= lang("copy_command") ?></button>';
html += '</div>';
html += '<p class="fix-guide-hint" style="margin-top: var(--spacing-sm);"><?= lang("composer_install_guide_pwd_hint") ?></p>';
html += '<div class="code-box">';
html += '<pre class="fix-command">pwd</pre>';
html += '<button type="button" class="btn-copy" onclick="copyCliCommand(this)"><?= lang("copy_command") ?></button>';
html += '</div>';
html += '<p class="fix-guide-hint" style="margin-top: var(--spacing-sm);"><?= lang("composer_install_guide_phar_hint") ?></p>';
html += '<p class="fix-guide-hint" style="margin-top: var(--spacing-sm);"><?= lang("composer_install_guide_link") ?></p>';
commandsDiv.innerHTML = html;
guide.style.display = '';
}
/**
* HTML 이스케이프
*/
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
/**
* PHP 감지 결과 표시 (감지 결과 영역)
*/
function showDetectResult(data) {
const resultDiv = document.getElementById('php-detect-result');
if (!resultDiv) return;
if (data.success && data.binaries && data.binaries.length > 0) {
let html = '<strong>' + '<?= lang("detected_php_binaries") ?>' + '</strong><ul style="margin: var(--spacing-xs) 0; padding-left: var(--spacing-lg);">';
data.binaries.forEach(function(bin) {
html += '<li><a href="#" onclick="selectPhpBinary(\'' + bin.path.replace(/'/g, "\\'") + '\'); return false;" style="cursor: pointer;">'
+ bin.path + '</a> — PHP ' + bin.version + '</li>';
});
html += '</ul>';
resultDiv.className = 'test-result test-success';
resultDiv.innerHTML = html;
} else {
resultDiv.className = 'test-result test-error';
resultDiv.innerHTML = data.message || '<?= lang("no_php_detected") ?>';
}
}
/**
* 감지된 PHP 바이너리 선택 시 자동 검증
*/
async function selectPhpBinary(path) {
document.getElementById('php_binary').value = path;
// PHP 검증 상태 초기화 후 재검증
window.CliValidator.setPhpVerified(false);
window.CliValidator.setComposerVerified(false);
await testPhpBinary();
// Composer도 PHP 경로 의존이므로 재검증
await testComposer();
}
// PHP 바이너리 자동 감지 (수동 버튼)
async function detectPhpBinaries() {
const resultDiv = document.getElementById('php-detect-result');
resultDiv.className = 'test-result';
resultDiv.innerHTML = '<span class="loading-spinner"></span> ' + '<?= lang("detecting_php") ?>';
try {
const response = await fetch('api/check-configuration.php?action=detect-php');
const data = await response.json();
showDetectResult(data);
if (!data.default_php_available) {
switchToRequiredMode();
}
} catch (e) {
resultDiv.className = 'test-result test-error';
resultDiv.innerHTML = '<?= lang("error_check_failed") ?>';
}
}
/**
* 명령어 복사 (Composer 설치 안내)
*/
function copyCliCommand(btn) {
const command = btn.previousElementSibling.textContent;
navigator.clipboard.writeText(command).then(function() {
const originalText = btn.textContent;
btn.textContent = '<?= lang("copied") ?>';
setTimeout(function() { btn.textContent = originalText; }, 2000);
});
}
// 페이지 로드 시 CLI 섹션이 열려 있으면 자동 감지 실행
document.addEventListener('DOMContentLoaded', function() {
const section = document.getElementById('php-cli-section');
const toggle = document.getElementById('show-php-cli-settings');
if (section && !section.classList.contains('hidden')) {
initCliDetection();
} else {
// 섹션이 닫혀 있어도 기본 php/composer 사용 가능 여부는 확인해야 함
// 사용 불가 시 필수 모드로 전환되면서 섹션이 열림
initCliDetection();
}
});
// 코어 업데이트 _pending 경로 입력 시 체크 버튼 표시
document.querySelector('input[name="core_update_pending_path"]')?.addEventListener('input', function() {
const wrapper = document.getElementById('core-pending-check-wrapper');
wrapper.style.display = this.value.trim() ? 'block' : 'none';
});
// 코어 _pending 경로 퍼미션/소유자 체크
async function checkCorePendingPath() {
const path = document.querySelector('input[name="core_update_pending_path"]').value.trim();
const resultDiv = document.getElementById('core-pending-check-result');
if (!path) return;
resultDiv.className = 'test-result';
resultDiv.innerHTML = '<span class="loading-spinner"></span> ' + '<?= lang("checking") ?>';
try {
const response = await fetch('api/check-configuration.php?action=check-core-pending-path&path=' + encodeURIComponent(path));
const data = await response.json();
if (data.success) {
resultDiv.className = 'test-result test-success';
resultDiv.innerHTML = data.message;
} else {
resultDiv.className = 'test-result test-error';
resultDiv.innerHTML = data.message;
}
} catch (e) {
resultDiv.className = 'test-result test-error';
resultDiv.innerHTML = '<?= lang("error_check_failed") ?>';
}
}
</script>
@@ -0,0 +1,166 @@
<?php
/**
* Step 4: 확장 기능 선택
*
* 설치할 템플릿, 모듈, 플러그인을 선택합니다.
* 관리자 템플릿은 최소 1개 필수이며, 나머지는 선택 사항입니다.
*/
?>
<div class="installer-container installer-container-wide">
<h1 class="installer-title"><?= htmlspecialchars(lang('step_4_extension_selection')) ?></h1>
<p class="installer-description">
<?= htmlspecialchars(lang('extension_selection_description')) ?>
</p>
<!-- 로딩 표시 -->
<div id="extensions-loading" class="extension-loading">
<div class="spinner"></div>
<p><?= htmlspecialchars(lang('loading_extensions')) ?></p>
</div>
<!-- 에러 표시 -->
<div id="extensions-error" class="alert alert-error hidden">
<p id="extensions-error-message"></p>
<button type="button" onclick="loadExtensions()" class="btn btn-sm btn-secondary">
<?= htmlspecialchars(lang('retry')) ?>
</button>
</div>
<!-- 확장 선택 폼 -->
<form id="extension-form" class="installer-form hidden">
<!-- 관리자 템플릿 (필수) -->
<div class="requirement-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title">
<i class="fas fa-shield-alt"></i>
<?= htmlspecialchars(lang('admin_templates')) ?>
<span class="badge badge-required"><?= htmlspecialchars(lang('required')) ?></span>
</h3>
</div>
<div class="requirement-card-body">
<p class="card-description"><?= htmlspecialchars(lang('admin_templates_description')) ?></p>
<div id="admin-templates-list" class="extension-grid">
<!-- JavaScript로 동적 렌더링 -->
</div>
</div>
</div>
<!-- 사용자 템플릿 (선택) -->
<div class="requirement-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title">
<i class="fas fa-palette"></i>
<?= htmlspecialchars(lang('user_templates')) ?>
<span class="badge badge-optional"><?= htmlspecialchars(lang('optional')) ?></span>
</h3>
</div>
<div class="requirement-card-body">
<p class="card-description"><?= htmlspecialchars(lang('user_templates_description')) ?></p>
<div id="user-templates-list" class="extension-grid">
<!-- JavaScript로 동적 렌더링 -->
</div>
<div id="user-templates-empty" class="extension-empty hidden">
<?= htmlspecialchars(lang('no_user_templates')) ?>
</div>
</div>
</div>
<!-- 모듈 (선택) -->
<div class="requirement-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title">
<i class="fas fa-cube"></i>
<?= htmlspecialchars(lang('modules')) ?>
<span class="badge badge-optional"><?= htmlspecialchars(lang('optional')) ?></span>
</h3>
</div>
<div class="requirement-card-body">
<p class="card-description"><?= htmlspecialchars(lang('modules_description')) ?></p>
<div id="modules-list" class="extension-grid">
<!-- JavaScript로 동적 렌더링 -->
</div>
<div id="modules-empty" class="extension-empty hidden">
<?= htmlspecialchars(lang('no_modules')) ?>
</div>
</div>
</div>
<!-- 플러그인 (선택) -->
<div class="requirement-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title">
<i class="fas fa-plug"></i>
<?= htmlspecialchars(lang('plugins')) ?>
<span class="badge badge-optional"><?= htmlspecialchars(lang('optional')) ?></span>
</h3>
</div>
<div class="requirement-card-body">
<p class="card-description"><?= htmlspecialchars(lang('plugins_description')) ?></p>
<div id="plugins-list" class="extension-grid">
<!-- JavaScript로 동적 렌더링 -->
</div>
<div id="plugins-empty" class="extension-empty hidden">
<?= htmlspecialchars(lang('no_plugins')) ?>
</div>
</div>
</div>
<!-- 선택 요약 -->
<div class="requirement-card selection-summary">
<div class="requirement-card-header">
<h3 class="requirement-card-title">
<i class="fas fa-clipboard-check"></i>
<?= htmlspecialchars(lang('selection_summary')) ?>
</h3>
</div>
<div class="requirement-card-body">
<div class="summary-grid">
<div class="summary-item">
<span class="summary-label"><?= htmlspecialchars(lang('admin_templates')) ?></span>
<span class="summary-count" id="summary-admin-templates">0</span>
</div>
<div class="summary-item">
<span class="summary-label"><?= htmlspecialchars(lang('user_templates')) ?></span>
<span class="summary-count" id="summary-user-templates">0</span>
</div>
<div class="summary-item">
<span class="summary-label"><?= htmlspecialchars(lang('modules')) ?></span>
<span class="summary-count" id="summary-modules">0</span>
</div>
<div class="summary-item">
<span class="summary-label"><?= htmlspecialchars(lang('plugins')) ?></span>
<span class="summary-count" id="summary-plugins">0</span>
</div>
</div>
</div>
</div>
<!-- 네비게이션 -->
<div class="btn-group btn-group-spread">
<button type="button" onclick="goToStep(3)" class="btn btn-secondary">
<?= htmlspecialchars(lang('previous')) ?>
</button>
<button type="submit" id="submit-btn" class="btn btn-primary" disabled>
<?= htmlspecialchars(lang('next')) ?>
</button>
</div>
</form>
</div>
<script>
// Step 4 번역 키 전달
window.EXTENSION_LABELS = {
version: <?= json_encode(lang('version')) ?>,
select: <?= json_encode(lang('select')) ?>,
selected: <?= json_encode(lang('selected')) ?>,
dependencies: <?= json_encode(lang('dependencies')) ?>,
admin_template_required: <?= json_encode(lang('admin_template_required')) ?>,
saving: <?= json_encode(lang('saving')) ?>,
save_failed: <?= json_encode(lang('save_failed')) ?>,
next: <?= json_encode(lang('next')) ?>,
extension_load_failed: <?= json_encode(lang('extension_load_failed')) ?>
};
</script>
+64
View File
@@ -0,0 +1,64 @@
<!DOCTYPE html>
<html lang="<?= htmlspecialchars($lang) ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>403 Forbidden</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background-color: #f5f5f5;
}
.error-container {
background: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
max-width: 500px;
text-align: center;
}
h1 {
color: #e74c3c;
margin-top: 0;
}
p {
color: #666;
line-height: 1.6;
}
.back-button {
display: inline-block;
margin-top: 1rem;
padding: 0.5rem 1rem;
background-color: #3498db;
color: white;
text-decoration: none;
border-radius: 4px;
}
.back-button:hover {
background-color: #2980b9;
}
@media (prefers-color-scheme: dark) {
body { background-color: #1e293b; }
.error-container { background: #334155; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4); }
h1 { color: #f87171; }
p { color: #cbd5e1; }
.back-button { background-color: #60a5fa; }
.back-button:hover { background-color: #3b82f6; }
}
</style>
</head>
<body>
<div class="error-container">
<h1>403 Forbidden</h1>
<p><?= htmlspecialchars($message) ?></p>
<a href="javascript:history.back()" class="back-button">
<?= $lang === 'ko' ? '뒤로 가기' : 'Go Back' ?>
</a>
</div>
</body>
</html>
+224
View File
@@ -0,0 +1,224 @@
<?php
/**
* Step 5: 설치 진행
*
* Composer 의존성 설치, .env 파일 생성, Artisan 명령 실행, 관리자 계정 생성,
* 선택한 확장 기능(템플릿, 모듈, 플러그인) 설치를 수행합니다.
* 진행률 표시와 실시간 로그를 통해 사용자에게 피드백을 제공합니다.
*/
// 설정 정보 가져오기 (state.json에서 로드 - 다른 브라우저에서도 접근 가능)
$config = $state['config'] ?? $_SESSION['install_config'] ?? [];
?>
<!-- 필수 파일 생성 안내 섹션 (JS에서 제어, 기본 숨김) -->
<div id="env-setup-section" class="installer-container installer-container-wide hidden">
<div class="requirement-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title"><?= htmlspecialchars(lang('file_setup_title')) ?></h3>
</div>
<div class="requirement-card-body">
<p><?= htmlspecialchars(lang('file_setup_description')) ?></p>
<!-- 누락 파일 목록 (JS에서 동적 표시) -->
<ul id="missing-files-list" class="missing-files"></ul>
<!-- 명령어 안내 (절대경로) -->
<p><?= htmlspecialchars(lang('file_setup_guide')) ?></p>
<div class="code-box">
<pre id="file-setup-command"></pre>
<button class="btn-copy" onclick="copySetupCommand()"><?= htmlspecialchars(lang('copy_command')) ?></button>
</div>
<!-- 상대경로 명령어 -->
<p class="fix-guide-hint" id="file-setup-relative-hint" style="display:none;"><?= htmlspecialchars(lang('or_relative_path')) ?></p>
<div class="code-box" id="file-setup-relative-box" style="display:none;">
<pre id="file-setup-command-relative"></pre>
<button class="btn-copy" onclick="copySetupCommandRelative()"><?= htmlspecialchars(lang('copy_command')) ?></button>
</div>
<!-- 확인 버튼 -->
<div class="env-check-actions">
<button id="env-recheck-btn" class="btn btn-primary" onclick="recheckFiles()"><?= htmlspecialchars(lang('file_check_button')) ?></button>
<span id="env-check-status" class="hidden"></span>
</div>
</div>
</div>
</div>
<div class="installer-container installer-container-wide">
<div class="installer-header-with-abort">
<h1 id="installer-title" class="installer-title"><?= htmlspecialchars(lang('installation_title')) ?></h1>
<button id="abort-installation-btn" class="btn-abort" onclick="abortInstallation()" style="display: none;">
<svg class="abort-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<?= htmlspecialchars(lang('abort_installation')) ?>
</button>
</div>
<!-- 완료 섹션 -->
<?php
$completionButtons = '<a href="../admin/login" class="btn btn-success">' . htmlspecialchars(lang('go_to_admin_login')) . '</a>';
echo renderInstallResultSection('completion', 'success', 'installation_completed', 'installation_complete_message', $completionButtons);
?>
<!-- 중단 섹션 -->
<?php
$abortedButtons = '<button onclick="resumeInstallationFromAborted()" class="btn btn-primary">' . htmlspecialchars(lang('resume_continue')) . '</button>
<button onclick="goToSettingsWithConfirm()" class="btn btn-secondary">' . htmlspecialchars(lang('back_to_settings')) . '</button>';
echo renderInstallResultSection('aborted', 'warning', 'installation_aborted', 'installation_aborted_message', $abortedButtons);
?>
<!-- 실패 섹션 -->
<?php
$failureButtons = '<button onclick="retryInstallation()" class="btn btn-primary">' . htmlspecialchars(lang('retry_installation')) . '</button>
<button onclick="goToSettingsWithConfirm()" class="btn btn-secondary">' . htmlspecialchars(lang('back_to_settings')) . '</button>';
echo renderInstallResultSection('failure', 'error', 'installation_failed', '', $failureButtons);
?>
<div class="alert alert-warning" id="install-warning">
⚠ <?= htmlspecialchars(lang('do_not_close_page')) ?>
</div>
<!-- 설치 진행 상황 카드 -->
<div class="requirement-card">
<div class="requirement-card-header" id="installation-card-header" onclick="toggleInstallationCard()">
<h3 class="requirement-card-title">
<?= htmlspecialchars(lang('progress_status')) ?>
<span id="install-toggle-icon" class="toggle-icon-inline hidden">▼</span>
</h3>
</div>
<div id="installation-card-body" class="requirement-card-body">
<!-- 전체 진행률 -->
<div class="progress-section">
<div class="progress-header">
<span class="progress-label"><?= htmlspecialchars(lang('overall_progress')) ?></span>
<span id="overall-percentage" class="progress-percentage">0%</span>
</div>
<div class="progress-bar-bg">
<div id="overall-progress-bar" class="progress-bar-fill" style="width: 0%"></div>
</div>
<p id="current-task" class="progress-status"><?= htmlspecialchars(lang('preparing')) ?></p>
</div>
<!-- 작업 목록 -->
<div id="task-list" class="task-list">
<!-- JavaScript로 동적 생성 -->
</div>
<!-- 로그 섹션 헤더 -->
<h4 class="log-section-title"><?= htmlspecialchars(lang('installation_log')) ?></h4>
<!-- 로그 출력 -->
<div class="install-log" id="install-log">
<div class="log-placeholder"><?= htmlspecialchars(lang('waiting_installation')) ?></div>
</div>
</div>
</div>
</div>
<?php
// 선택된 확장 기능 가져오기
$selectedExtensions = $state['selected_extensions'] ?? [];
$adminTemplates = $selectedExtensions['admin_templates'] ?? [];
$userTemplates = $selectedExtensions['user_templates'] ?? [];
$modules = $selectedExtensions['modules'] ?? [];
$plugins = $selectedExtensions['plugins'] ?? [];
?>
<script>
// Step 5 전용 데이터 전달 (INSTALLER_BASE_URL과 INSTALLER_LANG는 footer.php에서 처리)
window.INSTALLER_CONFIG = <?= json_encode($config) ?>;
window.INSTALLER_SELECTED_EXTENSIONS = <?= json_encode($selectedExtensions) ?>;
window.INSTALLER_EXTENSION_NAMES = <?= json_encode($state['extension_names'] ?? []) ?>;
// 작업 그룹 정의
window.INSTALLER_TASK_GROUPS = [
{
id: 'environment',
labelKey: 'task_group_environment',
tasks: [
{ id: 'composer_check' },
{ id: 'composer_install' },
{ id: 'env_update' },
{ id: 'key_generate' }
]
},
{
id: 'database',
labelKey: 'task_group_database',
tasks: [
{ id: 'db_migrate' },
{ id: 'db_seed' }
]
},
{
id: 'admin_templates',
labelKey: 'task_group_admin_templates',
tasks: <?= json_encode(array_map(function($tpl) {
return [
['id' => 'template_install', 'target' => $tpl],
['id' => 'template_activate', 'target' => $tpl]
];
}, $adminTemplates)) ?>
},
{
id: 'modules',
labelKey: 'task_group_modules',
tasks: <?= json_encode(array_map(function($mod) {
return [
['id' => 'module_install', 'target' => $mod],
['id' => 'module_activate', 'target' => $mod]
];
}, $modules)) ?>
},
{
id: 'plugins',
labelKey: 'task_group_plugins',
tasks: <?= json_encode(array_map(function($plg) {
return [
['id' => 'plugin_install', 'target' => $plg],
['id' => 'plugin_activate', 'target' => $plg]
];
}, $plugins)) ?>
},
{
id: 'user_templates',
labelKey: 'task_group_user_templates',
tasks: <?= json_encode(array_map(function($tpl) {
return [
['id' => 'user_template_install', 'target' => $tpl],
['id' => 'user_template_activate', 'target' => $tpl]
];
}, $userTemplates)) ?>
},
{
id: 'finalize',
labelKey: 'task_group_finalize',
tasks: [
{ id: 'create_settings_json' },
{ id: 'cache_clear' },
{ id: 'complete_flag' }
]
}
];
// 평탄화된 작업 목록 생성 (하위 호환성 유지)
window.INSTALLER_TASKS = (function() {
const tasks = [];
INSTALLER_TASK_GROUPS.forEach(group => {
if (!group.tasks || group.tasks.length === 0) return;
group.tasks.forEach(taskOrArray => {
if (Array.isArray(taskOrArray)) {
taskOrArray.forEach(t => tasks.push({ ...t, group: group.id }));
} else {
tasks.push({ ...taskOrArray, group: group.id });
}
});
});
return tasks;
})();
</script>
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow: