func.py 95 KB

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