func.py 105 KB

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