func.py 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  1. # Init
  2. import os
  3. import sys
  4. import platform
  5. import smtplib
  6. import shutil
  7. import json
  8. import datetime
  9. import ipaddress
  10. import subprocess
  11. import email.mime.text
  12. import email.utils
  13. import email.header
  14. # Init-Version
  15. with open('version.json', encoding = 'utf8') as file_data:
  16. version_list = json.loads(file_data.read())
  17. print('Version : ' + version_list['r_ver'])
  18. print('DB set version : ' + version_list['c_ver'])
  19. print('Skin set version : ' + version_list['s_ver'])
  20. # Init-PIP_Install
  21. data_up_date = 1
  22. if os.path.exists(os.path.join('data', 'version.json')):
  23. with open(os.path.join('data', 'version.json'), encoding = 'utf8') as file_data:
  24. data_load_ver = file_data.read()
  25. if data_load_ver == version_list['r_ver']:
  26. data_up_date = 0
  27. if os.getenv('NAMU_DOCKER') == 'O': # skip update check when run at docker
  28. data_up_date = 0
  29. if data_up_date == 1:
  30. with open(os.path.join('data', 'version.json'), 'w', encoding = 'utf8') as f:
  31. f.write(version_list['r_ver'])
  32. if platform.system() in ('Linux', 'Darwin', 'Windows'):
  33. python_ver = ''
  34. python_ver = str(sys.version_info.major) + '.' + str(sys.version_info.minor)
  35. run_list = [
  36. sys.executable,
  37. 'python' + python_ver,
  38. 'python3',
  39. 'python',
  40. 'py -' + python_ver
  41. ]
  42. user_opt = [] if getattr(sys, "base_prefix", sys.prefix) != sys.prefix else ["--user"]
  43. for exe_name in run_list:
  44. try:
  45. subprocess.check_call([exe_name, "-m", "pip", "install", "--upgrade", *user_opt, "-r", "requirements-optional.txt"])
  46. except:
  47. pass
  48. try:
  49. subprocess.check_call([exe_name, "-m", "pip", "install", "--upgrade", *user_opt, "-r", "requirements.txt"])
  50. subprocess.Popen([exe_name] + sys.argv)
  51. os._exit(0)
  52. except:
  53. pass
  54. else:
  55. print('Error : automatic installation is not supported.')
  56. print('Help : try "python3 -m pip install -r requirements.txt"')
  57. else:
  58. print('Error : automatic installation is not supported.')
  59. print('Help : try "python3 -m pip install -r requirements.txt"')
  60. else:
  61. print('PIP check pass')
  62. # Init-Load
  63. from .func_tool import *
  64. from .func_render import class_do_render
  65. from diff_match_patch import diff_match_patch
  66. import werkzeug.routing
  67. import werkzeug.debug
  68. import flask
  69. import asyncio
  70. import nest_asyncio
  71. import aiohttp
  72. import requests
  73. import psutil
  74. from PIL import Image
  75. try:
  76. import mysqlclient as pymysql
  77. except:
  78. import pymysql
  79. if sys.version_info < (3, 6):
  80. import sha3
  81. # Func
  82. # Func-main
  83. async def render_template(name, data, sub, menu, other = []):
  84. other_set = {}
  85. other_set["name"] = name
  86. other_set["data"] = data
  87. other_set["sub"] = [sub] + other
  88. other_set["menu"] = menu
  89. return await python_to_golang("post", other_set = other_set, path = "template")
  90. global_lang_data = {}
  91. global_some_set = {}
  92. def do_db_set(db_set):
  93. for for_a in db_set:
  94. global_func_some_set_do('db_' + for_a, db_set[for_a])
  95. global_some_set_do('db_' + for_a, db_set[for_a])
  96. class flask_data_or_variable:
  97. def __init__(self, flask_data, var_dict):
  98. if var_dict == {}:
  99. self.data = flask_data
  100. self.selected_flask = True
  101. else:
  102. self.data = var_dict
  103. self.selected_flask = False
  104. def get(self, dict_name, replace_data):
  105. if self.selected_flask == True:
  106. return self.data.get(dict_name, replace_data)
  107. else:
  108. if dict_name in self.data:
  109. return self.data[dict_name]
  110. else:
  111. return replace_data
  112. def global_some_set_do(set_name, data = None):
  113. global global_some_set
  114. if data != None:
  115. global_some_set[set_name] = data
  116. if set_name in global_some_set:
  117. return global_some_set[set_name]
  118. else:
  119. return None
  120. async def python_to_golang(func_name, other_set = {}, path = ''):
  121. headers = {}
  122. if flask.has_request_context():
  123. if "Cookie" in flask.request.headers:
  124. headers["Cookie"] = flask.request.headers["Cookie"]
  125. headers["X-Forwarded-For"] = ip_check()
  126. port_data = global_some_set_do("setup_golang_port")
  127. # print(func_name, other_set)
  128. if func_name == "same":
  129. async with aiohttp.ClientSession() as session:
  130. if flask.request.method == 'POST':
  131. form_data = flask.request.form.to_dict(flat = False)
  132. async with session.post('http://127.0.0.1:' + port_data + flask.request.path, data = form_data, headers = headers) as res:
  133. data = await res.text()
  134. return data
  135. else:
  136. async with session.get('http://127.0.0.1:' + port_data + flask.request.path, headers = headers) as res:
  137. data = await res.text()
  138. return data
  139. elif path != "":
  140. if func_name == "get":
  141. async with aiohttp.ClientSession() as session:
  142. async with session.get('http://127.0.0.1:' + port_data + "/api/" + path, headers = headers) as res:
  143. data = await res.text()
  144. return data
  145. elif func_name == "post":
  146. async with aiohttp.ClientSession() as session:
  147. async with session.post('http://127.0.0.1:' + port_data + "/api/" + path, data = json_dumps(other_set), headers = headers) as res:
  148. data = await res.text()
  149. return data
  150. elif func_name == "get_json":
  151. async with aiohttp.ClientSession() as session:
  152. async with session.get('http://127.0.0.1:' + port_data + "/api/" + path, headers = headers) as res:
  153. data = await res.json()
  154. return data
  155. else:
  156. async with aiohttp.ClientSession() as session:
  157. async with session.post('http://127.0.0.1:' + port_data + "/api/" + path, data = json_dumps(other_set), headers = headers) as res:
  158. data = await res.json()
  159. return data
  160. else:
  161. async with aiohttp.ClientSession() as session:
  162. async with session.post('http://127.0.0.1:' + port_data + '/compatible_api/' + func_name, data = json_dumps(other_set), headers = headers) as res:
  163. data = await res.json()
  164. if "response" in data and data["response"] == "error":
  165. raise Exception(f"API returned error: {data}")
  166. else:
  167. return data
  168. async def opennamu_make_list(left = '', right = '', bottom = '', class_name = ''):
  169. data_html = f'<span class="{class_name}">'
  170. data_html += '<div class="opennamu_recent_change">'
  171. data_html += left
  172. data_html += '<div style="float: right;">'
  173. data_html += right
  174. data_html += '</div>'
  175. data_html += '<div style="clear: both;"></div>'
  176. if bottom != '':
  177. data_html += '<hr>'
  178. data_html += bottom
  179. data_html += '</div>'
  180. data_html += '<hr class="main_hr">'
  181. data_html += '</span>'
  182. return data_html
  183. # Func-init
  184. def get_init_set_list(need = 'all'):
  185. init_set_list = {
  186. 'host' : {
  187. 'display' : 'Host',
  188. 'require' : 'conv',
  189. 'default' : '0.0.0.0'
  190. }, 'port' : {
  191. 'display' : 'Port',
  192. 'require' : 'conv',
  193. 'default' : '3000'
  194. }, 'golang_port' : {
  195. 'display' : 'Golang port',
  196. 'require' : 'conv',
  197. 'default' : '3001'
  198. }, 'language' : {
  199. 'display' : 'Language',
  200. 'require' : 'select',
  201. 'default' : 'ko-KR',
  202. 'list' : ['ko-KR', 'en-US']
  203. }, 'markup' : {
  204. 'display' : 'Markup',
  205. 'require' : 'select',
  206. 'default' : 'namumark',
  207. 'list' : ['namumark', 'namumark_beta', 'macromark', 'markdown', 'custom', 'raw']
  208. }, 'encode' : {
  209. 'display' : 'Encryption method',
  210. 'require' : 'select',
  211. 'default' : 'sha3',
  212. 'list' : ['sha3', 'sha3-salt', 'sha3-512', 'sha3-512-salt']
  213. }
  214. }
  215. if need == 'all':
  216. return init_set_list
  217. else:
  218. return init_set_list[need]
  219. class get_db_connect:
  220. def __init__(self, db_type = '', init_mode = False):
  221. self.db_set = {}
  222. self.init_mode = init_mode
  223. for for_a in ("db_type", "db_name"):
  224. self.db_set[for_a] = global_some_set_do(for_a)
  225. if db_type != '':
  226. self.db_set['db_type'] = db_type
  227. if self.db_set['db_type'] == 'mysql':
  228. for for_a in ("db_mysql_host", "db_mysql_user", "db_mysql_pw", "db_mysql_port"):
  229. self.db_set[for_a] = global_some_set_do(for_a)
  230. def __enter__(self):
  231. if self.db_set['db_type'] == 'sqlite':
  232. self.conn = sqlite3.connect(
  233. self.db_set['db_name'] + '.db',
  234. check_same_thread = False,
  235. isolation_level = None
  236. )
  237. else:
  238. # try connect
  239. # print('Wait for DB connection...')
  240. self.conn = None
  241. try_cnt = 1
  242. max_try = 30
  243. while self.conn == None and try_cnt <= max_try:
  244. try:
  245. if self.init_mode:
  246. try:
  247. self.conn = pymysql.connect(
  248. host = self.db_set['db_mysql_host'],
  249. user = self.db_set['db_mysql_user'],
  250. password = self.db_set['db_mysql_pw'],
  251. charset = 'utf8mb4',
  252. port = int(self.db_set['db_mysql_port']),
  253. autocommit = True,
  254. db = self.db_set['db_name']
  255. )
  256. except pymysql.err.OperationalError:
  257. self.conn = pymysql.connect(
  258. host = self.db_set['db_mysql_host'],
  259. user = self.db_set['db_mysql_user'],
  260. password = self.db_set['db_mysql_pw'],
  261. charset = 'utf8mb4',
  262. port = int(self.db_set['db_mysql_port']),
  263. autocommit = True
  264. )
  265. else:
  266. self.conn = pymysql.connect(
  267. host = self.db_set['db_mysql_host'],
  268. user = self.db_set['db_mysql_user'],
  269. password = self.db_set['db_mysql_pw'],
  270. charset = 'utf8mb4',
  271. port = int(self.db_set['db_mysql_port']),
  272. autocommit = True,
  273. db = self.db_set['db_name']
  274. )
  275. except pymysql.err.OperationalError as err:
  276. if try_cnt + 1 > max_try:
  277. raise err
  278. finally:
  279. if self.conn == None:
  280. try_cnt += 1
  281. time.sleep(1)
  282. if self.conn == None:
  283. raise Exception("Unable to connect database")
  284. # print('DB connected')
  285. return self.conn
  286. def __exit__(self, exc_type, exc_value, traceback):
  287. self.conn.commit()
  288. self.conn.close()
  289. # class get_whoosh_connect:
  290. class class_check_json:
  291. def do_check_set_json(self):
  292. if os.getenv('NAMU_DB') or os.getenv('NAMU_DB_TYPE'):
  293. set_data = {}
  294. set_data['db'] = os.getenv('NAMU_DB') if os.getenv('NAMU_DB') else 'data'
  295. set_data['db_type'] = os.getenv('NAMU_DB_TYPE') if os.getenv('NAMU_DB_TYPE') else 'sqlite'
  296. else:
  297. if os.path.exists(os.path.join('data', 'set.json')):
  298. db_set_list = ['db', 'db_type']
  299. with open(os.path.join('data', 'set.json'), encoding = 'utf8') as file_data:
  300. set_data = json_loads(file_data.read())
  301. for i in db_set_list:
  302. if not i in set_data:
  303. os.remove(os.path.join('data', 'set.json'))
  304. break
  305. if not os.path.exists(os.path.join('data', 'set.json')):
  306. set_data = {}
  307. normal_db_type = ['sqlite', 'mysql']
  308. print('DB type (' + normal_db_type[0] + ') [' + ', '.join(normal_db_type) + '] : ', end = '')
  309. try:
  310. data_get = str(input())
  311. except EOFError:
  312. print("\nInput is not available. You can set the environment variable NAMU_DB_TYPE instead.")
  313. print("No input detected. Using default value.")
  314. data_get = ''
  315. if data_get == '' or not data_get in normal_db_type:
  316. set_data['db_type'] = 'sqlite'
  317. else:
  318. set_data['db_type'] = data_get
  319. all_src = []
  320. if set_data['db_type'] == 'sqlite':
  321. for i_data in os.listdir("."):
  322. f_src = re.search(r"(.+)\.db$", i_data)
  323. if f_src:
  324. all_src += [f_src.group(1)]
  325. print('DB name (data) [' + ', '.join(all_src) + '] : ', end = '')
  326. data_get = str(input())
  327. if data_get == '':
  328. set_data['db'] = 'data'
  329. else:
  330. set_data['db'] = data_get
  331. with open(os.path.join('data', 'set.json'), 'w', encoding = 'utf8') as f:
  332. f.write(json_dumps(set_data))
  333. print('DB name : ' + set_data['db'])
  334. print('DB type : ' + set_data['db_type'])
  335. data_db_set = {}
  336. data_db_set['name'] = set_data['db']
  337. data_db_set['type'] = set_data['db_type']
  338. return data_db_set
  339. def do_check_mysql_json(self, data_db_set):
  340. def do_check_mysql_env():
  341. env_keys = ['NAMU_DB_HOST', 'NAMU_DB_PORT', 'NAMU_DB_USER', 'NAMU_DB_PASSWORD']
  342. vaild = False
  343. for key in env_keys:
  344. if os.getenv(key):
  345. vaild = True
  346. break
  347. return vaild
  348. if do_check_mysql_env():
  349. # ['user', 'password', 'host', 'port']
  350. set_data_mysql = {}
  351. set_data_mysql['host'] = os.getenv('NAMU_DB_HOST') if os.getenv('NAMU_DB_HOST') else '127.0.0.1'
  352. set_data_mysql['port'] = os.getenv('NAMU_DB_PORT') if os.getenv('NAMU_DB_PORT') else 3306
  353. if not os.getenv('NAMU_DB_USER'):
  354. raise Exception('Error : NAMU_DB_USER env not set')
  355. else:
  356. set_data_mysql['user'] = os.getenv('NAMU_DB_USER')
  357. if not os.getenv('NAMU_DB_PASSWORD'):
  358. raise Exception('Error : NAMU_DB_PASSWORD env not set')
  359. else:
  360. set_data_mysql['password'] = os.getenv('NAMU_DB_PASSWORD')
  361. elif os.path.exists(os.path.join('data', 'mysql.json')):
  362. db_set_list = ['user', 'password', 'host', 'port']
  363. with open(os.path.join('data', 'mysql.json'), encoding = 'utf8') as file_data:
  364. set_data = json_loads(file_data.read())
  365. for i in db_set_list:
  366. if not i in set_data:
  367. os.remove(os.path.join('data', 'mysql.json'))
  368. break
  369. set_data_mysql = set_data
  370. elif not os.path.exists(os.path.join('data', 'mysql.json')):
  371. set_data_mysql = {}
  372. print('DB user ID : ', end = '')
  373. set_data_mysql['user'] = str(input())
  374. print('DB password : ', end = '')
  375. set_data_mysql['password'] = str(input())
  376. print('DB host (127.0.0.1) : ', end = '')
  377. set_data_mysql['host'] = str(input())
  378. if set_data_mysql['host'] == '':
  379. set_data_mysql['host'] = '127.0.0.1'
  380. print('DB port (3306) : ', end = '')
  381. set_data_mysql['port'] = str(input())
  382. if set_data_mysql['port'] == '':
  383. set_data_mysql['port'] = '3306'
  384. with open(os.path.join('data', 'mysql.json'), 'w', encoding = 'utf8') as f:
  385. f.write(json_dumps(set_data_mysql))
  386. data_db_set['mysql_user'] = set_data_mysql['user']
  387. data_db_set['mysql_pw'] = set_data_mysql['password']
  388. if 'host' in set_data_mysql:
  389. data_db_set['mysql_host'] = set_data_mysql['host']
  390. else:
  391. data_db_set['mysql_host'] = '127.0.0.1'
  392. if 'port' in set_data_mysql:
  393. data_db_set['mysql_port'] = set_data_mysql['port']
  394. else:
  395. data_db_set['mysql_port'] = '3306'
  396. return data_db_set
  397. def __init__(self):
  398. self.data_db_set = {}
  399. def __new__(cls):
  400. instance = super().__new__(cls)
  401. cls.data_db_set = instance.do_check_set_json()
  402. if cls.data_db_set['type'] == 'mysql':
  403. cls.data_db_set = instance.do_check_mysql_json(cls.data_db_set)
  404. return cls.data_db_set
  405. def get_db_table_list():
  406. # DB table
  407. # Init-Create_DB
  408. # --이거 개편한다더니 도대체 언제?--
  409. create_data = {}
  410. # 폐지 예정 (data_set으로 통합)
  411. create_data['data_set'] = ['doc_name', 'doc_rev', 'set_name', 'set_data']
  412. create_data['data'] = ['title', 'data', 'type']
  413. create_data['history'] = ['id', 'title', 'data', 'date', 'ip', 'send', 'leng', 'hide', 'type']
  414. create_data['rc'] = ['id', 'title', 'date', 'type']
  415. create_data['acl'] = ['title', 'data', 'type']
  416. # 개편 예정 (data_link로 변경)
  417. create_data['back'] = ['title', 'link', 'type', 'data']
  418. # 폐지 예정 (topic_set으로 통합) [가장 시급]
  419. create_data['topic_set'] = ['thread_code', 'set_name', 'set_id', 'set_data']
  420. create_data['rd'] = ['title', 'sub', 'code', 'date', 'band', 'stop', 'agree', 'acl']
  421. create_data['topic'] = ['id', 'data', 'date', 'ip', 'block', 'top', 'code']
  422. # 폐지 예정 (user_set으로 통합)
  423. create_data['rb'] = ['block', 'end', 'today', 'blocker', 'why', 'band', 'login', 'ongoing']
  424. # 개편 예정 (wiki_set과 wiki_filter과 wiki_vote으로 변경)
  425. create_data['other'] = ['name', 'data', 'coverage']
  426. create_data['html_filter'] = ['html', 'kind', 'plus', 'plus_t']
  427. create_data['vote'] = ['name', 'id', 'subject', 'data', 'user', 'type', 'acl']
  428. # 개편 예정 (auth와 auth_log로 변경)
  429. create_data['alist'] = ['name', 'acl']
  430. create_data['re_admin'] = ['who', 'what', 'time']
  431. # 개편 예정 (user_notice와 user_agent로 변경)
  432. create_data['ua_d'] = ['name', 'ip', 'ua', 'today', 'sub']
  433. create_data['user_set'] = ['name', 'id', 'data']
  434. create_data['user_notice'] = ['id', 'name', 'data', 'date', 'readme']
  435. create_data['bbs_set'] = ['set_name', 'set_code', 'set_id', 'set_data']
  436. create_data['bbs_data'] = ['set_name', 'set_code', 'set_id', 'set_data']
  437. return create_data
  438. async def update(conn, ver_num, set_data):
  439. curs = conn.cursor()
  440. # 업데이트 하위 호환 유지 함수
  441. if ver_num < 3160027:
  442. print('Add init set')
  443. set_init(conn)
  444. ver_num = 3160027
  445. if ver_num < 3170002:
  446. curs.execute(db_change("select html from html_filter where kind = 'extension'"))
  447. if not curs.fetchall():
  448. for i in ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']:
  449. curs.execute(db_change("insert into html_filter (html, kind) values (?, 'extension')"), [i])
  450. ver_num = 3170002
  451. if ver_num < 3170400:
  452. curs.execute(db_change("select title, sub, code from topic where id = '1'"))
  453. for i in curs.fetchall():
  454. curs.execute(db_change("update topic set code = ? where title = ? and sub = ?"), [i[2], i[0], i[1]])
  455. curs.execute(db_change("update rd set code = ? where title = ? and sub = ?"), [i[2], i[0], i[1]])
  456. ver_num = 3170400
  457. if ver_num < 3171800:
  458. curs.execute(db_change("select data from other where name = 'recaptcha'"))
  459. change_rec = curs.fetchall()
  460. if change_rec and change_rec[0][0] != '':
  461. new_rec = re.search(r'data-sitekey="([^"]+)"', change_rec[0][0])
  462. if new_rec:
  463. curs.execute(db_change("update other set data = ? where name = 'recaptcha'"), [new_rec.group(1)])
  464. else:
  465. curs.execute(db_change("update other set data = '' where name = 'recaptcha'"))
  466. curs.execute(db_change("update other set data = '' where name = 'sec_re'"))
  467. ver_num = 3171800
  468. if ver_num < 3172800 and set_data['type'] == 'mysql':
  469. get_data_mysql = json_loads(open('data/mysql.json', encoding = 'utf8').read())
  470. with open('data/mysql.json', 'w') as f:
  471. f.write('{ "user" : "' + get_data_mysql['user'] + '", "password" : "' + get_data_mysql['password'] + '", "host" : "127.0.0.1" }')
  472. ver_num = 3172800
  473. if ver_num < 3183603:
  474. curs.execute(db_change("select block from ban where band = 'O'"))
  475. for i in curs.fetchall():
  476. curs.execute(db_change("update ban set block = ?, band = 'regex' where block = ? and band = 'O'"), ['^' + i[0].replace('.', '\\.'), i[0]])
  477. curs.execute(db_change("select block from rb where band = 'O'"))
  478. for i in curs.fetchall():
  479. curs.execute(db_change("update rb set block = ?, band = 'regex' where block = ? and band = 'O'"), ['^' + i[0].replace('.', '\\.'), i[0]])
  480. ver_num = 3183603
  481. if ver_num < 3190201:
  482. today_time = get_time()
  483. curs.execute(db_change("select block, end, why, band, login from ban"))
  484. for i in curs.fetchall():
  485. curs.execute(db_change("insert into rb (block, end, today, why, band, login, ongoing) values (?, ?, ?, ?, ?, ?, ?)"), [i[0], i[1], today_time, i[2], i[3], i[4], '1'])
  486. ver_num = 3190201
  487. if ver_num < 3191301:
  488. curs.execute(db_change('select id, title, date from history where not title like "user:%" order by date desc limit 50'))
  489. data_list = curs.fetchall()
  490. for get_data in data_list:
  491. curs.execute(db_change("insert into rc (id, title, date, type) values (?, ?, ?, 'normal')"), [get_data[0], get_data[1], get_data[2]])
  492. ver_num = 3191301
  493. if ver_num < 3202400:
  494. curs.execute(db_change("select data from other where name = 'update'"))
  495. get_data = curs.fetchall()
  496. if get_data and get_data[0][0] == 'master':
  497. curs.execute(db_change("update other set data = 'beta' where name = 'update'"), [])
  498. ver_num = 3202400
  499. if ver_num < 3202600:
  500. curs.execute(db_change("select name, regex, sub from filter"))
  501. for i in curs.fetchall():
  502. curs.execute(db_change("insert into html_filter (html, kind, plus, plus_t) values (?, 'regex_filter', ?, ?)"), [i[0], i[1], i[2]])
  503. curs.execute(db_change("select title, link, icon from inter"))
  504. for i in curs.fetchall():
  505. curs.execute(db_change("insert into html_filter (html, kind, plus, plus_t) values (?, 'inter_wiki', ?, ?)"), [i[0], i[1], i[2]])
  506. ver_num = 3202600
  507. if ver_num < 3203400:
  508. curs.execute(db_change("select user, css from custom"))
  509. for i in curs.fetchall():
  510. curs.execute(db_change("insert into user_set (name, id, data) values ('custom_css', ?, ?)"), [re.sub(r' \(head\)$', '', i[0]), i[1]])
  511. ver_num = 3203400
  512. if ver_num < 3205500:
  513. curs.execute(db_change("select title, decu, dis, view, why from acl"))
  514. for i in curs.fetchall():
  515. curs.execute(db_change("insert into acl (title, data, type) values (?, ?, ?)"), [i[0], i[1], 'decu'])
  516. curs.execute(db_change("insert into acl (title, data, type) values (?, ?, ?)"), [i[0], i[2], 'dis'])
  517. curs.execute(db_change("insert into acl (title, data, type) values (?, ?, ?)"), [i[0], i[3], 'view'])
  518. curs.execute(db_change("insert into acl (title, data, type) values (?, ?, ?)"), [i[0], i[4], 'why'])
  519. ver_num = 3205500
  520. if ver_num < 3300101:
  521. # 캐시 초기화
  522. curs.execute(db_change('delete from cache_data'))
  523. ver_num = 3300101
  524. if ver_num < 3300301:
  525. # regex_filter 오류 해결
  526. curs.execute(db_change('delete from html_filter where kind = "regex_filter" and html is null'))
  527. ver_num = 3300301
  528. if ver_num < 3302302:
  529. # user이랑 user_set 테이블의 통합
  530. curs.execute(db_change('select id, pw, acl, date, encode from user'))
  531. for i in curs.fetchall():
  532. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['pw', i[0], i[1]])
  533. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['acl', i[0], i[2]])
  534. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['date', i[0], i[3]])
  535. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['encode', i[0], i[4]])
  536. ver_num = 3302302
  537. if ver_num < 3400101:
  538. # user_set이랑 user_application 테이블의 통합
  539. curs.execute(db_change('select id, pw, date, encode, question, answer, ip, ua, email from user_application'))
  540. for i in curs.fetchall():
  541. sql_data = {}
  542. sql_data['id'] = i[0]
  543. sql_data['pw'] = i[1]
  544. sql_data['date'] = i[2]
  545. sql_data['encode'] = i[3]
  546. sql_data['question'] = i[4]
  547. sql_data['answer'] = i[5]
  548. sql_data['ip'] = i[6]
  549. sql_data['ua'] = i[7]
  550. sql_data['email'] = i[8]
  551. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['application', i[0], json_dumps(sql_data)])
  552. ver_num = 3400101
  553. if ver_num < 3500105:
  554. curs.execute(db_change('delete from acl where title like "file:%" and data = "admin" and type like "decu%"'))
  555. ver_num = 3500105
  556. if ver_num < 3500106:
  557. curs.execute(db_change("select data from other where name = 'domain'"))
  558. db_data = curs.fetchall()
  559. if db_data and db_data[0][0] != '':
  560. db_data = db_data[0][0]
  561. db_data = re.match(r'[^/]+\/\/([^/]+)', db_data)
  562. if db_data:
  563. db_data = db_data.group(1)
  564. curs.execute(db_change("update other set data = ? where name = 'domain'"), [db_data])
  565. else:
  566. curs.execute(db_change("update other set data = '' where name = 'domain'"))
  567. ver_num = 3500106
  568. if ver_num < 3500107:
  569. db_table_list = get_db_table_list()
  570. for for_a in db_table_list:
  571. for for_b in db_table_list[for_a]:
  572. curs.execute(db_change("update " + for_a + " set " + for_b + " = '' where " + for_b + " is null"))
  573. ver_num = 3500107
  574. if ver_num < 3500113:
  575. db_table_list = get_db_table_list()
  576. for for_a in db_table_list:
  577. for for_b in db_table_list[for_a]:
  578. curs.execute(db_change("update " + for_a + " set " + for_b + " = '' where " + for_b + " is null"))
  579. ver_num = 3500113
  580. if ver_num < 3500114:
  581. curs.execute(db_change('delete from alarm'))
  582. ver_num = 3500114
  583. if ver_num < 3500354:
  584. curs.execute(db_change("select data from other where name = 'robot'"))
  585. db_data = curs.fetchall()
  586. if db_data:
  587. robot_default = '' + \
  588. 'User-agent: *\n' + \
  589. 'Disallow: /\n' + \
  590. 'Allow: /$\n' + \
  591. 'Allow: /image/\n' + \
  592. 'Allow: /views/\n' + \
  593. 'Allow: /w/' + \
  594. ''
  595. if db_data[0][0] == robot_default:
  596. curs.execute(db_change("insert into other (name, data, coverage) values ('robot_default', 'on', '')"))
  597. ver_num = 3500354
  598. if ver_num < 3500355:
  599. # other coverage 오류 해결
  600. curs.execute(db_change("update other set coverage = '' where coverage is null"))
  601. ver_num = 3500355
  602. if ver_num < 3500358:
  603. curs.execute(db_change("drop index history_index"))
  604. curs.execute(db_change("create index history_index on history (title, ip)"))
  605. ver_num = 3500358
  606. if ver_num < 3500360:
  607. # 마지막 편집 따로 기록하도록
  608. # create_data['data_set'] = ['doc_name', 'doc_rev', 'set_name', 'set_data']
  609. print("Update 3500360...")
  610. curs.execute(db_change('delete from data_set where set_name = "last_edit"'))
  611. curs.execute(db_change("select title from data"))
  612. db_data = curs.fetchall()
  613. for for_a in db_data:
  614. curs.execute(db_change("select date from history where title = ? order by date desc limit 1"), [for_a[0]])
  615. db_data_2 = curs.fetchall()
  616. if db_data_2:
  617. curs.execute(db_change("insert into data_set (doc_name, doc_rev, set_name, set_data) values (?, '', 'last_edit', ?)"), [for_a[0], db_data_2[0][0]])
  618. curs.execute(db_change('delete from acl where title like "file:%" and data = "admin" and type like "decu%"'))
  619. print("Update 3500360 complete")
  620. ver_num = 3500360
  621. if ver_num < 3500361:
  622. # curs.execute(db_change('select id from user_set where name = "email" and data = ?'), [user_email])
  623. curs.execute(db_change('select id from user_set where name = "email"'))
  624. for db_data in curs.fetchall():
  625. if ip_or_user(db_data[0]) == 1:
  626. curs.execute(db_change('delete from user_set where id = ? and name = "email"'), [db_data[0]])
  627. ver_num = 3500361
  628. # create_data['history'] = ['id', 'title', 'data', 'date', 'ip', 'send', 'leng', 'hide', 'type']
  629. # create_data['rc'] = ['id', 'title', 'date', 'type']
  630. if ver_num == 3500362:
  631. curs.execute(db_change("drop index history_index"))
  632. curs.execute(db_change("create index history_index on history (title, ip)"))
  633. if ver_num < 3500365:
  634. curs.execute(db_change("update back set data = '' where data is null"))
  635. ver_num = 3500365
  636. if ver_num < 3500371:
  637. curs.execute(db_change("delete from user_notice"))
  638. user_alarm_count = {}
  639. curs.execute(db_change("select name, data, date from alarm"))
  640. for db_data in curs.fetchall():
  641. if db_data[0] in user_alarm_count:
  642. user_alarm_count[db_data[0]] += 1
  643. else:
  644. user_alarm_count[db_data[0]] = 1
  645. curs.execute(db_change('insert into user_notice (id, name, data, date, readme) values (?, ?, ?, ?, "")'), [str(user_alarm_count[db_data[0]]), db_data[0], db_data[1], db_data[2]])
  646. ver_num = 3500371
  647. if ver_num < 3500372:
  648. # ID 글자 확인 호환용
  649. curs.execute(db_change('insert into html_filter (html, kind, plus, plus_t) values (?, ?, ?, ?)'), [r'(?:[^A-Za-zㄱ-ㅣ가-힣0-9])', 'name', '', ''])
  650. ver_num = 3500372
  651. if ver_num < 3500373:
  652. select_data = {}
  653. curs.execute(db_change("select name, id, data from user_set where name = 'application'"))
  654. for db_data in curs.fetchall():
  655. select_data[db_data[1]] = db_data
  656. curs.execute(db_change("delete from user_set where name = 'application'"))
  657. for db_data in select_data:
  658. curs.execute(db_change("insert into user_set (id, name, data) values (?, ?, ?)"), [select_data[db_data][1], select_data[db_data][0], select_data[db_data][2]])
  659. ver_num = 3500373
  660. if ver_num < 3500374:
  661. # ban 오류 해결
  662. curs.execute(db_change("update rb set ongoing = '' where ongoing is null"))
  663. curs.execute(db_change("update rb set login = '' where login is null"))
  664. ver_num = 3500374
  665. if ver_num < 3500375:
  666. curs.execute(db_change("select title, type, user from scan"))
  667. for for_a in curs.fetchall():
  668. type_data = 'watchlist' if for_a[1] == '' else 'star_doc'
  669. curs.execute(db_change("insert into user_set (id, name, data) values (?, ?, ?)"), [for_a[2], type_data, for_a[0]])
  670. ver_num = 3500375
  671. if ver_num < 3500376:
  672. curs.execute(db_change("select doc_name, doc_rev from data_set where set_name = 'edit_request_data'"))
  673. for for_a in curs.fetchall():
  674. curs.execute(db_change("select id from history where title = ? order by id + 0 desc limit 1"), [for_a[0]])
  675. get_data = curs.fetchall()
  676. if get_data and (int(get_data[0][0]) + 1) == int(for_a[1]):
  677. curs.execute(db_change("insert into data_set (doc_name, doc_rev, set_name, set_data) values (?, ?, 'edit_request_doing', '1')"), [for_a[0], for_a[1]])
  678. ver_num = 3500376
  679. if ver_num < 3500377 and set_data['type'] == 'sqlite':
  680. conn.execute('pragma journal_mode = delete')
  681. ver_num = 3500377
  682. if ver_num < 3500378:
  683. curs.execute(db_change("select title from data where title like 'category:%' or title like 'user:%' or title like 'file:%'"))
  684. for for_a in curs.fetchall():
  685. mode = ''
  686. if re.search('^user:', for_a[0]):
  687. mode = 'user'
  688. elif re.search('^file:', for_a[0]):
  689. mode = 'file'
  690. elif re.search('^category:', for_a[0]):
  691. mode = 'category'
  692. curs.execute(db_change('delete from data_set where doc_name = ? and set_name = "doc_type"'), [for_a[0]])
  693. curs.execute(db_change("insert into data_set (doc_name, doc_rev, set_name, set_data) values (?, '', 'doc_type', ?)"), [for_a[0], mode])
  694. ver_num = 3500378
  695. if ver_num < 3500379:
  696. curs.execute(db_change("select distinct doc_name from data_set where doc_rev = 'not_exist' or doc_rev = ''"))
  697. for for_a in curs.fetchall():
  698. data_set_exist = ''
  699. curs.execute(db_change("select title from data where title = ?"), [for_a[0]])
  700. if not curs.fetchall():
  701. data_set_exist = 'not_exist'
  702. curs.execute(db_change("update data_set set doc_rev = ? where doc_name = ? and (doc_rev = '' or doc_rev = 'not_exist')"), [data_set_exist, for_a[0]])
  703. ver_num = 3500379
  704. if ver_num < 20240513:
  705. curs.execute(db_change("update user_set set data = '☑️' where name = 'user_title' and data = '✅'"))
  706. ver_num = 20240513
  707. if ver_num < 20240732:
  708. curs.execute(db_change("select distinct name from alist where acl = 'owner'"))
  709. for for_a in curs.fetchall():
  710. curs.execute(db_change("select distinct id from user_set where name = 'acl' and data = ?"), [for_a[0]])
  711. for for_b in curs.fetchall():
  712. lang_name = 'en-US'
  713. if lang_name == 'ko-KR':
  714. print('메인 ACL이 권한으로 개편되면서 기존 설정 값이 날라갔으니 권한으로 재설정 해주세요.')
  715. else:
  716. print('As the main ACL has been reorganized into the auth, the existing setting values have been lost, so please reset it to the auth.')
  717. ver_num = 20240732
  718. print('Update completed')
  719. def set_init_always(conn, ver_num, run_mode):
  720. curs = conn.cursor()
  721. # 버전 기입
  722. curs.execute(db_change('delete from other where name = "ver"'))
  723. curs.execute(db_change('insert into other (name, data, coverage) values ("ver", ?, "")'), [ver_num])
  724. # 기본 권한 그룹 설정
  725. curs.execute(db_change('delete from alist where name = "owner"'))
  726. curs.execute(db_change('insert into alist (name, acl) values ("owner", "owner")'))
  727. curs.execute(db_change("select name from alist where name = 'user' limit 1"))
  728. if not curs.fetchall():
  729. curs.execute(db_change('insert into alist (name, acl) values ("user", "user")'))
  730. curs.execute(db_change("select name from alist where name = 'ip' limit 1"))
  731. if not curs.fetchall():
  732. curs.execute(db_change('insert into alist (name, acl) values ("ip", "ip")'))
  733. curs.execute(db_change("select name from alist where name = 'ban' limit 1"))
  734. if not curs.fetchall():
  735. curs.execute(db_change('insert into alist (name, acl) values ("ban", "view")'))
  736. # 문서 댓글용 게시판 생성
  737. bbs_num = '0'
  738. bbs_name = 'document_comment'
  739. bbs_type = 'comment'
  740. curs.execute(db_change("insert into bbs_set (set_name, set_code, set_id, set_data) values ('bbs_name', '', ?, ?)"), [bbs_num, bbs_name])
  741. curs.execute(db_change("insert into bbs_set (set_name, set_code, set_id, set_data) values ('bbs_type', '', ?, ?)"), [bbs_num, bbs_type])
  742. # 이미지 폴더 없으면 생성
  743. if not os.path.exists(load_image_url(conn)):
  744. os.makedirs(load_image_url(conn))
  745. # 비밀키 없으면 생성
  746. curs.execute(db_change('select data from other where name = "key"'))
  747. if not curs.fetchall():
  748. curs.execute(db_change('insert into other (name, data, coverage) values ("key", ?, "")'), [load_random_key()])
  749. # 솔트키 없으면 생성
  750. curs.execute(db_change('select data from other where name = "salt_key"'))
  751. if not curs.fetchall():
  752. curs.execute(db_change('insert into other (name, data, coverage) values ("salt_key", ?, "")'), [load_random_key(4)])
  753. # 문서 전체 갯수 없으면 생성
  754. curs.execute(db_change('select data from other where name = "count_all_title"'))
  755. if not curs.fetchall():
  756. curs.execute(db_change('insert into other (name, data, coverage) values ("count_all_title", "0", "")'))
  757. # 위키 접근 비밀번호 있으면 temp DB로 넘겨줌
  758. curs.execute(db_change('select data from other where name = "wiki_access_password_need"'))
  759. db_data = curs.fetchall()
  760. if db_data and db_data[0][0] != '':
  761. curs.execute(db_change('select data from other where name = "wiki_access_password"'))
  762. db_data = curs.fetchall()
  763. if db_data:
  764. global_some_set_do("wiki_access_password", db_data[0][0])
  765. curs.execute(db_change('select data from other where name = "load_ip_select"'))
  766. db_data = curs.fetchall()
  767. if db_data and db_data[0][0] != '':
  768. global_func_some_set_do("load_ip_select", db_data[0][0])
  769. # OS마다 실행 파일 설정
  770. exe_type = linux_exe_chmod()
  771. if platform.system() == 'Linux' or platform.system() == 'Darwin':
  772. os.system('chmod +x ./bin/' + exe_type)
  773. def linux_exe_chmod():
  774. exe_type = ''
  775. if platform.system() == 'Linux':
  776. if platform.machine() in ["AMD64", "x86_64"]:
  777. exe_type = 'main.amd64.bin'
  778. else:
  779. exe_type = 'main.arm64.bin'
  780. elif platform.system() == 'Darwin':
  781. exe_type = 'main.mac.arm64.bin'
  782. else:
  783. if platform.machine() in ["AMD64", "x86_64"]:
  784. exe_type = 'main.amd64.exe'
  785. else:
  786. exe_type = 'main.arm64.exe'
  787. return exe_type
  788. def set_init(conn):
  789. curs = conn.cursor()
  790. # 초기값 설정 함수
  791. curs.execute(db_change("select html from html_filter where kind = 'email'"))
  792. if not curs.fetchall():
  793. for i in ['naver.com', 'gmail.com', 'daum.net', 'kakao.com']:
  794. curs.execute(db_change("insert into html_filter (html, kind, plus, plus_t) values (?, 'email', '', '')"), [i])
  795. curs.execute(db_change("select html from html_filter where kind = 'extension'"))
  796. if not curs.fetchall():
  797. for i in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
  798. curs.execute(db_change("insert into html_filter (html, kind, plus, plus_t) values (?, 'extension', '', '')"), [i])
  799. curs.execute(db_change('select data from other where name = "smtp_server" or name = "smtp_port" or name = "smtp_security"'))
  800. if not curs.fetchall():
  801. for i in [['smtp_server', 'smtp.gmail.com'], ['smtp_port', '587'], ['smtp_security', 'starttls']]:
  802. curs.execute(db_change("insert into other (name, data, coverage) values (?, ?, '')"), [i[0], i[1]])
  803. curs.execute(db_change('insert into html_filter (html, kind, plus, plus_t) values (?, ?, ?, ?)'), [r'(?:[^A-Za-zㄱ-ㅣ가-힣0-9])', 'name', '', ''])
  804. # Func-simple
  805. ## Func-simple-without_DB
  806. def get_default_admin_group():
  807. return ['owner', 'user', 'ip', 'ban']
  808. def get_default_robots_txt(conn):
  809. data = '' + \
  810. 'User-agent: *\n' + \
  811. 'Disallow: /\n' + \
  812. 'Allow: /$\n' + \
  813. 'Allow: /w/\n' + \
  814. 'Allow: /bbs/w/\n' + \
  815. 'Allow: /sitemap.xml$\n' + \
  816. 'Allow: /sitemap_*.xml$' + \
  817. ''
  818. if os.path.exists('sitemap.xml'):
  819. data += '' + \
  820. '\n' + \
  821. 'Sitemap: ' + load_domain(conn, 'full') + '/sitemap.xml' + \
  822. ''
  823. return data
  824. def load_random_key(long = 128):
  825. return ''.join(random.choice("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(long))
  826. async def http_warning():
  827. return '''
  828. <div id="opennamu_http_warning_text"></div>
  829. <span style="display: none;" id="opennamu_http_warning_text_lang">''' + await get_lang('http_warning') + '''</span>
  830. '''
  831. async def get_next_page_bottom(link, num, page, end = 50):
  832. list_data = ''
  833. if num == 1:
  834. if len(page) == end:
  835. list_data += '' + \
  836. '<hr class="main_hr">' + \
  837. '<a href="' + link.format(str(num + 1)) + '">(' + await get_lang('next') + ')</a>' + \
  838. ''
  839. elif len(page) != end:
  840. list_data += '' + \
  841. '<hr class="main_hr">' + \
  842. '<a href="' + link.format(str(num - 1)) + '">(' + await get_lang('previous') + ')</a>' + \
  843. ''
  844. else:
  845. list_data += '' + \
  846. '<hr class="main_hr">' + \
  847. '<a href="' + link.format(str(num - 1)) + '">(' + await get_lang('previous') + ')</a> ' + \
  848. '<a href="' + link.format(str(num + 1)) + '">(' + await get_lang('next') + ')</a>' + \
  849. ''
  850. return list_data
  851. def leng_check(A, B):
  852. # B -> new
  853. # A -> old
  854. return '0' if A == B else (('-' + str(A - B)) if A > B else ('+' + str(B - A)))
  855. def number_check(data, f = 0):
  856. try:
  857. float(data) if f == 1 else int(data)
  858. return data
  859. except:
  860. return '1'
  861. def redirect(conn, data = '/'):
  862. return flask.redirect(load_domain(conn, 'full') + data)
  863. # Golang 의존
  864. async def get_acl_list(type_data = 'normal'):
  865. if type_data == 'user':
  866. type_data = 'user_document'
  867. other_set = {}
  868. other_set['type'] = type_data
  869. data = await python_to_golang('api_list_acl', other_set)
  870. return data["data"]
  871. ## Func-simple-with_DB
  872. async def get_user_title_list(conn, ip = ''):
  873. curs = conn.cursor()
  874. ip = ip_check() if ip == '' else ip
  875. # default
  876. user_title = {
  877. '' : await get_lang('default'),
  878. '🌳' : '🌳 newbie',
  879. }
  880. curs.execute(db_change('select name from user_set where id = ? and name = ?'), [ip, 'get_🥚'])
  881. if curs.fetchall():
  882. user_title['🥚'] = '🥚 easter_egg'
  883. curs.execute(db_change('select data from user_set where name = ? and id = ?'), ['challenge_first_contribute', ip])
  884. if curs.fetchall():
  885. user_title['🔰'] = '🔰 first_contribute'
  886. curs.execute(db_change('select data from user_set where name = ? and id = ?'), ['challenge_tenth_contribute', ip])
  887. if curs.fetchall():
  888. user_title['📝'] = '📝 tenth_contribute'
  889. curs.execute(db_change('select data from user_set where name = ? and id = ?'), ['challenge_hundredth_contribute', ip])
  890. if curs.fetchall():
  891. user_title['🖊️'] = '🖊️ hundredth_contribute'
  892. curs.execute(db_change('select data from user_set where name = ? and id = ?'), ['challenge_thousandth_contribute', ip])
  893. if curs.fetchall():
  894. user_title['🏅'] = '🏅 thousandth_contribute'
  895. curs.execute(db_change('select data from user_set where name = ? and id = ?'), ['challenge_first_discussion', ip])
  896. if curs.fetchall():
  897. user_title['💬'] = '💬 first_discussion'
  898. curs.execute(db_change('select data from user_set where name = ? and id = ?'), ['challenge_tenth_discussion', ip])
  899. if curs.fetchall():
  900. user_title['💡'] = '💡 tenth_discussion'
  901. curs.execute(db_change('select data from user_set where name = ? and id = ?'), ['challenge_hundredth_discussion', ip])
  902. if curs.fetchall():
  903. user_title['📢'] = '📢 hundredth_discussion'
  904. curs.execute(db_change('select data from user_set where name = ? and id = ?'), ['challenge_thousandth_discussion', ip])
  905. if curs.fetchall():
  906. user_title['📜'] = '📜 thousandth_discussion'
  907. curs.execute(db_change('select data from user_set where name = ? and id = ?'), ['challenge_admin', ip])
  908. if curs.fetchall():
  909. user_title['☑️'] = '☑️ before_admin'
  910. if await acl_check(tool = 'all_admin_auth') != 1:
  911. user_title['✅'] = '✅ admin'
  912. return user_title
  913. def load_image_url(conn):
  914. curs = conn.cursor()
  915. curs.execute(db_change('select data from other where name = "image_where"'))
  916. image_where = curs.fetchall()
  917. image_where = image_where[0][0] if image_where else os.path.join('data', 'images')
  918. return image_where
  919. def load_domain(conn, data_type = 'normal'):
  920. curs = conn.cursor()
  921. domain = ''
  922. try:
  923. sys_host = flask.request.host
  924. except:
  925. sys_host = ''
  926. if data_type == 'full':
  927. curs.execute(db_change("select data from other where name = 'http_select'"))
  928. db_data = curs.fetchall()
  929. domain += db_data[0][0] if db_data and db_data[0][0] != '' else 'http'
  930. domain += '://'
  931. curs.execute(db_change("select data from other where name = 'domain'"))
  932. db_data = curs.fetchall()
  933. domain += db_data[0][0] if db_data and db_data[0][0] != '' else sys_host
  934. else:
  935. curs.execute(db_change("select data from other where name = 'domain'"))
  936. db_data = curs.fetchall()
  937. domain += db_data[0][0] if db_data and db_data[0][0] != '' else sys_host
  938. return domain
  939. def get_tool_js_safe(data):
  940. data = data.replace('\n', '\\\\n')
  941. data = data.replace('\\', '\\\\')
  942. data = data.replace("'", "\\'")
  943. data = data.replace('"', '\\"')
  944. return data
  945. async def edit_button(conn):
  946. curs = conn.cursor()
  947. insert_list = []
  948. curs.execute(db_change("select html, plus from html_filter where kind = 'edit_top'"))
  949. db_data = curs.fetchall()
  950. for get_data in db_data:
  951. insert_list += [[get_data[1], get_data[0]]]
  952. data = ''
  953. for insert_data in insert_list:
  954. data += '<a href="javascript:do_insert_data(\'' + get_tool_js_safe(insert_data[0]) + '\');">(' + html.escape(insert_data[1]) + ')</a> '
  955. data += (' ' if data != '' else '') + '<a href="/filter/edit_top">(' + await get_lang('add') + ')</a>'
  956. data += '<hr class="main_hr">'
  957. return data
  958. async def ip_warning(conn):
  959. curs = conn.cursor()
  960. if ip_or_user() != 0:
  961. curs.execute(db_change('select data from other where name = "no_login_warning"'))
  962. data = curs.fetchall()
  963. if data and data[0][0] != '':
  964. text_data = '' + \
  965. '<span>' + data[0][0] + '</span>' + \
  966. '<hr class="main_hr">' + \
  967. ''
  968. else:
  969. text_data = '' + \
  970. '<span>' + await get_lang('no_login_warning') + '</span>' + \
  971. '<hr class="main_hr">' + \
  972. ''
  973. else:
  974. text_data = ''
  975. return text_data
  976. # Func-login
  977. def pw_encode(conn, data, db_data_encode = ''):
  978. curs = conn.cursor()
  979. if db_data_encode == '':
  980. curs.execute(db_change('select data from other where name = "encode"'))
  981. db_data = curs.fetchall()
  982. db_data_encode = db_data[0][0] if db_data else 'sha3'
  983. if db_data_encode == 'sha256':
  984. return hashlib.sha256(bytes(data, 'utf-8')).hexdigest()
  985. elif db_data_encode == 'sha3':
  986. return hashlib.sha3_256(bytes(data, 'utf-8')).hexdigest()
  987. elif db_data_encode == 'sha3-512':
  988. return hashlib.sha3_512(bytes(data, 'utf-8')).hexdigest()
  989. else:
  990. curs.execute(db_change('select data from other where name = "salt_key"'))
  991. db_data = curs.fetchall()
  992. db_data_salt = db_data[0][0] if db_data else ''
  993. if db_data_encode == 'sha3-salt':
  994. return hashlib.sha3_256(bytes(data + db_data_salt, 'utf-8')).hexdigest()
  995. else:
  996. return hashlib.sha3_512(bytes(data + db_data_salt, 'utf-8')).hexdigest()
  997. def pw_check(conn, data, data2, type_d = 'no', id_d = ''):
  998. curs = conn.cursor()
  999. curs.execute(db_change('select data from other where name = "encode"'))
  1000. db_data = curs.fetchall()
  1001. load_set_data = db_data[0][0] if db_data and db_data[0][0] != '' else 'sha3'
  1002. set_data = load_set_data
  1003. if type_d != 'no':
  1004. set_data = 'sha3' if type_d == '' else type_d
  1005. re_data = 1 if pw_encode(conn, data, set_data) == data2 else 0
  1006. if load_set_data != set_data and re_data == 1 and id_d != '':
  1007. curs.execute(db_change("update user_set set data = ? where id = ? and name = 'pw'"), [pw_encode(conn, data), id_d])
  1008. curs.execute(db_change("update user_set set data = ? where id = ? and name = 'encode'"), [load_set_data, id_d])
  1009. return re_data
  1010. # Func-skin
  1011. async def get_lang(data, safe = 0):
  1012. if data in global_lang_data:
  1013. if safe == 1:
  1014. return html.unescape(global_lang_data[data])
  1015. else:
  1016. return global_lang_data[data]
  1017. else:
  1018. lang = json_loads(open(os.path.join('lang', 'en-US.json'), encoding = 'utf-8').read())
  1019. other_set = {}
  1020. other_set["data"] = ' '.join([title for title in lang if title[0] != '_'])
  1021. other_set["legacy"] = ""
  1022. other_set["safe"] = ""
  1023. res = await python_to_golang('api_func_language', other_set)
  1024. if res['response'] == 'ok':
  1025. for load_data in res['data']:
  1026. global_lang_data[load_data] = res['data'][load_data]
  1027. if data in global_lang_data:
  1028. if safe == 1:
  1029. return html.unescape(global_lang_data[data])
  1030. else:
  1031. return global_lang_data[data]
  1032. else:
  1033. return data + ' (M)'
  1034. # 하위 호환용
  1035. def load_lang(data, safe = 0):
  1036. try:
  1037. loop = asyncio.get_running_loop()
  1038. if loop.is_running():
  1039. nest_asyncio.apply()
  1040. return loop.run_until_complete(get_lang(data, safe))
  1041. except RuntimeError:
  1042. return asyncio.run(get_lang(data, safe))
  1043. async def skin_check(set_n = 0):
  1044. other_set = {}
  1045. other_set["set_n"] = str(set_n)
  1046. res = await python_to_golang('api_func_skin_name', other_set)
  1047. raw = res["data"]
  1048. norm = os.path.normpath(raw)
  1049. parts = norm.split(os.sep)
  1050. if "views" in parts:
  1051. idx = parts.index("views")
  1052. rel_parts = parts[idx + 1:]
  1053. else:
  1054. rel_parts = parts
  1055. data = "/".join(rel_parts)
  1056. return data
  1057. def cache_v():
  1058. return '.cache_v289'
  1059. def cut_100(data):
  1060. return ''
  1061. async def wiki_set():
  1062. other_set = {}
  1063. data = await python_to_golang('api_func_wiki_set', other_set)
  1064. return data["data"]
  1065. async def wiki_custom():
  1066. other_set = {}
  1067. data = await python_to_golang('api_func_wiki_custom', other_set)
  1068. return data["data"]
  1069. async def load_skin(data = '', set_n = 0, default = 0):
  1070. # without_DB
  1071. # data -> 가장 앞에 있을 스킨 이름
  1072. # set_n == 0 -> 스트링으로 반환
  1073. # set_n == 1 -> 리스트로 반환
  1074. # default == 0 -> 디폴트 미포함
  1075. # default == 1 -> 디폴트 포함
  1076. skin_return_data = []
  1077. skin_return_data_str = ''
  1078. skin_list_get = os.listdir('views')
  1079. if default == 1:
  1080. skin_list_get = ['default'] + skin_list_get
  1081. for skin_data in skin_list_get:
  1082. if skin_data != 'default':
  1083. see_data = skin_data
  1084. else:
  1085. see_data = await get_lang('default')
  1086. if skin_data != 'main_css':
  1087. if set_n == 0:
  1088. if skin_data == data:
  1089. skin_return_data_str = '' + \
  1090. '<option value="' + skin_data + '">' + \
  1091. see_data + \
  1092. '</option>' + \
  1093. '' + skin_return_data_str
  1094. else:
  1095. skin_return_data_str += '' + \
  1096. '<option value="' + skin_data + '">' + \
  1097. see_data + \
  1098. '</option>' + \
  1099. ''
  1100. else:
  1101. if skin_data == data:
  1102. skin_return_data = [skin_data] + skin_return_data
  1103. else:
  1104. skin_return_data += [skin_data]
  1105. if set_n == 0:
  1106. return skin_return_data_str
  1107. else:
  1108. return skin_return_data
  1109. # Func-markup
  1110. async def render_set(conn, doc_name = '', doc_data = '', data_type = 'view', markup = '', parameter = {}):
  1111. curs = conn.cursor()
  1112. # data_type in ['view', 'from', 'thread', 'api_view', 'api_thread', 'api_include', 'backlink']
  1113. # data_type을 list 형식으로 개편 필요할 듯
  1114. return_type = True
  1115. if data_type in ['api_from', 'api_view', 'api_thread', 'api_include']:
  1116. return_type = False
  1117. if await acl_check(doc_name, 'render') == 1:
  1118. if not return_type:
  1119. return ["", ""]
  1120. else:
  1121. return ''
  1122. if data_type == '':
  1123. data_type = 'view'
  1124. elif data_type == 'api_view':
  1125. data_type = 'view'
  1126. elif data_type == 'api_from':
  1127. data_type = 'from'
  1128. elif data_type == 'api_thread':
  1129. data_type = 'thread'
  1130. elif data_type == 'api_include':
  1131. data_type = 'include'
  1132. doc_data = '' if doc_data == None else doc_data
  1133. ip = ip_check()
  1134. render_lang_data = {
  1135. 'toc' : await get_lang('toc'),
  1136. 'category' : await get_lang('category')
  1137. }
  1138. curs.execute(db_change('select data from other where name = "category_text"'))
  1139. db_data = curs.fetchall()
  1140. if db_data and db_data[0][0] != '':
  1141. render_lang_data['category'] = db_data[0][0]
  1142. get_class_render = await class_do_render(
  1143. conn,
  1144. render_lang_data,
  1145. markup,
  1146. parameter,
  1147. render_set
  1148. ).do_render(
  1149. doc_name,
  1150. doc_data,
  1151. data_type
  1152. )
  1153. if data_type == 'backlink':
  1154. return ''
  1155. get_class_render[0] = '<div class="opennamu_render_complete">' + get_class_render[0] + '</div>'
  1156. font_size_set_data = get_main_skin_set(conn, flask.session, 'main_css_font_size', ip)
  1157. if font_size_set_data != 'default':
  1158. font_size_set_data = number_check(font_size_set_data)
  1159. get_class_render[0] = '' + \
  1160. '''<style>
  1161. .opennamu_render_complete {
  1162. font-size: ''' + font_size_set_data + '''px !important;
  1163. }
  1164. </style>''' + \
  1165. '' + get_class_render[0]
  1166. curs.execute(db_change("select data from other where name = 'namumark_compatible'"))
  1167. db_data = curs.fetchall()
  1168. if db_data and db_data[0][0] != '':
  1169. get_class_render[0] = '' + \
  1170. '''<style>
  1171. .opennamu_render_complete {
  1172. font-size: 15px !important;
  1173. line-height: 1.5;
  1174. }
  1175. .opennamu_render_complete td {
  1176. padding: 5px 10px !important;
  1177. word-break: break-all;
  1178. }
  1179. .opennamu_render_complete summary {
  1180. list-style: none !important;
  1181. font-weight: bold !important;
  1182. }
  1183. .opennamu_render_complete .opennamu_folding {
  1184. margin-bottom: 5px;
  1185. }
  1186. .opennamu_render_complete .opennamu_footnote {
  1187. padding-bottom: 30px;
  1188. }
  1189. .opennamu_render_complete iframe {
  1190. display: block;
  1191. }
  1192. </style>''' + \
  1193. '' + get_class_render[0]
  1194. table_set_data = get_main_skin_set(conn, flask.session, 'main_css_table_scroll', ip)
  1195. if table_set_data == 'on':
  1196. get_class_render[0] = '<style>.table_safe { overflow-x: scroll; white-space: nowrap; }</style>' + get_class_render[0]
  1197. joke_set_data = get_main_skin_set(conn, flask.session, 'main_css_view_joke', ip)
  1198. if joke_set_data == 'off':
  1199. get_class_render[0] = '<style>.opennamu_joke { display: none; }</style>' + get_class_render[0]
  1200. math_set_data = get_main_skin_set(conn, flask.session, 'main_css_math_scroll', ip)
  1201. if math_set_data == 'on':
  1202. get_class_render[0] = '<style>.katex .base { overflow-x: scroll; }</style>' + get_class_render[0]
  1203. transparent_set_data = get_main_skin_set(conn, flask.session, 'main_css_table_transparent', ip)
  1204. if transparent_set_data == 'on':
  1205. get_class_render[0] = '' + \
  1206. '''<style>
  1207. .table_safe td {
  1208. background: transparent !important;
  1209. color: inherit !important;
  1210. }
  1211. </style>''' + \
  1212. '' + get_class_render[0]
  1213. if not return_type:
  1214. return [get_class_render[0], get_class_render[1]]
  1215. else:
  1216. return get_class_render[0] + '<script>window.addEventListener("DOMContentLoaded", function() {' + get_class_render[1] + '});</script>'
  1217. async def render_simple_set(data):
  1218. # without_DB
  1219. toc_data = ''
  1220. toc_regex = r'<h([1-6])>([^<>]+)<\/h[1-6]>'
  1221. toc_search_data = re.findall(toc_regex, data)
  1222. heading_stack = [0, 0, 0, 0, 0, 0]
  1223. if toc_search_data:
  1224. toc_data += '''
  1225. <div class="opennamu_TOC" id="toc">
  1226. <span class="opennamu_TOC_title">''' + await get_lang('toc') + '''</span>
  1227. <br>
  1228. '''
  1229. for toc_search_in in toc_search_data:
  1230. heading_level = int(toc_search_in[0])
  1231. heading_level_str = str(heading_level)
  1232. heading_stack[heading_level - 1] += 1
  1233. for for_a in range(heading_level, 6):
  1234. heading_stack[for_a] = 0
  1235. heading_stack_str = ''.join([str(for_a) + '.' if for_a != 0 else '' for for_a in heading_stack])
  1236. heading_stack_str = re.sub(r'\.$', '', heading_stack_str)
  1237. toc_data += '''
  1238. <br>
  1239. <span class="opennamu_TOC_list">
  1240. ''' + ('<span style="margin-left: 10px;"></span>' * (heading_stack_str.count('.'))) + '''
  1241. <a href="#s-''' + heading_stack_str + '''">''' + heading_stack_str + '''.</a>
  1242. ''' + toc_search_in[1] + '''
  1243. </span>
  1244. '''
  1245. data = re.sub(toc_regex, '<h' + toc_search_in[0] + ' id="s-' + heading_stack_str + '"><a href="#toc">' + heading_stack_str + '.</a> ' + toc_search_in[1] + '</h' + toc_search_in[0] + '>', data, 1)
  1246. if toc_data != '':
  1247. toc_data += '</div>'
  1248. footnote_data = ''
  1249. footnote_regex = r'<sup>((?:(?!<sup>|<\/sup>).)+)<\/sup>'
  1250. footnote_search_data = re.findall(footnote_regex, data)
  1251. footnote_count = 1
  1252. if footnote_search_data:
  1253. footnote_data += '<div class="opennamu_footnote">'
  1254. for footnote_search in footnote_search_data:
  1255. footnote_count_str = str(footnote_count)
  1256. if footnote_count != 1:
  1257. footnote_data += '<br>'
  1258. footnote_data += '<a id="fn-' + footnote_count_str + '" href="#rfn-' + footnote_count_str + '">(' + footnote_count_str + ')</a> ' + footnote_search
  1259. data = re.sub(footnote_regex, '<sup id="rfn-' + footnote_count_str + '"><a href="#fn-' + footnote_count_str + '">(' + footnote_count_str + ')</a></sup>', data, 1)
  1260. footnote_count += 1
  1261. if footnote_data != '':
  1262. footnote_data += '</div>'
  1263. data = toc_data + data + footnote_data
  1264. return data
  1265. # Func-request
  1266. async def send_email(conn, who, title, data):
  1267. curs = conn.cursor()
  1268. curs.execute(db_change('' + \
  1269. 'select name, data from other ' + \
  1270. 'where name = "smtp_email" or name = "smtp_pass" or name = "smtp_server" or name = "smtp_port" or name = "smtp_security"' + \
  1271. ''))
  1272. rep_data = curs.fetchall()
  1273. smtp_email = ''
  1274. smtp_pass = ''
  1275. smtp_server = ''
  1276. smtp_security = ''
  1277. smtp_port = ''
  1278. smtp = ''
  1279. for i in rep_data:
  1280. if i[0] == 'smtp_email':
  1281. smtp_email = i[1]
  1282. elif i[0] == 'smtp_pass':
  1283. smtp_pass = i[1]
  1284. elif i[0] == 'smtp_server':
  1285. smtp_server = i[1]
  1286. elif i[0] == 'smtp_security':
  1287. smtp_security = i[1]
  1288. elif i[0] == 'smtp_port':
  1289. smtp_port = i[1]
  1290. smtp_port = int(number_check(smtp_port))
  1291. if smtp_security == 'plain':
  1292. smtp = smtplib.SMTP(smtp_server, smtp_port)
  1293. elif smtp_security == 'starttls':
  1294. smtp = smtplib.SMTP(smtp_server, smtp_port)
  1295. smtp.starttls()
  1296. else:
  1297. # if smtp_security == 'tls':
  1298. smtp = smtplib.SMTP_SSL(smtp_server, smtp_port)
  1299. domain = load_domain(conn)
  1300. wiki_name = (await wiki_set())[0]
  1301. msg = email.mime.text.MIMEText(data)
  1302. msg['Subject'] = title
  1303. msg['From'] = wiki_name + ' <noreply@' + domain + '>'
  1304. msg['To'] = who
  1305. try:
  1306. smtp.login(smtp_email, smtp_pass)
  1307. smtp.sendmail('openNAMU@' + domain, who, msg.as_string())
  1308. smtp.quit()
  1309. return 1
  1310. except Exception as e:
  1311. print('Error : email send error')
  1312. print(e)
  1313. return 0
  1314. async def captcha_get(conn):
  1315. curs = conn.cursor()
  1316. data = ''
  1317. if await acl_check('', 'recaptcha_five_pass') == 0 and 'recapcha_pass' in flask.session and flask.session['recapcha_pass'] > 0:
  1318. pass
  1319. elif await acl_check('', 'recaptcha') == 1:
  1320. curs.execute(db_change('select data from other where name = "recaptcha"'))
  1321. recaptcha = curs.fetchall()
  1322. curs.execute(db_change('select data from other where name = "sec_re"'))
  1323. sec_re = curs.fetchall()
  1324. curs.execute(db_change('select data from other where name = "recaptcha_ver"'))
  1325. rec_ver = curs.fetchall()
  1326. if recaptcha and recaptcha[0][0] != '' and sec_re and sec_re[0][0] != '':
  1327. if not rec_ver or rec_ver[0][0] == '':
  1328. data += '' + \
  1329. '<script defer src="https://www.google.com/recaptcha/api.js"></script>' + \
  1330. '<div class="g-recaptcha" data-sitekey="' + recaptcha[0][0] + '"></div>' + \
  1331. '<hr class="main_hr">' + \
  1332. ''
  1333. elif rec_ver[0][0] == 'v3':
  1334. data += '' + \
  1335. '<script defer src="https://www.google.com/recaptcha/api.js?render=' + recaptcha[0][0] + '"></script>' + \
  1336. '<input class="__ON_INPUT__" type="hidden" id="g-recaptcha" name="g-recaptcha">' + \
  1337. '<script type="text/javascript">' + \
  1338. 'document.addEventListener(\'DOMContentLoaded\', function () {' + \
  1339. 'grecaptcha.ready(function() {' + \
  1340. 'grecaptcha.execute(\'' + recaptcha[0][0] + '\', {action: \'homepage\'}).then(function(token) {' + \
  1341. 'document.getElementById(\'g-recaptcha\').value = token;' + \
  1342. '});' + \
  1343. '});' + \
  1344. '});' + \
  1345. '</script>' + \
  1346. ''
  1347. elif rec_ver[0][0] == 'cf':
  1348. data += '' + \
  1349. '<script defer src="https://challenges.cloudflare.com/turnstile/v0/api.js?compat=recaptcha"></script>' + \
  1350. '<div class="g-recaptcha" data-sitekey="' + recaptcha[0][0] + '"></div>' + \
  1351. '<hr class="main_hr">' + \
  1352. ''
  1353. else:
  1354. # rec_ver[0][0] == 'h'
  1355. data += '''
  1356. <script defer src="https://js.hcaptcha.com/1/api.js"></script>
  1357. <div class="h-captcha" data-sitekey="''' + recaptcha[0][0] + '''"></div>
  1358. <hr class="main_hr">
  1359. '''
  1360. return data
  1361. async def captcha_post(conn, re_data):
  1362. curs = conn.cursor()
  1363. if await acl_check('', 'recaptcha_five_pass') == 0 and 'recapcha_pass' in flask.session and flask.session['recapcha_pass'] > 0:
  1364. pass
  1365. elif await acl_check('', 'recaptcha') == 1:
  1366. curs.execute(db_change('select data from other where name = "sec_re"'))
  1367. sec_re = curs.fetchall()
  1368. curs.execute(db_change('select data from other where name = "recaptcha_ver"'))
  1369. rec_ver = curs.fetchall()
  1370. if await captcha_get(conn) != '':
  1371. url = ''
  1372. if not rec_ver or rec_ver[0][0] in ('', 'v3'):
  1373. url = 'https://www.google.com/recaptcha/api/siteverify'
  1374. elif rec_ver[0][0] == 'cf':
  1375. url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
  1376. else:
  1377. # rec_ver[0][0] == 'h'
  1378. url = 'https://hcaptcha.com/siteverify'
  1379. async with aiohttp.ClientSession() as session:
  1380. async with session.post(url, data = {
  1381. "secret": sec_re[0][0],
  1382. "response": re_data
  1383. }) as res:
  1384. if res.status == 200:
  1385. json_data = await res.json()
  1386. if json_data['success'] != True:
  1387. return 1
  1388. if 'recapcha_pass' in flask.session:
  1389. if flask.session['recapcha_pass'] > 0:
  1390. flask.session['recapcha_pass'] -= 1
  1391. else:
  1392. flask.session['recapcha_pass'] = 5
  1393. else:
  1394. flask.session['recapcha_pass'] = 5
  1395. return 0
  1396. # Func-user
  1397. def do_user_name_check(conn, user_name):
  1398. curs = conn.cursor()
  1399. # XSS 필터
  1400. if html.escape(user_name) != user_name:
  1401. return 1
  1402. # IP와 혼동 방지
  1403. if ip_or_user(user_name) == 1:
  1404. return 1
  1405. # 슬래시 불가능
  1406. if user_name.find('/') != -1:
  1407. return 1
  1408. # ID 필터
  1409. curs.execute(db_change('select html from html_filter where kind = "name"'))
  1410. set_d = curs.fetchall()
  1411. for i in set_d:
  1412. check_r = re.compile(i[0], re.I)
  1413. if check_r.search(user_name):
  1414. return 1
  1415. # ID 길이 제한 (128글자)
  1416. if len(user_name) > 128:
  1417. return 1
  1418. # 중복 확인
  1419. curs.execute(db_change("select id from user_set where name = 'user_name' and data = ?"), [user_name])
  1420. if curs.fetchall():
  1421. return 1
  1422. curs.execute(db_change("select id from user_set where id = ?"), [user_name])
  1423. if curs.fetchall():
  1424. return 1
  1425. return 0
  1426. async def level_check(ip = ''):
  1427. ip = ip_check() if ip == '' else ip
  1428. other_set = {}
  1429. other_set['ip'] = ip
  1430. data = await python_to_golang('api_func_level', other_set)
  1431. return data["data"]
  1432. async def acl_check(name = '', tool = '', topic_num = '', ip = '', memo = ''):
  1433. ip = ip_check() if ip == '' else ip
  1434. other_set = {}
  1435. other_set['ip'] = ip
  1436. other_set['name'] = name
  1437. other_set['topic_number'] = topic_num
  1438. other_set['tool'] = tool
  1439. data = await python_to_golang('api_func_acl', other_set)
  1440. result = 0 if data["data"] else 1
  1441. if memo != '' and result == 0:
  1442. other_set = {}
  1443. other_set['ip'] = ip
  1444. other_set['what'] = memo
  1445. await python_to_golang('api_func_auth_post', other_set)
  1446. return result
  1447. async def ban_check(ip = None, tool = ''):
  1448. ip = ip_check() if not ip else ip
  1449. tool = '' if not tool else tool
  1450. other_set = {}
  1451. other_set['ip'] = ip
  1452. other_set['type'] = tool
  1453. data = await python_to_golang('api_func_ban', other_set)
  1454. data["ban"] = 1 if data["ban"] == "true" else 0
  1455. return [data["ban"], data["ban_type"]]
  1456. async def ip_pas(raw_ip):
  1457. other_set = {}
  1458. return_data = 0
  1459. if type(raw_ip) != type([]):
  1460. get_ip = [raw_ip]
  1461. return_data = 1
  1462. else:
  1463. get_ip = raw_ip
  1464. for for_a in range(1, len(get_ip) + 1):
  1465. other_set["data_" + str(for_a)] = get_ip[for_a - 1]
  1466. data = await python_to_golang('api_func_ip_post', other_set)
  1467. return data["data"][raw_ip] if return_data == 1 else data["data"]
  1468. # Func-edit
  1469. def get_edit_text_bottom(conn, tool = '') :
  1470. curs = conn.cursor()
  1471. b_text = ''
  1472. curs.execute(db_change('select data from other where name = "edit_bottom_text"'))
  1473. db_data = curs.fetchall()
  1474. if db_data and db_data[0][0] != '':
  1475. b_text = db_data[0][0] + '<hr class="main_hr">'
  1476. if tool != '':
  1477. if tool == 'edit':
  1478. curs.execute(db_change('select data from other where name = "edit_only_bottom_text"'))
  1479. elif tool == 'move':
  1480. curs.execute(db_change('select data from other where name = "move_bottom_text"'))
  1481. elif tool == 'delete':
  1482. curs.execute(db_change('select data from other where name = "delete_bottom_text"'))
  1483. else:
  1484. curs.execute(db_change('select data from other where name = "revert_bottom_text"'))
  1485. db_data = curs.fetchall()
  1486. if db_data and db_data[0][0] != '':
  1487. b_text = db_data[0][0] + '<hr class="main_hr">'
  1488. return b_text
  1489. def get_edit_text_bottom_check_box(conn):
  1490. curs = conn.cursor()
  1491. cccb_text = ''
  1492. curs.execute(db_change('select data from other where name = "copyright_checkbox_text"'))
  1493. sql_d = curs.fetchall()
  1494. if sql_d and sql_d[0][0] != '':
  1495. checked = ''
  1496. if flask.session and 'bottom_check_box_pass' in flask.session:
  1497. checked = 'checked'
  1498. cccb_text = '' + \
  1499. '<label class="__ON_CHECKLABEL__"><input class="__ON_CHECKBOX__" type="checkbox" name="copyright_agreement" value="yes" ' + checked + '> ' + sql_d[0][0] + '</label>' + \
  1500. '<hr class="main_hr">' + \
  1501. ''
  1502. return cccb_text
  1503. def do_edit_text_bottom_check_box_check(conn, data):
  1504. curs = conn.cursor()
  1505. curs.execute(db_change('select data from other where name = "copyright_checkbox_text"'))
  1506. db_data = curs.fetchall()
  1507. if db_data and db_data[0][0] != '':
  1508. if 'bottom_check_box_pass' in flask.session and flask.session['bottom_check_box_pass'] > 0:
  1509. pass
  1510. elif data != 'yes':
  1511. return 1
  1512. if not 'bottom_check_box_pass' in flask.session:
  1513. flask.session['bottom_check_box_pass'] = 1
  1514. return 0
  1515. async def do_edit_send_check(conn, data):
  1516. curs = conn.cursor()
  1517. curs.execute(db_change('select data from other where name = "edit_bottom_compulsion"'))
  1518. db_data = curs.fetchall()
  1519. if db_data and db_data[0][0] != '':
  1520. if await acl_check('', 'edit_bottom_compulsion') == 1:
  1521. if data == '':
  1522. return 1
  1523. return 0
  1524. async def do_edit_slow_check(conn, do_type = 'edit'):
  1525. curs = conn.cursor()
  1526. if do_type == 'edit':
  1527. curs.execute(db_change("select data from other where name = 'slow_edit'"))
  1528. else:
  1529. # do_type == 'thread'
  1530. curs.execute(db_change("select data from other where name = 'slow_thread'"))
  1531. slow_edit = curs.fetchall()
  1532. if slow_edit and slow_edit[0][0] != '':
  1533. if await acl_check('', 'slow_edit') == 1:
  1534. slow_edit = int(number_check(slow_edit[0][0]))
  1535. if do_type == 'edit':
  1536. curs.execute(db_change("select date from history where ip = ? order by date desc limit 1"), [ip_check()])
  1537. else:
  1538. curs.execute(db_change("select date from topic where ip = ? order by date desc limit 1"), [ip_check()])
  1539. last_edit_data = curs.fetchall()
  1540. if last_edit_data:
  1541. last_edit_data = int(re.sub(' |:|-', '', last_edit_data[0][0]))
  1542. now_edit_data = int((
  1543. datetime.datetime.now() - datetime.timedelta(seconds = slow_edit)
  1544. ).strftime("%Y%m%d%H%M%S"))
  1545. if last_edit_data > now_edit_data:
  1546. return 1
  1547. return 0
  1548. async def do_edit_filter(conn, data):
  1549. curs = conn.cursor()
  1550. ip = ip_check()
  1551. if await acl_check(tool = 'edit_filter_pass') == 1:
  1552. curs.execute(db_change("select plus, plus_t from html_filter where kind = 'regex_filter' and plus != ''"))
  1553. for data_list in curs.fetchall():
  1554. match = re.compile(data_list[0], re.I)
  1555. if match.search(data):
  1556. end = '0' if data_list[1] == 'X' else data_list[1]
  1557. if end != '0':
  1558. end = int(number_check(end))
  1559. time = datetime.datetime.now()
  1560. plus = datetime.timedelta(seconds = end)
  1561. r_time = (time + plus).strftime("%Y-%m-%d %H:%M:%S")
  1562. else:
  1563. r_time = '0'
  1564. curs.execute(db_change('delete from user_set where name = "edit_filter" and id = ?'), [ip])
  1565. curs.execute(db_change('insert into user_set (name, id, data) values ("edit_filter", ?, ?)'), [ip, data])
  1566. ban_insert(conn,
  1567. ip,
  1568. r_time,
  1569. 'edit filter',
  1570. '',
  1571. 'tool:edit filter'
  1572. )
  1573. return 1
  1574. return 0
  1575. def do_title_length_check(conn, name, check_type = 'document'):
  1576. curs = conn.cursor()
  1577. if check_type == 'topic':
  1578. curs.execute(db_change('select data from other where name = "title_topic_max_length"'))
  1579. db_data = curs.fetchall()
  1580. if db_data and db_data[0][0] != '':
  1581. db_data = int(number_check(db_data[0][0]))
  1582. if len(name) > db_data:
  1583. return 1
  1584. else:
  1585. curs.execute(db_change('select data from other where name = "title_max_length"'))
  1586. db_data = curs.fetchall()
  1587. if db_data and db_data[0][0] != '':
  1588. db_data = int(number_check(db_data[0][0]))
  1589. if len(name) > db_data:
  1590. return 1
  1591. return 0
  1592. # Func-insert
  1593. def do_add_thread(conn, thread_code, thread_data, thread_top = '', thread_id = ''):
  1594. curs = conn.cursor()
  1595. if thread_id == '':
  1596. curs.execute(db_change("select id from topic where code = ? order by id + 0 desc limit 1"), [thread_code])
  1597. db_data = curs.fetchall()
  1598. if db_data:
  1599. thread_id = str(int(db_data[0][0]) + 1)
  1600. else:
  1601. thread_id = '1'
  1602. curs.execute(db_change("insert into topic (id, data, date, ip, block, top, code) values (?, ?, ?, ?, ?, '', ?)"), [
  1603. thread_id,
  1604. thread_data,
  1605. get_time(),
  1606. ip_check(),
  1607. thread_top,
  1608. thread_code
  1609. ])
  1610. def do_reload_recent_thread(conn, topic_num, date, name = None, sub = None):
  1611. curs = conn.cursor()
  1612. curs.execute(db_change("select code from rd where code = ?"), [topic_num])
  1613. if curs.fetchall():
  1614. curs.execute(db_change("update rd set date = ? where code = ?"), [date, topic_num])
  1615. else:
  1616. curs.execute(db_change("insert into rd (title, sub, code, date, band, stop, agree, acl) values (?, ?, ?, ?, '', '', '', '')"), [name, sub, topic_num, date])
  1617. async def add_alarm(to_user, from_user, context):
  1618. other_set = {}
  1619. other_set['to'] = to_user
  1620. other_set['from'] = from_user
  1621. other_set['data'] = context
  1622. await python_to_golang('api_func_alarm_post', other_set)
  1623. def add_user(conn, user_name, user_pw, user_email = '', user_encode = ''):
  1624. curs = conn.cursor()
  1625. if user_encode == '':
  1626. user_pw_hash = pw_encode(conn, user_pw)
  1627. curs.execute(db_change('select data from other where name = "encode"'))
  1628. data_encode = curs.fetchall()
  1629. data_encode = data_encode[0][0]
  1630. else:
  1631. user_pw_hash = user_pw
  1632. data_encode = user_encode
  1633. curs.execute(db_change("select id from user_set limit 1"))
  1634. if not curs.fetchall():
  1635. user_auth = 'owner'
  1636. else:
  1637. user_auth = 'user'
  1638. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'pw', ?)"), [user_name, user_pw_hash])
  1639. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'acl', ?)"), [user_name, user_auth])
  1640. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'date', ?)"), [user_name, get_time()])
  1641. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'encode', ?)"), [user_name, data_encode])
  1642. if user_email != '':
  1643. curs.execute(db_change("insert into user_set (name, id, data) values ('email', ?, ?)"), [user_name, user_email])
  1644. def ua_plus(conn, u_id, u_ip, u_agent, time):
  1645. curs = conn.cursor()
  1646. curs.execute(db_change("select data from other where name = 'ua_get'"))
  1647. rep_data = curs.fetchall()
  1648. if rep_data and rep_data[0][0] != '':
  1649. pass
  1650. else:
  1651. curs.execute(db_change("insert into ua_d (name, ip, ua, today, sub) values (?, ?, ?, ?, '')"), [
  1652. u_id,
  1653. u_ip,
  1654. u_agent,
  1655. time
  1656. ])
  1657. def ban_insert(conn, name, end, why, login, blocker, type_d = None, release = 0):
  1658. curs = conn.cursor()
  1659. now_time = get_time()
  1660. band = type_d if type_d else ''
  1661. curs.execute(db_change("update rb set ongoing = '' where block = ? and band = ? and ongoing = '1'"), [name, band])
  1662. if release == 1:
  1663. curs.execute(db_change("insert into rb (block, end, today, blocker, why, band, ongoing, login) values (?, ?, ?, ?, ?, ?, '', '')"), [
  1664. name,
  1665. 'release',
  1666. now_time,
  1667. blocker,
  1668. why,
  1669. band
  1670. ])
  1671. else:
  1672. login = login if login != '' else ''
  1673. r_time = end if end != '0' else ''
  1674. curs.execute(db_change("insert into rb (block, end, today, blocker, why, band, ongoing, login) values (?, ?, ?, ?, ?, ?, '1', ?)"), [
  1675. name,
  1676. r_time,
  1677. now_time,
  1678. blocker,
  1679. why,
  1680. band,
  1681. login
  1682. ])
  1683. def history_plus_rc_max(conn, mode):
  1684. curs = conn.cursor()
  1685. curs.execute(db_change("select count(*) from rc where type = ?"), [mode])
  1686. if curs.fetchall()[0][0] >= 200:
  1687. curs.execute(db_change("select id, title from rc where type = ? order by date asc limit 1"), [mode])
  1688. rc_data = curs.fetchall()
  1689. if rc_data:
  1690. curs.execute(db_change('delete from rc where id = ? and title = ? and type = ?'), [rc_data[0][0], rc_data[0][1], mode])
  1691. def history_plus(conn, title, data, date, ip, send, leng, t_check = '', mode = ''):
  1692. curs = conn.cursor()
  1693. curs.execute(db_change('select data from other where name = "history_recording_off"'))
  1694. db_data = curs.fetchall()
  1695. if db_data and db_data[0][0] != '':
  1696. return 0
  1697. if mode == 'add' or mode == 'setting':
  1698. curs.execute(db_change("select id from history where title = ? order by id + 0 asc limit 1"), [title])
  1699. id_data = curs.fetchall()
  1700. id_data = str(int(id_data[0][0]) - 1) if id_data else '0'
  1701. else:
  1702. curs.execute(db_change("select id from history where title = ? order by id + 0 desc limit 1"), [title])
  1703. id_data = curs.fetchall()
  1704. id_data = str(int(id_data[0][0]) + 1) if id_data else '1'
  1705. mode = 'r1' if id_data == '1' else mode
  1706. if re.search('^user:', title):
  1707. mode = 'user'
  1708. elif re.search('^file:', title):
  1709. mode = 'file'
  1710. elif re.search('^category:', title):
  1711. mode = 'category'
  1712. send = re.sub(r'<|>', '', send)
  1713. send = send[:512] if len(send) > 512 else send
  1714. send = send + ' (' + t_check + ')' if t_check != '' else send
  1715. if mode != 'add' and mode != 'setting' and mode != 'user':
  1716. history_plus_rc_max(conn, 'normal')
  1717. curs.execute(db_change("insert into rc (id, title, date, type) values (?, ?, ?, 'normal')"), [id_data, title, date])
  1718. if mode != 'add' and mode != 'setting':
  1719. history_plus_rc_max(conn, mode)
  1720. curs.execute(db_change("select count(*) from data"))
  1721. count_data = curs.fetchall()
  1722. count_data = count_data[0][0] if count_data else 0
  1723. curs.execute(db_change('delete from other where name = "count_all_title"'))
  1724. curs.execute(db_change('insert into other (name, data, coverage) values ("count_all_title", ?, "")'), [str(count_data)])
  1725. curs.execute(db_change("insert into rc (id, title, date, type) values (?, ?, ?, ?)"), [id_data, title, date, mode])
  1726. data_set_exist = ''
  1727. if mode == 'delete':
  1728. data_set_exist = 'not_exist'
  1729. curs.execute(db_change('delete from data_set where doc_name = ? and set_name = "edit_request_doing"'), [title])
  1730. curs.execute(db_change('delete from data_set where doc_name = ? and set_name = "last_edit"'), [title])
  1731. curs.execute(db_change("insert into data_set (doc_name, doc_rev, set_name, set_data) values (?, '', 'last_edit', ?)"), [title, date])
  1732. curs.execute(db_change('delete from data_set where doc_name = ? and set_name = "length"'), [title])
  1733. curs.execute(db_change("insert into data_set (doc_name, doc_rev, set_name, set_data) values (?, '', 'length', ?)"), [title, len(data)])
  1734. curs.execute(db_change("update data_set set doc_rev = ? where doc_name = ? and (doc_rev = '' or doc_rev = 'not_exist')"), [data_set_exist, title])
  1735. curs.execute(db_change("insert into history (id, title, data, date, ip, send, leng, hide, type) values (?, ?, ?, ?, ?, ?, ?, '', ?)"), [id_data, title, data, date, ip, send, leng, mode])
  1736. # Func-error
  1737. async def re_error(conn, data):
  1738. curs = conn.cursor()
  1739. if data == 0:
  1740. if (await ban_check())[0] == 1:
  1741. end = '<div id="opennamu_get_user_info">' + html.escape(ip_check()) + '</div>'
  1742. else:
  1743. end = '<ul><li>' + await get_lang('authority_error') + '</li></ul>'
  1744. return await render_template(
  1745. await get_lang('error'),
  1746. '<h2>' + await get_lang('error') + '</h2>' + end,
  1747. 0,
  1748. 0
  1749. ), 401
  1750. else:
  1751. title = await get_lang('error')
  1752. sub_title = title
  1753. return_code = 400
  1754. num = data
  1755. if num == 1:
  1756. data = await get_lang('no_login_error')
  1757. elif num == 2:
  1758. data = await get_lang('no_exist_user_error')
  1759. elif num == 3:
  1760. data = await get_lang('authority_error')
  1761. elif num == 4:
  1762. data = await get_lang('no_admin_block_error')
  1763. elif num == 5:
  1764. data = await get_lang('error_skin_set')
  1765. elif num == 8:
  1766. data = '' + \
  1767. await get_lang('long_id_error') + '<br>' + \
  1768. await get_lang('id_char_error') + ' <a href="/filter/name_filter">(' + await get_lang('id_filter_list') + ')</a><br>' + \
  1769. await get_lang('same_id_exist_error') + \
  1770. ''
  1771. elif num == 9:
  1772. data = await get_lang('file_exist_error')
  1773. elif num == 10:
  1774. data = await get_lang('password_error')
  1775. elif num == 11:
  1776. data = await get_lang('topic_long_error')
  1777. elif num == 12:
  1778. data = await get_lang('email_error')
  1779. elif num == 13:
  1780. data = await get_lang('recaptcha_error')
  1781. elif num == 14:
  1782. data = await get_lang('file_extension_error') + ' <a href="/filter/extension_filter">(' + await get_lang('extension_filter_list') + ')</a>'
  1783. elif num == 15:
  1784. data = await get_lang('edit_record_error')
  1785. elif num == 16:
  1786. data = await get_lang('same_file_error')
  1787. elif num == 17:
  1788. curs.execute(db_change('select data from other where name = "upload"'))
  1789. db_data = curs.fetchall()
  1790. file_max = number_check(db_data[0][0]) if db_data and db_data[0][0] != '' else '2'
  1791. data = await get_lang('file_capacity_error') + file_max
  1792. elif num == 18:
  1793. data = await get_lang('email_send_error')
  1794. elif num == 19:
  1795. data = await get_lang('move_error')
  1796. elif num == 20:
  1797. data = await get_lang('password_diffrent_error')
  1798. elif num == 21:
  1799. data = await get_lang('edit_filter_error')
  1800. elif num == 22:
  1801. data = await get_lang('file_name_error')
  1802. elif num == 23:
  1803. data = await get_lang('regex_error')
  1804. elif num == 24:
  1805. curs.execute(db_change("select data from other where name = 'slow_edit'"))
  1806. db_data = curs.fetchall()
  1807. db_data = '' if not db_data else db_data[0][0]
  1808. data = await get_lang('fast_edit_error') + db_data
  1809. elif num == 25:
  1810. data = await get_lang('too_many_dec_error')
  1811. elif num == 26:
  1812. data = await get_lang('application_not_found')
  1813. elif num == 27:
  1814. data = await get_lang("invalid_password_error")
  1815. elif num == 28:
  1816. data = await get_lang('watchlist_overflow_error')
  1817. elif num == 29:
  1818. data = await get_lang('copyright_disagreed')
  1819. elif num == 30:
  1820. data = await get_lang('ie_wrong_callback')
  1821. elif num == 33:
  1822. data = await get_lang('restart_fail_error')
  1823. elif num == 34:
  1824. data = await get_lang("update_error") + ' <a href="https://github.com/opennamu/opennamu">(Github)</a>'
  1825. elif num == 35:
  1826. data = await get_lang('same_email_error')
  1827. elif num == 36:
  1828. data = await get_lang('input_email_error')
  1829. elif num == 37:
  1830. data = await get_lang('error_edit_send_request')
  1831. elif num == 38:
  1832. curs.execute(db_change("select data from other where name = 'title_max_length'"))
  1833. db_data = curs.fetchall()
  1834. db_data = '' if not db_data else db_data[0][0]
  1835. data = await get_lang('error_title_length_too_long') + db_data
  1836. elif num == 39:
  1837. curs.execute(db_change("select data from other where name = 'title_topic_max_length'"))
  1838. db_data = curs.fetchall()
  1839. db_data = '' if not db_data else db_data[0][0]
  1840. data = await get_lang('error_title_length_too_long') + db_data
  1841. elif num == 40:
  1842. curs.execute(db_change("select data from other where name = 'password_min_length'"))
  1843. db_data = curs.fetchall()
  1844. password_min_length = '' if not db_data else db_data[0][0]
  1845. data = await get_lang('error_password_length_too_short') + password_min_length
  1846. elif num == 41:
  1847. curs.execute(db_change("select data from other where name = 'edit_timeout'"))
  1848. db_data = curs.fetchall()
  1849. db_data = '' if not db_data else db_data[0][0]
  1850. data = await get_lang('timeout_error') + db_data
  1851. elif num == 42:
  1852. curs.execute(db_change("select data from other where name = 'slow_thread'"))
  1853. db_data = curs.fetchall()
  1854. db_data = '' if not db_data else db_data[0][0]
  1855. data = await get_lang('fast_edit_error') + db_data
  1856. elif num == 43:
  1857. title = await get_lang('application_submitted')
  1858. sub_title = title
  1859. data = await get_lang('waiting_for_approval')
  1860. elif num == 44:
  1861. curs.execute(db_change("select data from other where name = 'document_content_max_length'"))
  1862. db_data = curs.fetchall()
  1863. db_data = '' if not db_data else db_data[0][0]
  1864. data = await get_lang('error_content_length_too_long') + db_data
  1865. elif num == 45:
  1866. data = await get_lang('cidr_error')
  1867. elif num == 46:
  1868. data = await get_lang('func_404_error')
  1869. title = '404'
  1870. return_code = 404
  1871. elif num == 47:
  1872. data = await get_lang('still_use_auth_error')
  1873. elif num == 48:
  1874. data = await get_lang('xss_data_include_error')
  1875. elif num == 49:
  1876. data = await get_lang('password_same_as_id_error')
  1877. else:
  1878. data = '???'
  1879. if num == 5:
  1880. if flask.request.path != '/skin_set':
  1881. data += '<br>' + await get_lang('error_skin_set_old') + ' <a href="/skin_set">(' + await get_lang('go') + ')</a>'
  1882. return await render_template(
  1883. await get_lang('skin_set'),
  1884. '' + \
  1885. '<div id="main_skin_set">' + \
  1886. '<h2>' + await get_lang('error') + '</h2>' + \
  1887. '<ul>' + \
  1888. '<li>' + data + '</a></li>' + \
  1889. '</ul>' + \
  1890. '</div>' + \
  1891. '',
  1892. 0,
  1893. [['change', await get_lang('user_setting')], ['change/skin_set/main', await get_lang('main_skin_set')]]
  1894. )
  1895. else:
  1896. return await render_template(
  1897. title,
  1898. '' + \
  1899. '<h2>' + sub_title + '</h2>' + \
  1900. '<ul>' + \
  1901. '<li>' + data + '</li>' + \
  1902. '</ul>' + \
  1903. '',
  1904. 0,
  1905. 0
  1906. ), return_code