func.py 58 KB

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