func.py 108 KB

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