func.py 96 KB

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