func.py 105 KB

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