2
0

func.py 94 KB

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