func.py 105 KB

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