func.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762
  1. # Init
  2. import os
  3. import sys
  4. import platform
  5. import json
  6. import smtplib
  7. import zipfile
  8. import shutil
  9. import logging
  10. import random
  11. import email.mime.text
  12. import email.utils
  13. import email.header
  14. import urllib.request
  15. # Init-Version
  16. version_list = json.loads(open('version.json', encoding = 'utf8').read())
  17. print('Version : ' + version_list['beta']['r_ver'])
  18. print('DB set version : ' + version_list['beta']['c_ver'])
  19. print('Skin set version : ' + version_list['beta']['s_ver'])
  20. print('----')
  21. # Init-PIP_Install
  22. data_up_date = 1
  23. if os.path.exists(os.path.join('data', 'version.json')):
  24. data_load_ver = open(os.path.join('data', 'version.json'), encoding = 'utf8').read()
  25. if data_load_ver == version_list['beta']['r_ver']:
  26. data_up_date = 0
  27. if data_up_date == 1:
  28. with open(os.path.join('data', 'version.json'), 'w', encoding = 'utf8') as f:
  29. f.write(version_list['beta']['r_ver'])
  30. if platform.system() in ('Linux', 'Windows'):
  31. os.system(
  32. 'python' + ('3' if platform.system() != 'Windows' else '') + ' ' + \
  33. '-m pip install --upgrade --user -r requirements.txt'
  34. )
  35. print('----')
  36. try:
  37. os.execl(sys.executable, sys.executable, *sys.argv)
  38. except:
  39. pass
  40. try:
  41. os.execl(sys.executable, '"' + sys.executable + '"', *sys.argv)
  42. except:
  43. print('Error : restart failed')
  44. raise
  45. else:
  46. print('Error : automatic installation is not supported.')
  47. print('Help : try "python3 -m pip install -r requirements.txt"')
  48. else:
  49. print('PIP check pass')
  50. print('----')
  51. # Init-Load
  52. from .func_mark import *
  53. from diff_match_patch import diff_match_patch
  54. from gevent.pywsgi import WSGIServer
  55. import werkzeug.routing
  56. import werkzeug.debug
  57. import flask
  58. import requests
  59. import pymysql
  60. if sys.version_info < (3, 6):
  61. import sha3
  62. # Init-Global
  63. global_lang = {}
  64. global_wiki_set = {}
  65. data_css_ver = '106'
  66. data_css = ''
  67. conn = ''
  68. curs = ''
  69. # Func
  70. # Func-main
  71. def load_conn(data):
  72. global conn
  73. global curs
  74. conn = data
  75. curs = conn.cursor()
  76. load_conn2(data)
  77. # Func-init
  78. class server_init:
  79. def __init__(self):
  80. self.env_dict = {
  81. 'host' : os.getenv('NAMU_HOST'),
  82. 'port' : os.getenv('NAMU_PORT'),
  83. 'language' : os.getenv('NAMU_LANG'),
  84. 'markup' : os.getenv('NAMU_MARKUP'),
  85. 'encode' : os.getenv('NAMU_ENCRYPT')
  86. }
  87. self.server_set_var = {
  88. 'host' : {
  89. 'display' : 'Host',
  90. 'require' : 'conv',
  91. 'default' : '0.0.0.0'
  92. }, 'port' : {
  93. 'display' : 'Port',
  94. 'require' : 'conv',
  95. 'default' : '3000'
  96. }, 'language' : {
  97. 'display' : 'Language',
  98. 'require' : 'select',
  99. 'default' : 'ko-KR',
  100. 'list' : ['ko-KR', 'en-US']
  101. }, 'markup' : {
  102. 'display' : 'Markup',
  103. 'require' : 'select',
  104. 'default' : 'namumark',
  105. 'list' : ['namumark', 'custom', 'raw']
  106. }, 'encode' : {
  107. 'display' : 'Encryption method',
  108. 'require' : 'select',
  109. 'default' : 'sha3',
  110. 'list' : ['sha3', 'sha256']
  111. }
  112. }
  113. def server_init(self):
  114. return self.server_set_var
  115. def init(self, key):
  116. if self.env_dict[key] != None:
  117. return self.env_dict[key]
  118. else:
  119. while 1:
  120. if self.server_set_var[key]['require'] == 'select':
  121. list_ = '[' + ', '.join(self.server_set_var[key]['list']) + ']'
  122. else:
  123. list_ = ''
  124. print('{} ({}) {} : '.format(
  125. self.server_set_var[key]['display'],
  126. self.server_set_var[key]['default'],
  127. list_
  128. ), end = '')
  129. server_set_val = input()
  130. if server_set_val:
  131. if self.server_set_var[key]['require'] == 'select':
  132. if server_set_val not in self.server_set_var[key]['list']:
  133. pass
  134. else:
  135. return server_set_val
  136. else:
  137. return server_set_val
  138. else:
  139. return self.server_set_var[key]['default']
  140. def get_conn(db_set):
  141. if db_set['type'] == 'sqlite':
  142. conn = sqlite3.connect(db_set['name'] + '.db')
  143. curs = conn.cursor()
  144. else:
  145. conn = pymysql.connect(
  146. host = db_set['mysql_host'],
  147. user = db_set['mysql_user'],
  148. password = db_set['mysql_pw'],
  149. charset = 'utf8mb4',
  150. port = int(db_set['mysql_port'])
  151. )
  152. curs = conn.cursor()
  153. try:
  154. curs.execute(db_change(
  155. 'create database ' + db_set['name'] + ' ' + \
  156. 'default character set utf8mb4;'
  157. ))
  158. except:
  159. pass
  160. conn.select_db(db_set['name'])
  161. return conn
  162. def update(ver_num, set_data):
  163. print('----')
  164. # 업데이트 하위 호환 유지 함수
  165. if ver_num < 3160027:
  166. print('Add init set')
  167. set_init()
  168. if ver_num < 3170002:
  169. curs.execute(db_change("select html from html_filter where kind = 'extension'"))
  170. if not curs.fetchall():
  171. for i in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
  172. curs.execute(db_change(
  173. "insert into html_filter (html, kind) values (?, 'extension')"
  174. ), [i])
  175. if ver_num < 3170400:
  176. curs.execute(db_change("select title, sub, code from topic where id = '1'"))
  177. for i in curs.fetchall():
  178. curs.execute(db_change(
  179. "update topic set code = ? where title = ? and sub = ?"
  180. ), [
  181. i[2],
  182. i[0],
  183. i[1]
  184. ])
  185. curs.execute(db_change(
  186. "update rd set code = ? where title = ? and sub = ?"
  187. ), [
  188. i[2],
  189. i[0],
  190. i[1]
  191. ])
  192. if ver_num < 3171800:
  193. curs.execute(db_change("select data from other where name = 'recaptcha'"))
  194. change_rec = curs.fetchall()
  195. if change_rec and change_rec[0][0] != '':
  196. new_rec = re.search(r'data-sitekey="([^"]+)"', change_rec[0][0])
  197. if new_rec:
  198. curs.execute(db_change(
  199. "update other set data = ? where name = 'recaptcha'"
  200. ), [new_rec.group(1)])
  201. else:
  202. curs.execute(db_change("update other set data = '' where name = 'recaptcha'"))
  203. curs.execute(db_change("update other set data = '' where name = 'sec_re'"))
  204. if ver_num < 3172800 and \
  205. set_data['db_type'] == 'mysql':
  206. get_data_mysql = json.loads(open('data/mysql.json', encoding = 'utf8').read())
  207. with open('data/mysql.json', 'w') as f:
  208. f.write('{ "user" : "' + get_data_mysql['user'] + '", "password" : "' + get_data_mysql['password'] + '", "host" : "localhost" }')
  209. if ver_num < 3183603:
  210. curs.execute(db_change("select block from ban where band = 'O'"))
  211. for i in curs.fetchall():
  212. curs.execute(db_change(
  213. "update ban set block = ?, band = 'regex' where block = ? and band = 'O'"
  214. ), [
  215. '^' + i[0].replace('.', '\\.'),
  216. i[0]
  217. ])
  218. curs.execute(db_change("select block from rb where band = 'O'"))
  219. for i in curs.fetchall():
  220. curs.execute(db_change(
  221. "update rb set block = ?, band = 'regex' where block = ? and band = 'O'"
  222. ), [
  223. '^' + i[0].replace('.', '\\.'),
  224. i[0]
  225. ])
  226. if ver_num < 3190201:
  227. today_time = get_time()
  228. curs.execute(db_change("select block, end, why, band, login from ban"))
  229. for i in curs.fetchall():
  230. curs.execute(db_change(
  231. "insert into rb (block, end, today, why, band, login, ongoing) " + \
  232. "values (?, ?, ?, ?, ?, ?, ?)"
  233. ), [
  234. i[0],
  235. i[1],
  236. today_time,
  237. i[2],
  238. i[3],
  239. i[4],
  240. '1'
  241. ])
  242. if ver_num < 3191301:
  243. curs.execute(db_change('' + \
  244. 'select id, title, date from history ' + \
  245. 'where not title like "user:%" ' + \
  246. 'order by date desc ' + \
  247. 'limit 50' + \
  248. ''))
  249. data_list = curs.fetchall()
  250. for get_data in data_list:
  251. curs.execute(db_change(
  252. "insert into rc (id, title, date, type) values (?, ?, ?, 'normal')"
  253. ), [
  254. get_data[0],
  255. get_data[1],
  256. get_data[2]
  257. ])
  258. if ver_num < 3202400:
  259. curs.execute(db_change("select data from other where name = 'update'"))
  260. get_data = curs.fetchall()
  261. if get_data and get_data[0][0] == 'master':
  262. curs.execute(db_change("update other set data = 'beta' where name = 'update'"), [])
  263. if ver_num < 3202600:
  264. curs.execute(db_change("select name, regex, sub from filter"))
  265. for i in curs.fetchall():
  266. curs.execute(db_change(
  267. "insert into html_filter (html, kind, plus, plus_t) " + \
  268. "values (?, 'regex_filter', ?, ?)"
  269. ), [
  270. i[0],
  271. i[1],
  272. i[2]
  273. ])
  274. curs.execute(db_change("select title, link, icon from inter"))
  275. for i in curs.fetchall():
  276. curs.execute(db_change(
  277. "insert into html_filter (html, kind, plus, plus_t) " + \
  278. "values (?, 'inter_wiki', ?, ?)"), [
  279. i[0],
  280. i[1],
  281. i[2]
  282. ])
  283. if ver_num < 3203400:
  284. curs.execute(db_change("select user, css from custom"))
  285. for i in curs.fetchall():
  286. curs.execute(db_change(
  287. "insert into user_set (name, id, data) values ('custom_css', ?, ?)"
  288. ), [
  289. re.sub(r' \(head\)$', '', i[0]),
  290. i[1]
  291. ])
  292. if ver_num < 3205500:
  293. curs.execute(db_change("select title, decu, dis, view, why from acl"))
  294. for i in curs.fetchall():
  295. curs.execute(db_change(
  296. "insert into acl (title, data, type) values (?, ?, ?)"
  297. ), [i[0], i[1], 'decu'])
  298. curs.execute(db_change(
  299. "insert into acl (title, data, type) values (?, ?, ?)"
  300. ), [i[0], i[2], 'dis'])
  301. curs.execute(db_change(
  302. "insert into acl (title, data, type) values (?, ?, ?)"
  303. ), [i[0], i[3], 'view'])
  304. curs.execute(db_change(
  305. "insert into acl (title, data, type) values (?, ?, ?)"
  306. ), [i[0], i[4], 'why'])
  307. if ver_num < 3300101:
  308. # 캐시 초기화
  309. curs.execute(db_change('delete from cache_data'))
  310. if ver_num < 3300301:
  311. # regex_filter 오류 해결
  312. curs.execute(db_change(
  313. 'delete from html_filter where kind = "regex_filter" and html is null'
  314. ))
  315. if ver_num < 3302302:
  316. # user이랑 user_set 테이블의 통합
  317. curs.execute(db_change('select id, pw, acl, date, encode from user'))
  318. for i in curs.fetchall():
  319. curs.execute(db_change(
  320. "insert into user_set (name, id, data) values (?, ?, ?)"
  321. ), ['pw', i[0], i[1]])
  322. curs.execute(db_change(
  323. "insert into user_set (name, id, data) values (?, ?, ?)"
  324. ), ['acl', i[0], i[2]])
  325. curs.execute(db_change(
  326. "insert into user_set (name, id, data) values (?, ?, ?)"
  327. ), ['date', i[0], i[3]])
  328. curs.execute(db_change(
  329. "insert into user_set (name, id, data) values (?, ?, ?)"
  330. ), ['encode', i[0], i[4]])
  331. if ver_num < 3400101:
  332. # user_set이랑 user_application 테이블의 통합
  333. curs.execute(db_change('' + \
  334. 'select id, pw, date, encode, question, answer, ip, ua, email ' + \
  335. 'from user_application' + \
  336. ''))
  337. for i in curs.fetchall():
  338. sql_data = {}
  339. sql_data['id'] = i[0]
  340. sql_data['pw'] = i[1]
  341. sql_data['date'] = i[2]
  342. sql_data['encode'] = i[3]
  343. sql_data['question'] = i[4]
  344. sql_data['answer'] = i[5]
  345. sql_data['ip'] = i[6]
  346. sql_data['ua'] = i[7]
  347. sql_data['email'] = i[8]
  348. curs.execute(db_change(
  349. "insert into user_set (name, id, data) values (?, ?, ?)"
  350. ), ['application', i[0], json.dumps(sql_data)])
  351. conn.commit()
  352. print('Update completed')
  353. def set_init_always(ver_num):
  354. curs.execute(db_change('delete from other where name = "ver"'))
  355. curs.execute(db_change('insert into other (name, data) values ("ver", ?)'), [ver_num])
  356. curs.execute(db_change('delete from alist where name = "owner"'))
  357. curs.execute(db_change('insert into alist (name, acl) values ("owner", "owner")'))
  358. if not os.path.exists(load_image_url()):
  359. os.makedirs(load_image_url())
  360. conn.commit()
  361. def set_init():
  362. # 초기값 설정 함수
  363. curs.execute(db_change("select html from html_filter where kind = 'email'"))
  364. if not curs.fetchall():
  365. for i in ['naver.com', 'gmail.com', 'daum.net', 'kakao.com']:
  366. curs.execute(db_change(
  367. "insert into html_filter (html, kind) values (?, 'email')"
  368. ), [i])
  369. curs.execute(db_change("select html from html_filter where kind = 'extension'"))
  370. if not curs.fetchall():
  371. for i in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
  372. curs.execute(db_change(
  373. "insert into html_filter (html, kind) values (?, 'extension')"
  374. ), [i])
  375. curs.execute(db_change(
  376. 'select data from other ' + \
  377. 'where name = "smtp_server" or name = "smtp_port" or name = "smtp_security"'
  378. ))
  379. if not curs.fetchall():
  380. for i in [
  381. ['smtp_server', 'smtp.gmail.com'],
  382. ['smtp_port', '587'],
  383. ['smtp_security', 'starttls']
  384. ]:
  385. curs.execute(db_change(
  386. "insert into other (name, data) values (?, ?)"
  387. ), [i[0], i[1]])
  388. curs.execute(db_change('select data from other where name = "key"'))
  389. rep_data = curs.fetchall()
  390. if not rep_data:
  391. rep_key = ''.join(random.choice("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for i in range(64))
  392. curs.execute(db_change('insert into other (name, data) values ("key", ?)'), [rep_key])
  393. curs.execute(db_change('select data from other where name = "count_all_title"'))
  394. if not curs.fetchall():
  395. curs.execute(db_change('insert into other (name, data) values ("count_all_title", "0")'))
  396. conn.commit()
  397. # Func-simple
  398. def get_default_admin_group():
  399. return ['owner', 'ban']
  400. def load_image_url():
  401. curs.execute(db_change('select data from other where name = "image_where"'))
  402. image_where = curs.fetchall()
  403. image_where = image_where[0][0] if image_where else 'data/images'
  404. return image_where
  405. def http_warning():
  406. return '''
  407. <div id="http_warning_text"></div>
  408. <script>
  409. if(window.location.protocol !== 'https:') {
  410. document.getElementById('http_warning_text').innerHTML = "''' + \
  411. load_lang('http_warning') + \
  412. '''";
  413. document.getElementById('http_warning_text').style.margin = "10px 0px 0px 0px";
  414. }
  415. </script>
  416. '''
  417. def load_domain():
  418. curs.execute(db_change("select data from other where name = 'domain'"))
  419. domain = curs.fetchall()
  420. domain = domain[0][0] if domain and domain[0][0] != '' else flask.request.host_url
  421. return domain
  422. def load_random_key(long = 64):
  423. return ''.join(
  424. random.choice(
  425. "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  426. ) for i in range(long)
  427. )
  428. def edit_button():
  429. insert_list = []
  430. curs.execute(db_change("select html, plus from html_filter where kind = 'edit_top'"))
  431. db_data = curs.fetchall()
  432. for get_data in db_data:
  433. insert_list += [[get_data[1], get_data[0]]]
  434. data = ''
  435. for insert_data in insert_list:
  436. data += '' + \
  437. '<a href="' + \
  438. 'javascript:do_insert_data(\'content\', \'' + insert_data[0] + '\')' + \
  439. '">(' + insert_data[1] + ')</a> ' + \
  440. ''
  441. data += (' ' if data != '' else '') + '<a href="/edit_top">(' + load_lang('add') + ')</a>'
  442. data += '<hr class="main_hr">'
  443. return data
  444. def ip_warning():
  445. if ip_or_user() != 0:
  446. curs.execute(db_change('select data from other where name = "no_login_warning"'))
  447. data = curs.fetchall()
  448. if data and data[0][0] != '':
  449. text_data = '' + \
  450. '<span>' + data[0][0] + '</span>' + \
  451. '<hr class="main_hr">' + \
  452. ''
  453. else:
  454. text_data = '' + \
  455. '<span>' + load_lang('no_login_warning') + '</span>' + \
  456. '<hr class="main_hr">' + \
  457. ''
  458. else:
  459. text_data = ''
  460. return text_data
  461. def next_fix(link, num, page, end = 50):
  462. list_data = ''
  463. if num == 1:
  464. if len(page) == end:
  465. list_data += '' + \
  466. '<hr class="main_hr">' + \
  467. '<a href="' + link + str(num + 1) + '">(' + load_lang('next') + ')</a>' + \
  468. ''
  469. elif len(page) != end:
  470. list_data += '' + \
  471. '<hr class="main_hr">' + \
  472. '<a href="' + link + str(num - 1) + '">(' + load_lang('previous') + ')</a>' + \
  473. ''
  474. else:
  475. list_data += '' + \
  476. '<hr class="main_hr">' + \
  477. '<a href="' + link + str(num - 1) + '">(' + load_lang('previous') + ')</a> <a href="' + link + str(num + 1) + '">(' + load_lang('next') + ')</a>' + \
  478. ''
  479. return list_data
  480. def leng_check(first, second):
  481. if first < second:
  482. all_plus = '+' + str(second - first)
  483. elif second < first:
  484. all_plus = '-' + str(first - second)
  485. else:
  486. all_plus = '0'
  487. return all_plus
  488. def number_check(data):
  489. try:
  490. int(data)
  491. return data
  492. except:
  493. return '1'
  494. def redirect(data = '/'):
  495. return flask.redirect(flask.request.host_url[:-1] + data)
  496. def get_acl_list(type_d = 'normal'):
  497. if type_d == 'user':
  498. return ['', 'user', 'all']
  499. else:
  500. return ['', 'all', 'user', 'admin', 'owner', '50_edit', 'email', 'ban', 'before', '30_day', 'ban_admin']
  501. # Func-login
  502. def pw_encode(data, type_d = ''):
  503. if type_d == '':
  504. curs.execute(db_change('select data from other where name = "encode"'))
  505. set_data = curs.fetchall()
  506. type_d = set_data[0][0]
  507. if type_d == 'sha256':
  508. return hashlib.sha256(bytes(data, 'utf-8')).hexdigest()
  509. else:
  510. if sys.version_info < (3, 6):
  511. return sha3.sha3_256(bytes(data, 'utf-8')).hexdigest()
  512. else:
  513. return hashlib.sha3_256(bytes(data, 'utf-8')).hexdigest()
  514. def pw_check(data, data2, type_d = 'no', id_d = ''):
  515. curs.execute(db_change('select data from other where name = "encode"'))
  516. db_data = curs.fetchall()
  517. if type_d != 'no':
  518. if type_d == '':
  519. set_data = 'sha3'
  520. else:
  521. set_data = type_d
  522. else:
  523. set_data = db_data[0][0]
  524. re_data = 1 if pw_encode(data, set_data) == data2 else 0
  525. if db_data[0][0] != set_data and re_data == 1 and id_d != '':
  526. curs.execute(db_change("update user_set set data = ? where id = ? and name = 'pw'"), [
  527. pw_encode(data),
  528. id_d
  529. ])
  530. curs.execute(db_change("update user_set set data = ? where id = ? and name = 'encode'"), [
  531. db_data[0][0],
  532. id_d
  533. ])
  534. return re_data
  535. # Func-skin
  536. def easy_minify(data, tool = None):
  537. return data
  538. def load_lang(data, safe = 0):
  539. global global_lang
  540. ip = ip_check()
  541. if ip_or_user(ip) == 0:
  542. curs.execute(db_change('select data from user_set where name = "lang" and id = ?'), [ip])
  543. rep_data = curs.fetchall()
  544. elif 'lang' in flask.session:
  545. rep_data = [[flask.session['lang']]]
  546. else:
  547. curs.execute(db_change("select data from other where name = 'language'"))
  548. rep_data = curs.fetchall()
  549. if not rep_data or rep_data[0][0] in ('', 'default'):
  550. curs.execute(db_change("select data from other where name = 'language'"))
  551. rep_data = curs.fetchall()
  552. if rep_data:
  553. lang_name = rep_data[0][0]
  554. else:
  555. lang_name = 'en-US'
  556. if lang_name in global_lang:
  557. lang = global_lang[lang_name]
  558. else:
  559. lang_list = os.listdir('lang')
  560. if (lang_name + '.json') in lang_list:
  561. lang = json.loads(open(
  562. os.path.join('lang', lang_name + '.json'),
  563. encoding = 'utf8'
  564. ).read())
  565. global_lang[lang_name] = lang
  566. else:
  567. lang = {}
  568. if data in lang:
  569. if safe == 1:
  570. return lang[data]
  571. else:
  572. return html.escape(lang[data])
  573. return html.escape(data + ' (' + lang_name + ')')
  574. def skin_check(set_n = 0):
  575. # 개편 필요?
  576. skin_list = load_skin('tenshi', 1)
  577. skin = skin_list[0]
  578. ip = ip_check()
  579. user_need_skin = ''
  580. if ip_or_user(ip) == 0:
  581. curs.execute(db_change('select data from user_set where name = "skin" and id = ?'), [ip])
  582. skin_exist = curs.fetchall()
  583. if skin_exist:
  584. user_need_skin = skin_exist[0][0]
  585. else:
  586. if 'skin' in flask.session:
  587. user_need_skin = flask.session['skin']
  588. if user_need_skin == '':
  589. curs.execute(db_change('select data from other where name = "skin"'))
  590. skin_exist = curs.fetchall()
  591. if skin_exist:
  592. user_need_skin = skin_exist[0][0]
  593. if user_need_skin != '' and user_need_skin in skin_list:
  594. skin = user_need_skin
  595. if set_n == 0:
  596. return './views/' + skin + '/index.html'
  597. else:
  598. return skin
  599. def wiki_css(data):
  600. global data_css
  601. global data_css_ver
  602. data += ['' for _ in range(0, 3 - len(data))]
  603. if data_css == '':
  604. for i_data in os.listdir(os.path.join("views", "main_css", "css")):
  605. if i_data != 'sub':
  606. data_css += '<link rel="stylesheet" href="/views/main_css/css/' + i_data + '?ver=' + data_css_ver + '">'
  607. for i_data in os.listdir(os.path.join("views", "main_css", "js")):
  608. if i_data != 'sub':
  609. data_css += '<script src="/views/main_css/js/' + i_data + '?ver=' + data_css_ver + '"></script>'
  610. data = data[0:2] + ['', '''
  611. <link rel="stylesheet"
  612. href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.2.0/build/styles/default.min.css">
  613. <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.2.0/build/highlight.min.js"></script>
  614. <link defer rel="stylesheet"
  615. href="https://cdn.jsdelivr.net/npm/katex@0.13.2/dist/katex.min.css"
  616. integrity="sha384-Cqd8ihRLum0CCg8rz0hYKPoLZ3uw+gES2rXQXycqnL5pgVQIflxAUDS7ZSjITLb5"
  617. crossorigin="anonymous">
  618. <script src="https://cdn.jsdelivr.net/npm/katex@0.13.2/dist/katex.min.js"
  619. integrity="sha384-1Or6BdeNQb0ezrmtGeqQHFpppNd7a/gw29xeiSikBbsb44xu3uAo8c7FwbF5jhbd"
  620. crossorigin="anonymous"></script>
  621. ''' + data_css + '<script>window.addEventListener(\'DOMContentLoaded\', main_css_skin_load);</script>'] + data[2:]
  622. return data
  623. def cut_100(data):
  624. if re.search(r'^\/w\/', flask.request.path):
  625. data = re.sub(r'<script>((\n*(((?!<\/script>).)+)\n*)+)<\/script>', '', data)
  626. data = re.sub(r'<hr class="main_hr">((\n*((.+)\n*))+)$', '', data)
  627. data = re.sub(r'<div id="cate_all">((\n*((.+)\n*))+)$', '', data)
  628. data = re.sub(r'<(((?!>).)*)>', ' ', data)
  629. data = re.sub(r'\n', ' ', data)
  630. data = re.sub(r'^ +', '', data)
  631. data = re.sub(r' +$', '', data)
  632. data = re.sub(r' {2,}', ' ', data)
  633. return data[0:100] + '...'
  634. else:
  635. return ''
  636. def wiki_set(num = 1):
  637. if num == 1:
  638. skin_name = skin_check(1)
  639. data_list = []
  640. curs.execute(db_change('select data from other where name = ?'), ['name'])
  641. db_data = curs.fetchall()
  642. data_list += [db_data[0][0]] if db_data and db_data[0][0] != '' else ['Wiki']
  643. curs.execute(db_change('select data from other where name = "license"'))
  644. db_data = curs.fetchall()
  645. data_list += [db_data[0][0]] if db_data and db_data[0][0] != '' else ['ARR']
  646. data_list += ['', '']
  647. curs.execute(db_change('select data from other where name = "logo" and coverage = ?'), [skin_name])
  648. db_data = curs.fetchall()
  649. if db_data and db_data[0][0] != '':
  650. data_list += [db_data[0][0]]
  651. else:
  652. curs.execute(db_change('select data from other where name = "logo" and coverage = ""'))
  653. db_data = curs.fetchall()
  654. data_list += [db_data[0][0]] if db_data and db_data[0][0] != '' else [data_list[0]]
  655. head_data = ''
  656. curs.execute(db_change("select data from other where name = 'head' and coverage = ''"))
  657. db_data = curs.fetchall()
  658. head_data += db_data[0][0] if db_data and db_data[0][0] != '' else ''
  659. curs.execute(db_change("select data from other where name = 'head' and coverage = ?"), [skin_name])
  660. db_data = curs.fetchall()
  661. head_data += db_data[0][0] if db_data and db_data[0][0] != '' else ''
  662. data_list += [head_data]
  663. elif num == 2:
  664. curs.execute(db_change('select data from other where name = "frontpage"'))
  665. db_data = curs.fetchall()
  666. data_list = db_data[0][0] if db_data and db_data[0][0] != '' else 'FrontPage'
  667. elif num == 3:
  668. curs.execute(db_change('select data from other where name = "upload"'))
  669. db_data = curs.fetchall()
  670. data_list = db_data[0][0] if db_data and db_data[0][0] != '' else '2'
  671. else:
  672. data_list = ''
  673. return data_list
  674. def wiki_custom():
  675. ip = ip_check()
  676. if ip_or_user(ip) == 0:
  677. user_icon = 1
  678. user_name = ip
  679. curs.execute(db_change("select data from user_set where id = ? and name = 'custom_css'"), [ip])
  680. user_head = curs.fetchall()
  681. user_head = user_head[0][0] if user_head else ''
  682. curs.execute(db_change('select data from user_set where name = "email" and id = ?'), [ip])
  683. email = curs.fetchall()
  684. email = email[0][0] if email else ''
  685. if admin_check('all') == 1:
  686. user_admin = '1'
  687. user_acl_list = []
  688. curs.execute(db_change("select data from user_set where id = ? and name = 'acl'"), [ip])
  689. curs.execute(db_change('select acl from alist where name = ?'), [curs.fetchall()[0][0]])
  690. user_acl = curs.fetchall()
  691. for i in user_acl:
  692. user_acl_list += [i[0]]
  693. user_acl_list = user_acl_list if user_acl != [] else '0'
  694. else:
  695. user_admin = '0'
  696. user_acl_list = '0'
  697. curs.execute(db_change("select count(*) from alarm where name = ?"), [ip])
  698. count = curs.fetchall()
  699. user_notice = str(count[0][0]) if count else '0'
  700. else:
  701. user_icon = 0
  702. user_name = load_lang('user')
  703. email = ''
  704. user_admin = '0'
  705. user_acl_list = '0'
  706. user_notice = '0'
  707. user_head = flask.session['head'] if 'head' in flask.session else ''
  708. curs.execute(db_change("select title from rd where title = ? and stop = ''"), ['user:' + ip])
  709. user_topic = '1' if curs.fetchall() else '0'
  710. return [
  711. '',
  712. '',
  713. user_icon,
  714. user_head,
  715. email,
  716. user_name,
  717. user_admin,
  718. str(ban_check()),
  719. user_notice,
  720. user_acl_list,
  721. ip,
  722. user_topic
  723. ]
  724. def load_skin(data = '', set_n = 0, default = 0):
  725. # data -> 가장 앞에 있을 스킨 이름
  726. # set_n == 0 -> 스트링으로 반환
  727. # set_n == 1 -> 리스트로 반환
  728. # default == 0 -> 디폴트 미포함
  729. # default == 1 -> 디폴트 포함
  730. if set_n == 0:
  731. skin_return_data = ''
  732. else:
  733. skin_return_data = []
  734. skin_list_get = os.listdir('views')
  735. if default == 1:
  736. skin_list_get += ['default']
  737. for skin_data in skin_list_get:
  738. if skin_data != 'default':
  739. see_data = skin_data
  740. else:
  741. see_data = load_lang('default')
  742. if skin_data != 'main_css':
  743. if set_n == 0:
  744. if skin_data == data:
  745. skin_return_data = '' + \
  746. '<option value="' + skin_data + '">' + \
  747. see_data + \
  748. '</option>' + \
  749. '' + skin_return_data
  750. else:
  751. skin_return_data += '' + \
  752. '<option value="' + skin_data + '">' + \
  753. see_data + \
  754. '</option>' + \
  755. ''
  756. else:
  757. if skin_data == data:
  758. skin_return_data = [skin_data] + skin_return_data
  759. else:
  760. skin_return_data += [skin_data]
  761. return skin_return_data
  762. # Func-markup
  763. def render_set(doc_name = '', doc_data = '', data_type = 'view', data_in = '', doc_acl = ''):
  764. # data_type in ['view', 'raw', 'api_view', 'backlink']
  765. doc_acl = acl_check(doc_name, 'render') if doc_acl == '' else doc_acl
  766. doc_data = 0 if doc_data == None else doc_data
  767. if doc_acl == 1:
  768. return 'HTTP Request 401.3'
  769. else:
  770. if data_type == 'raw':
  771. return doc_data
  772. else:
  773. if doc_data != 0:
  774. return render_do(doc_name, doc_data, data_type, data_in)
  775. else:
  776. return 'HTTP Request 404'
  777. # Func-request
  778. def send_email(who, title, data):
  779. try:
  780. curs.execute(db_change('' + \
  781. 'select name, data from other ' + \
  782. 'where name = "smtp_email" or name = "smtp_pass" or name = "smtp_server" or name = "smtp_port" or name = "smtp_security"' + \
  783. ''))
  784. rep_data = curs.fetchall()
  785. smtp_email = ''
  786. smtp_pass = ''
  787. smtp_server = ''
  788. smtp_security = ''
  789. smtp_port = ''
  790. smtp = ''
  791. for i in rep_data:
  792. if i[0] == 'smtp_email':
  793. smtp_email = i[1]
  794. elif i[0] == 'smtp_pass':
  795. smtp_pass = i[1]
  796. elif i[0] == 'smtp_server':
  797. smtp_server = i[1]
  798. elif i[0] == 'smtp_security':
  799. smtp_security = i[1]
  800. elif i[0] == 'smtp_port':
  801. smtp_port = i[1]
  802. smtp_port = int(smtp_port)
  803. if smtp_security == 'plain':
  804. smtp = smtplib.SMTP(smtp_server, smtp_port)
  805. elif smtp_security == 'starttls':
  806. smtp = smtplib.SMTP(smtp_server, smtp_port)
  807. smtp.starttls()
  808. else:
  809. # if smtp_security == 'tls':
  810. smtp = smtplib.SMTP_SSL(smtp_server, smtp_port)
  811. smtp.login(smtp_email, smtp_pass)
  812. domain = load_domain()
  813. wiki_name = wiki_set()[0]
  814. msg = email.mime.text.MIMEText(data)
  815. msg['Subject'] = title
  816. msg['From'] = 'openNAMU <noreply@' + domain + '>'
  817. msg['To'] = who
  818. smtp.sendmail('openNAMU@' + domain, who, msg.as_string())
  819. smtp.quit()
  820. return 1
  821. except Exception as e:
  822. print('----')
  823. print('Error : email send error')
  824. print(e)
  825. return 0
  826. def captcha_get():
  827. data = ''
  828. if ip_or_user() != 0:
  829. curs.execute(db_change('select data from other where name = "recaptcha"'))
  830. recaptcha = curs.fetchall()
  831. curs.execute(db_change('select data from other where name = "sec_re"'))
  832. sec_re = curs.fetchall()
  833. curs.execute(db_change('select data from other where name = "recaptcha_ver"'))
  834. rec_ver = curs.fetchall()
  835. if recaptcha and recaptcha[0][0] != '' and \
  836. sec_re and sec_re[0][0] != '':
  837. if not rec_ver or rec_ver[0][0] == '':
  838. data += '' + \
  839. '<script src="https://www.google.com/recaptcha/api.js" async defer></script>' + \
  840. '<div class="g-recaptcha" data-sitekey="' + recaptcha[0][0] + '"></div>' + \
  841. '<hr class="main_hr">' + \
  842. ''
  843. else:
  844. data += '' + \
  845. '<script src="https://www.google.com/recaptcha/api.js?render=' + recaptcha[0][0] + '"></script>' + \
  846. '<input type="hidden" id="g-recaptcha" name="g-recaptcha">' + \
  847. '<script type="text/javascript">' + \
  848. 'grecaptcha.ready(function() {' + \
  849. 'grecaptcha.execute(\'' + recaptcha[0][0] + '\', {action: \'homepage\'}).then(function(token) {' + \
  850. 'document.getElementById(\'g-recaptcha\').value = token;' + \
  851. '});' + \
  852. '});' + \
  853. '</script>' + \
  854. ''
  855. return data
  856. def captcha_post(re_data, num = 1):
  857. if num == 1:
  858. curs.execute(db_change('select data from other where name = "sec_re"'))
  859. sec_re = curs.fetchall()
  860. if sec_re and sec_re[0][0] != '' and \
  861. ip_or_user() != 0 and captcha_get() != '':
  862. data = requests.get(
  863. 'https://www.google.com/recaptcha/api/siteverify' + \
  864. '?secret=' + sec_re[0][0] + '&response=' + re_data
  865. )
  866. if data.status_code == 200:
  867. json_data = json.loads(data.text)
  868. if json_data['success'] != True:
  869. return 1
  870. return 0
  871. # Func-user
  872. def ip_or_user(data = ''):
  873. # 1 == ip
  874. # 0 == reg
  875. if data == '':
  876. data = ip_check()
  877. if re.search(r'(\.|:)', data):
  878. return 1
  879. else:
  880. return 0
  881. def admin_check(num = None, what = None, name = ''):
  882. ip = ip_check() if name == '' else name
  883. time_data = get_time()
  884. pass_ok = 0
  885. if ip_or_user(ip) == 0:
  886. curs.execute(db_change(
  887. "select data from user_set where id = ? and name = 'acl'"
  888. ), [ip])
  889. user_auth = curs.fetchall()
  890. if user_auth:
  891. user_auth = user_auth[0][0]
  892. check = {
  893. 0 : 'owner',
  894. 1 : 'ban',
  895. 2 : 'nothing',
  896. 3 : 'toron',
  897. 4 : 'check',
  898. 5 : 'acl',
  899. 6 : 'hidel',
  900. 7 : 'give'
  901. }
  902. if not num:
  903. check = check[0]
  904. elif num == 'all':
  905. check = [check[i] for i in check]
  906. else:
  907. check = check[num]
  908. curs.execute(db_change(
  909. 'select name from alist where name = ? and acl = "owner"'
  910. ), [user_auth])
  911. if curs.fetchall():
  912. pass_ok = 1
  913. else:
  914. if num == 'all':
  915. curs.execute(db_change(
  916. 'select name from alist where name = ?'
  917. ), [user_auth])
  918. else:
  919. curs.execute(db_change(
  920. 'select name from alist where name = ? and acl = ?'
  921. ), [user_auth, check])
  922. if curs.fetchall():
  923. pass_ok = 1
  924. if pass_ok == 1:
  925. if what:
  926. curs.execute(db_change(
  927. "insert into re_admin (who, what, time) values (?, ?, ?)"
  928. ), [ip, what, time_data])
  929. conn.commit()
  930. return 1
  931. return 0
  932. def acl_check(name = 'test', tool = '', topic_num = '1'):
  933. ip = ip_check()
  934. get_ban = ban_check()
  935. acl_c = re.search(r"^user:((?:(?!\/).)*)", name) if name else None
  936. if tool == '' and acl_c:
  937. acl_n = acl_c.groups()
  938. if get_ban == 1:
  939. return 1
  940. if admin_check(5) == 1:
  941. return 0
  942. curs.execute(db_change(
  943. "select data from acl where title = ? and type = 'decu'"
  944. ), ['user:' + acl_n[0]])
  945. acl_data = curs.fetchall()
  946. if acl_data:
  947. if acl_data[0][0] == 'all':
  948. return 0
  949. elif acl_data[0][0] == 'user' and not ip_or_user(ip) == 1:
  950. return 0
  951. elif ip == acl_n[0] and not ip_or_user(ip) == 1:
  952. return 0
  953. else:
  954. if ip == acl_n[0] and not ip_or_user(ip) == 1 and not ip_or_user(acl_n[0]) == 1:
  955. return 0
  956. return 1
  957. if tool == 'topic':
  958. if not name:
  959. curs.execute(db_change("select title from rd where code = ?"), [topic_num])
  960. name = curs.fetchall()
  961. name = name[0][0] if name else 'test'
  962. end = 3
  963. elif tool == 'render' or tool == '' or tool == 'vote':
  964. if tool == '' and acl_check(name, 'render') == 1:
  965. return 1
  966. end = 2
  967. else:
  968. end = 1
  969. for i in range(0, end):
  970. if tool == '':
  971. if i == 0:
  972. curs.execute(db_change(
  973. "select data from acl where title = ? and type = 'decu'"
  974. ), [name])
  975. else:
  976. curs.execute(db_change('select data from other where name = "edit"'))
  977. num = 5
  978. elif tool == 'topic':
  979. if i == 0 and topic_num:
  980. curs.execute(db_change("select acl from rd where code = ?"), [topic_num])
  981. elif i == 1:
  982. curs.execute(db_change(
  983. "select data from acl where title = ? and type = 'dis'"
  984. ), [name])
  985. else:
  986. curs.execute(db_change('select data from other where name = "discussion"'))
  987. num = 3
  988. elif tool == 'upload':
  989. curs.execute(db_change("select data from other where name = 'upload_acl'"))
  990. num = 5
  991. elif tool == 'many_upload':
  992. curs.execute(db_change("select data from other where name = 'many_upload_acl'"))
  993. num = 5
  994. elif tool == 'vote':
  995. if i == 0:
  996. curs.execute(db_change(
  997. 'select acl from vote where id = ? and user = ""'
  998. ), [topic_num])
  999. else:
  1000. curs.execute(db_change('select data from other where name = "vote_acl"'))
  1001. num = None
  1002. else:
  1003. # tool == 'render'
  1004. if i == 0:
  1005. curs.execute(db_change(
  1006. "select data from acl where title = ? and type = 'view'"
  1007. ), [name])
  1008. else:
  1009. curs.execute(db_change("select data from other where name = 'all_view_acl'"))
  1010. num = 5
  1011. acl_data = curs.fetchall()
  1012. if (
  1013. i == (end - 1) and \
  1014. (not acl_data or acl_data[0][0] == '' or acl_data[0][0] == 'normal')
  1015. ) and \
  1016. get_ban == 1 and \
  1017. tool != 'render':
  1018. return 1
  1019. elif acl_data and acl_data[0][0] != 'normal' and acl_data[0][0] != '':
  1020. if acl_data[0][0] != 'ban' and get_ban == 1 and tool != 'render':
  1021. return 1
  1022. if acl_data[0][0] == 'all' or acl_data[0][0] == 'ban':
  1023. return 0
  1024. elif acl_data[0][0] == 'user':
  1025. if ip_or_user(ip) != 1:
  1026. return 0
  1027. elif acl_data[0][0] == 'admin':
  1028. if ip_or_user(ip) != 1:
  1029. if admin_check(num) == 1:
  1030. return 0
  1031. elif acl_data[0][0] == '50_edit':
  1032. if ip_or_user(ip) != 1:
  1033. if admin_check(num) == 1:
  1034. return 0
  1035. else:
  1036. curs.execute(db_change(
  1037. "select count(*) from history where ip = ?"
  1038. ), [ip])
  1039. count = curs.fetchall()
  1040. count = count[0][0] if count else 0
  1041. if count >= 50:
  1042. return 0
  1043. elif acl_data[0][0] == 'before':
  1044. if ip_or_user(ip) != 1:
  1045. if admin_check(num) == 1:
  1046. return 0
  1047. curs.execute(db_change(
  1048. "select ip from history where title = ? and ip = ?"
  1049. ), [name, ip])
  1050. if curs.fetchall():
  1051. return 0
  1052. elif acl_data[0][0] == '30_day':
  1053. if ip_or_user(ip) != 1:
  1054. if admin_check(num) == 1:
  1055. return 0
  1056. else:
  1057. curs.execute(db_change(
  1058. "select data from user_set where id = ? and name = 'date'"
  1059. ), [ip])
  1060. user_date = curs.fetchall()[0][0]
  1061. time_1 = datetime.datetime.strptime(
  1062. user_date,
  1063. '%Y-%m-%d %H:%M:%S'
  1064. ) + datetime.timedelta(days = 30)
  1065. time_2 = datetime.datetime.strptime(
  1066. get_time(),
  1067. '%Y-%m-%d %H:%M:%S'
  1068. )
  1069. if time_2 > time_1:
  1070. return 0
  1071. elif acl_data[0][0] == 'email':
  1072. if ip_or_user(ip) != 1:
  1073. if admin_check(num) == 1:
  1074. return 0
  1075. else:
  1076. curs.execute(db_change(
  1077. "select data from user_set where id = ? and name = 'email'"
  1078. ), [ip])
  1079. if curs.fetchall():
  1080. return 0
  1081. elif acl_data[0][0] == 'owner':
  1082. if admin_check() == 1:
  1083. return 0
  1084. elif acl_data[0][0] == 'ban_admin':
  1085. if admin_check(1) == 1 or ban_check() == 1:
  1086. return 0
  1087. return 1
  1088. else:
  1089. if i == (end - 1):
  1090. if tool == 'topic' and topic_num:
  1091. curs.execute(db_change(
  1092. "select title from rd where code = ? and stop != ''"
  1093. ), [topic_num])
  1094. if curs.fetchall():
  1095. if admin_check(3, 'topic (code ' + topic_num + ')') == 1:
  1096. return 0
  1097. else:
  1098. return 0
  1099. else:
  1100. return 0
  1101. return 1
  1102. def ban_check(ip = None, tool = ''):
  1103. ip = ip_check() if not ip else ip
  1104. tool = '' if not tool else tool
  1105. if admin_check(None, None, ip) == 1:
  1106. return 0
  1107. curs.execute(db_change(
  1108. "update rb set ongoing = '' " + \
  1109. "where end < ? and end != '' and ongoing = '1'"
  1110. ), [get_time()])
  1111. conn.commit()
  1112. curs.execute(db_change("" + \
  1113. "select login, block from rb " + \
  1114. "where band = 'regex' and ongoing = '1'" + \
  1115. ""))
  1116. regex_d = curs.fetchall()
  1117. for test_r in regex_d:
  1118. g_regex = re.compile(test_r[1])
  1119. if g_regex.search(ip):
  1120. if tool == 'login':
  1121. if test_r[0] != 'O':
  1122. return 1
  1123. else:
  1124. return 1
  1125. curs.execute(db_change("" + \
  1126. "select login from rb " + \
  1127. "where block = ? and band = '' and ongoing = '1'" + \
  1128. "" + \
  1129. ""), [ip])
  1130. ban_d = curs.fetchall()
  1131. if ban_d:
  1132. if tool == 'login':
  1133. if ban_d[0][0] != 'O':
  1134. return 1
  1135. else:
  1136. return 1
  1137. return 0
  1138. def ip_pas(raw_ip, type_d = 0):
  1139. hide = 0
  1140. end_ip = {}
  1141. i = 0
  1142. return_data = 0
  1143. if type(raw_ip) != type([]):
  1144. get_ip = [raw_ip]
  1145. return_data = 1
  1146. else:
  1147. get_ip = raw_ip
  1148. curs.execute(db_change("select data from other where name = 'ip_view'"))
  1149. ip_view = curs.fetchall()
  1150. ip_view = ip_view[0][0] if ip_view else ''
  1151. ip_view = '' if admin_check(1) == 1 else ip_view
  1152. get_ip = list(set(get_ip))
  1153. for raw_ip in get_ip:
  1154. change_ip = 0
  1155. is_this_ip = ip_or_user(raw_ip)
  1156. if is_this_ip != 0 and ip_view != '':
  1157. ip = re.sub(r'\.([^.]*)\.([^.]*)$', '.*.*', raw_ip)
  1158. ip = re.sub(r':([^:]*):([^:]*)$', ':*:*', ip)
  1159. change_ip = 1
  1160. else:
  1161. ip = raw_ip
  1162. if type_d == 0:
  1163. if is_this_ip == 0:
  1164. ip = '<a href="/w/' + url_pas('user:' + raw_ip) + '">' + raw_ip + '</a>'
  1165. if change_ip == 0:
  1166. ip += ' <a href="/tool/' + url_pas(raw_ip) + '">(' + load_lang('tool') + ')</a>'
  1167. end_ip[raw_ip] = ip
  1168. if return_data == 1:
  1169. return end_ip[raw_ip]
  1170. else:
  1171. return end_ip
  1172. # Func-edit
  1173. def slow_edit_check():
  1174. curs.execute(db_change("select data from other where name = 'slow_edit'"))
  1175. slow_edit = curs.fetchall()
  1176. if slow_edit and slow_edit != '0' and admin_check(5) != 1:
  1177. slow_edit = slow_edit[0][0]
  1178. curs.execute(db_change(
  1179. "select date from history where ip = ? order by date desc limit 1"
  1180. ), [ip_check()])
  1181. last_edit_data = curs.fetchall()
  1182. if last_edit_data:
  1183. last_edit_data = int(re.sub(' |:|-', '', last_edit_data[0][0]))
  1184. now_edit_data = int(
  1185. (datetime.datetime.now() - datetime.timedelta(
  1186. seconds = int(slow_edit))
  1187. ).strftime("%Y%m%d%H%M%S")
  1188. )
  1189. if last_edit_data > now_edit_data:
  1190. return 1
  1191. return 0
  1192. def edit_filter_do(data):
  1193. if admin_check(1) != 1:
  1194. curs.execute(db_change(
  1195. "select plus, plus_t from html_filter where kind = 'regex_filter' and plus != ''"
  1196. ))
  1197. for data_list in curs.fetchall():
  1198. match = re.compile(data_list[0], re.I)
  1199. if match.search(data):
  1200. ban_insert(
  1201. ip_check(),
  1202. '0' if data_list[1] == 'X' else data_list[1],
  1203. 'edit filter',
  1204. None,
  1205. 'tool:edit filter'
  1206. )
  1207. return 1
  1208. return 0
  1209. # Func-insert
  1210. def add_alarm(who, context):
  1211. curs.execute(db_change(
  1212. 'insert into alarm (name, data, date) values (?, ?, ?)'
  1213. ), [who, context, get_time()])
  1214. def add_user(user_name, user_pw, user_email = '', user_encode = ''):
  1215. if user_encode == '':
  1216. user_pw_hash = pw_encode(user_pw)
  1217. curs.execute(db_change('select data from other where name = "encode"'))
  1218. data_encode = curs.fetchall()
  1219. data_encode = data_encode[0][0]
  1220. else:
  1221. user_pw_hash = user_pw
  1222. data_encode = user_encode
  1223. curs.execute(db_change("select id from user_set limit 1"))
  1224. if not curs.fetchall():
  1225. user_auth = 'owner'
  1226. else:
  1227. user_auth = 'user'
  1228. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'pw', ?)"), [
  1229. user_name,
  1230. user_pw_hash
  1231. ])
  1232. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'acl', ?)"), [
  1233. user_name,
  1234. user_auth
  1235. ])
  1236. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'date', ?)"), [
  1237. user_name,
  1238. get_time()
  1239. ])
  1240. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'encode', ?)"), [
  1241. user_name,
  1242. data_encode
  1243. ])
  1244. if user_email != '':
  1245. curs.execute(db_change("insert into user_set (name, id, data) values ('email', ?, ?)"), [
  1246. user_name,
  1247. user_email
  1248. ])
  1249. conn.commit()
  1250. def ua_plus(u_id, u_ip, u_agent, time):
  1251. curs.execute(db_change("select data from other where name = 'ua_get'"))
  1252. rep_data = curs.fetchall()
  1253. if rep_data and rep_data[0][0] != '':
  1254. pass
  1255. else:
  1256. curs.execute(db_change(
  1257. "insert into ua_d (name, ip, ua, today, sub) values (?, ?, ?, ?, '')"
  1258. ), [
  1259. u_id,
  1260. u_ip,
  1261. u_agent,
  1262. time
  1263. ])
  1264. def ban_insert(name, end, why, login, blocker, type_d = None):
  1265. now_time = get_time()
  1266. band = type_d if type_d else ''
  1267. curs.execute(db_change(
  1268. "update rb set ongoing = '' where end < ? and end != '' and ongoing = '1'"
  1269. ), [now_time])
  1270. curs.execute(db_change("" + \
  1271. "select block from rb " + \
  1272. "where ((end > ? and end != '') or end = '') and block = ? and " + \
  1273. "band = ? and ongoing = '1'" + \
  1274. ""), [now_time, name, band])
  1275. if curs.fetchall():
  1276. curs.execute(db_change(
  1277. "insert into rb (block, end, today, blocker, why, band) values (?, ?, ?, ?, ?, ?)"
  1278. ), [
  1279. name,
  1280. 'release',
  1281. now_time,
  1282. blocker,
  1283. '',
  1284. band
  1285. ])
  1286. curs.execute(db_change(
  1287. "update rb set ongoing = '' where block = ? and band = ? and ongoing = '1'"
  1288. ), [name, band])
  1289. else:
  1290. login = 'O' if login != '' else ''
  1291. if end != '0':
  1292. end = int(number_check(end))
  1293. time = datetime.datetime.now()
  1294. plus = datetime.timedelta(seconds = end)
  1295. r_time = (time + plus).strftime("%Y-%m-%d %H:%M:%S")
  1296. else:
  1297. r_time = ''
  1298. curs.execute(db_change(
  1299. "insert into rb (block, end, today, blocker, why, band, ongoing, login) " + \
  1300. "values (?, ?, ?, ?, ?, ?, '1', ?)"
  1301. ), [
  1302. name,
  1303. r_time,
  1304. now_time,
  1305. blocker,
  1306. why,
  1307. band,
  1308. login
  1309. ])
  1310. conn.commit()
  1311. def rd_plus(topic_num, date, name = None, sub = None):
  1312. curs.execute(db_change("select code from rd where code = ?"), [topic_num])
  1313. if curs.fetchall():
  1314. curs.execute(db_change("update rd set date = ? where code = ?"), [date, topic_num])
  1315. else:
  1316. curs.execute(db_change(
  1317. "insert into rd (title, sub, code, date) values (?, ?, ?, ?)"
  1318. ), [name, sub, topic_num, date])
  1319. conn.commit()
  1320. def history_plus(title, data, date, ip, send, leng, t_check = '', mode = ''):
  1321. if mode == 'add':
  1322. curs.execute(db_change(
  1323. "select id from history where title = ? order by id + 0 asc limit 1"
  1324. ), [title])
  1325. id_data = curs.fetchall()
  1326. id_data = str(int(id_data[0][0]) - 1) if id_data else '0'
  1327. else:
  1328. curs.execute(db_change(
  1329. "select id from history where title = ? order by id + 0 desc limit 1"
  1330. ), [title])
  1331. id_data = curs.fetchall()
  1332. id_data = str(int(id_data[0][0]) + 1) if id_data else '1'
  1333. mode = mode if not re.search('^user:', title) else 'user'
  1334. send = re.sub(r'\(|\)|<|>', '', send)
  1335. send = send[:128] if len(send) > 128 else send
  1336. send = send + ' (' + t_check + ')' if t_check != '' else send
  1337. if mode != 'add' and mode != 'user':
  1338. curs.execute(db_change("select count(*) from rc where type = 'normal'"))
  1339. if curs.fetchall()[0][0] >= 200:
  1340. curs.execute(db_change(
  1341. "select id, title from rc where type = 'normal' order by date asc limit 1"
  1342. ))
  1343. rc_data = curs.fetchall()
  1344. if rc_data:
  1345. curs.execute(db_change(
  1346. 'delete from rc where id = ? and title = ? and type = "normal"'
  1347. ), [
  1348. rc_data[0][0],
  1349. rc_data[0][1]
  1350. ])
  1351. curs.execute(db_change(
  1352. "insert into rc (id, title, date, type) values (?, ?, ?, 'normal')"
  1353. ), [
  1354. id_data,
  1355. title,
  1356. date
  1357. ])
  1358. if mode != 'add':
  1359. curs.execute(db_change("select count(*) from rc where type = ?"), [mode])
  1360. if curs.fetchall()[0][0] >= 200:
  1361. curs.execute(db_change(
  1362. "select id, title from rc where type = ? order by date asc limit 1"
  1363. ), [mode])
  1364. rc_data = curs.fetchall()
  1365. if rc_data:
  1366. curs.execute(db_change(
  1367. 'delete from rc where id = ? and title = ? and type = ?'
  1368. ), [
  1369. rc_data[0][0],
  1370. rc_data[0][1],
  1371. mode
  1372. ])
  1373. curs.execute(db_change(
  1374. "insert into rc (id, title, date, type) values (?, ?, ?, ?)"
  1375. ), [
  1376. id_data,
  1377. title,
  1378. date,
  1379. mode
  1380. ])
  1381. curs.execute(db_change(
  1382. "insert into history (id, title, data, date, ip, send, leng, hide, type) " + \
  1383. "values (?, ?, ?, ?, ?, ?, ?, '', ?)"
  1384. ), [
  1385. id_data,
  1386. title,
  1387. data,
  1388. date,
  1389. ip,
  1390. send,
  1391. leng,
  1392. mode
  1393. ])
  1394. # Func-error
  1395. def re_error(data):
  1396. conn.commit()
  1397. if data == '/ban':
  1398. if ban_check() == 1:
  1399. end = '<div id="get_user_info"></div><script>load_user_info("' + ip_check() + '");</script>'
  1400. else:
  1401. end = '<ul class="inside_ul"><li>' + load_lang('authority_error') + '</li></ul>'
  1402. return easy_minify(flask.render_template(skin_check(),
  1403. imp = [load_lang('error'), wiki_set(1), wiki_custom(), wiki_css([0, 0])],
  1404. data = '<h2>' + load_lang('error') + '</h2>' + end,
  1405. menu = 0
  1406. )), 401
  1407. else:
  1408. num = int(number_check(data.replace('/error/', '')))
  1409. if num == 1:
  1410. data = load_lang('no_login_error')
  1411. elif num == 2:
  1412. data = load_lang('no_exist_user_error')
  1413. elif num == 3:
  1414. data = load_lang('authority_error')
  1415. elif num == 4:
  1416. data = load_lang('no_admin_block_error')
  1417. elif num == 5:
  1418. data = load_lang('skin_error')
  1419. elif num == 6:
  1420. data = load_lang('same_id_exist_error')
  1421. elif num == 7:
  1422. data = load_lang('long_id_error')
  1423. elif num == 8:
  1424. data = load_lang('id_char_error') + ' <a href="/name_filter">(' + load_lang('id_filter_list') + ')</a>'
  1425. elif num == 9:
  1426. data = load_lang('file_exist_error')
  1427. elif num == 10:
  1428. data = load_lang('password_error')
  1429. elif num == 11:
  1430. data = load_lang('topic_long_error')
  1431. elif num == 12:
  1432. data = load_lang('email_error')
  1433. elif num == 13:
  1434. data = load_lang('recaptcha_error')
  1435. elif num == 14:
  1436. data = load_lang('file_extension_error') + ' <a href="/extension_filter">(' + load_lang('extension_filter_list') + ')</a>'
  1437. elif num == 15:
  1438. data = load_lang('edit_record_error')
  1439. elif num == 16:
  1440. data = load_lang('same_file_error')
  1441. elif num == 17:
  1442. data = load_lang('file_capacity_error') + wiki_set(3)
  1443. elif num == 18:
  1444. data = load_lang('email_send_error')
  1445. elif num == 19:
  1446. data = load_lang('decument_exist_error')
  1447. elif num == 20:
  1448. data = load_lang('password_diffrent_error')
  1449. elif num == 21:
  1450. data = load_lang('edit_filter_error')
  1451. elif num == 22:
  1452. data = load_lang('file_name_error')
  1453. elif num == 23:
  1454. data = load_lang('regex_error')
  1455. elif num == 24:
  1456. curs.execute(db_change("select data from other where name = 'slow_edit'"))
  1457. slow_edit = curs.fetchall()
  1458. slow_edit = '' if not slow_edit else slow_edit[0][0]
  1459. data = load_lang('fast_edit_error') + slow_edit
  1460. elif num == 25:
  1461. data = load_lang('too_many_dec_error')
  1462. elif num == 26:
  1463. data = load_lang('application_not_found')
  1464. elif num == 27:
  1465. data = load_lang("invalid_password_error")
  1466. elif num == 28:
  1467. data = load_lang('watchlist_overflow_error')
  1468. elif num == 29:
  1469. data = load_lang('copyright_disagreed')
  1470. elif num == 30:
  1471. data = load_lang('ie_wrong_callback')
  1472. elif num == 33:
  1473. data = load_lang('restart_fail_error')
  1474. elif num == 34:
  1475. data = load_lang("update_error") + ' <a href="https://github.com/opennamu/opennamu">(Github)</a>'
  1476. elif num == 35:
  1477. data = load_lang('same_email_error')
  1478. elif num == 36:
  1479. data = load_lang('input_email_error')
  1480. else:
  1481. data = '???'
  1482. if num == 5:
  1483. if flask.request.path != '/main_skin_set':
  1484. title = load_lang('skin_set')
  1485. tool = [['main_skin_set', load_lang('main_skin_set')]]
  1486. load_skin_set = ''
  1487. else:
  1488. title = load_lang('main_skin_set')
  1489. tool = [['skin_set', load_lang('skin_set')]]
  1490. load_skin_set = '<script>main_css_skin_set();</script>'
  1491. return easy_minify(flask.render_template(skin_check(),
  1492. imp = [title, wiki_set(1), wiki_custom(), wiki_css([0, 0])],
  1493. data = '' + \
  1494. '<div id="main_skin_set">' + \
  1495. '<h2>' + load_lang('error') + '</h2>' + \
  1496. '<ul class="inside_ul">' + \
  1497. '<li>' + data + ' <a href="/main_skin_set">(' + load_lang('main_skin_set') + ')</a></li>' + \
  1498. '</ul>' + \
  1499. '</div>' + \
  1500. load_skin_set,
  1501. menu = tool
  1502. ))
  1503. else:
  1504. return easy_minify(flask.render_template(skin_check(),
  1505. imp = [load_lang('error'), wiki_set(1), wiki_custom(), wiki_css([0, 0])],
  1506. data = '' + \
  1507. '<h2>' + load_lang('error') + '</h2>' + \
  1508. '<ul class="inside_ul">' + \
  1509. '<li>' + data + '</li>' + \
  1510. '</ul>' + \
  1511. '',
  1512. menu = 0
  1513. )), 400