func.py 84 KB

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