func.py 96 KB

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