func.py 105 KB

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