func.py 86 KB

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