func.py 94 KB

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