application_model.rb 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. class ApplicationModel < ActiveRecord::Base
  3. include ApplicationModel::Assets
  4. include ApplicationModel::HistoryLogBase
  5. include ApplicationModel::ActivityStreamBase
  6. include ApplicationModel::SearchIndexBase
  7. self.abstract_class = true
  8. before_create :check_attributes_protected, :check_limits, :cache_delete, :fill_up_user_create
  9. before_update :check_limits, :fill_up_user_update
  10. before_destroy :destroy_dependencies
  11. after_create :cache_delete
  12. after_update :cache_delete
  13. after_touch :cache_delete
  14. after_destroy :cache_delete
  15. after_create :attachments_buffer_check
  16. after_update :attachments_buffer_check
  17. after_create :activity_stream_create
  18. after_update :activity_stream_update
  19. before_destroy :activity_stream_destroy
  20. after_create :history_create
  21. after_update :history_update
  22. after_destroy :history_destroy
  23. after_create :search_index_update
  24. after_update :search_index_update
  25. after_destroy :search_index_destroy
  26. before_destroy :recent_view_destroy
  27. # create instance accessor
  28. class << self
  29. attr_accessor :activity_stream_support_config, :history_support_config, :search_index_support_config
  30. end
  31. attr_accessor :history_changes_last_done
  32. def check_attributes_protected
  33. import_class_list = ['Ticket', 'Ticket::Article', 'History', 'Ticket::State', 'Ticket::StateType', 'Ticket::Priority', 'Group', 'User', 'Role' ]
  34. # do noting, use id as it is
  35. return if !Setting.get('system_init_done')
  36. return if Setting.get('import_mode') && import_class_list.include?(self.class.to_s)
  37. self[:id] = nil
  38. end
  39. =begin
  40. remove all not used model attributes of params
  41. result = Model.param_cleanup(params)
  42. for object creation, ignore id's
  43. result = Model.param_cleanup(params, true)
  44. returns
  45. result = params # params with valid attributes of model
  46. =end
  47. def self.param_cleanup(params, newObject = false)
  48. if params.nil?
  49. raise "No params for #{self}!"
  50. end
  51. # ignore id for new objects
  52. if newObject && params[:id]
  53. params[:id] = nil
  54. end
  55. # only use object attributes
  56. data = {}
  57. new.attributes.each {|item|
  58. next if !params.key?(item[0])
  59. data[item[0].to_sym] = params[item[0]]
  60. }
  61. # we do want to set this via database
  62. param_validation(data)
  63. end
  64. =begin
  65. set rellations of model based on params
  66. model = Model.find(1)
  67. result = model.param_set_associations(params)
  68. returns
  69. result = true|false
  70. =end
  71. def param_set_associations(params)
  72. # set relations
  73. self.class.reflect_on_all_associations.map { |assoc|
  74. real_key = assoc.name.to_s[0, assoc.name.to_s.length - 1] + '_ids'
  75. next if !params.key?(real_key.to_sym)
  76. list_of_items = params[ real_key.to_sym ]
  77. if params[ real_key.to_sym ].class != Array
  78. list_of_items = [ params[ real_key.to_sym ] ]
  79. end
  80. list = []
  81. list_of_items.each {|item|
  82. list.push(assoc.klass.find(item))
  83. }
  84. send(assoc.name.to_s + '=', list)
  85. }
  86. end
  87. =begin
  88. get rellations of model based on params
  89. model = Model.find(1)
  90. attributes = model.attributes_with_associations
  91. returns
  92. hash with attributes and association ids
  93. =end
  94. def attributes_with_associations
  95. # set relations
  96. attributes = self.attributes
  97. self.class.reflect_on_all_associations.map { |assoc|
  98. real_key = assoc.name.to_s[0, assoc.name.to_s.length - 1] + '_ids'
  99. if respond_to?(real_key)
  100. attributes[ real_key ] = send(real_key)
  101. end
  102. }
  103. attributes
  104. end
  105. =begin
  106. remove all not used params of object (per default :updated_at, :created_at, :updated_by_id and :created_by_id)
  107. result = Model.param_validation(params)
  108. returns
  109. result = params # params without listed attributes
  110. =end
  111. def self.param_validation(data)
  112. # we do want to set this via database
  113. data.delete(:updated_at)
  114. data.delete(:created_at)
  115. data.delete(:updated_by_id)
  116. data.delete(:created_by_id)
  117. if data.respond_to?('permit!')
  118. data.permit!
  119. end
  120. data
  121. end
  122. =begin
  123. set created_by_id & updated_by_id if not given based on UserInfo (current session)
  124. Used as before_create callback, no own use needed
  125. result = Model.fill_up_user_create(params)
  126. returns
  127. result = params # params with updated_by_id & created_by_id if not given based on UserInfo (current session)
  128. =end
  129. def fill_up_user_create
  130. if self.class.column_names.include? 'updated_by_id'
  131. if UserInfo.current_user_id
  132. if updated_by_id && updated_by_id != UserInfo.current_user_id
  133. logger.info "NOTICE create - self.updated_by_id is different: #{updated_by_id}/#{UserInfo.current_user_id}"
  134. end
  135. self.updated_by_id = UserInfo.current_user_id
  136. end
  137. end
  138. return if !self.class.column_names.include? 'created_by_id'
  139. return if !UserInfo.current_user_id
  140. if created_by_id && created_by_id != UserInfo.current_user_id
  141. logger.info "NOTICE create - self.created_by_id is different: #{created_by_id}/#{UserInfo.current_user_id}"
  142. end
  143. self.created_by_id = UserInfo.current_user_id
  144. end
  145. =begin
  146. set updated_by_id if not given based on UserInfo (current session)
  147. Used as before_update callback, no own use needed
  148. result = Model.fill_up_user_update(params)
  149. returns
  150. result = params # params with updated_by_id & created_by_id if not given based on UserInfo (current session)
  151. =end
  152. def fill_up_user_update
  153. return if !self.class.column_names.include? 'updated_by_id'
  154. return if !UserInfo.current_user_id
  155. self.updated_by_id = UserInfo.current_user_id
  156. end
  157. def cache_update(o)
  158. cache_delete if respond_to?('cache_delete')
  159. o.cache_delete if o.respond_to?('cache_delete')
  160. end
  161. def cache_delete
  162. # delete id caches
  163. key = "#{self.class}::#{id}"
  164. Cache.delete(key)
  165. # delete old name / login caches
  166. if changed?
  167. if changes.key?('name')
  168. name = changes['name'][0]
  169. key = "#{self.class}::#{name}"
  170. Cache.delete(key.to_s)
  171. end
  172. if changes.key?('login')
  173. name = changes['login'][0]
  174. key = "#{self.class}::#{name}"
  175. Cache.delete(key)
  176. end
  177. end
  178. # delete name caches
  179. if self[:name]
  180. key = "#{self.class}::#{self.name}"
  181. Cache.delete(key)
  182. end
  183. # delete login caches
  184. return if !self[:login]
  185. Cache.delete("#{self.class}::#{login}")
  186. end
  187. def self.cache_set(data_id, data)
  188. key = "#{self}::#{data_id}"
  189. Cache.write(key, data)
  190. end
  191. def self.cache_get(data_id)
  192. key = "#{self}::#{data_id}"
  193. Cache.get(key)
  194. end
  195. =begin
  196. generate uniq name (will check name of model and generates _1 sequenze)
  197. Used as before_update callback, no own use needed
  198. name = Model.genrate_uniq_name('some name')
  199. returns
  200. result = 'some name_X'
  201. =end
  202. def self.genrate_uniq_name(name)
  203. return name if !find_by(name: name)
  204. (1..100).each {|counter|
  205. name = "#{name}_#{counter}"
  206. exists = find_by(name: name)
  207. next if exists
  208. break
  209. }
  210. name
  211. end
  212. =begin
  213. lookup model from cache (if exists) or retrieve it from db, id, name, login or email possible
  214. result = Model.lookup(id: 123)
  215. result = Model.lookup(name: 'some name')
  216. result = Model.lookup(login: 'some login')
  217. result = Model.lookup(email: 'some login')
  218. returns
  219. result = model # with all attributes
  220. =end
  221. def self.lookup(data)
  222. if data[:id]
  223. cache = cache_get(data[:id])
  224. return cache if cache
  225. record = find_by(id: data[:id])
  226. cache_set(data[:id], record)
  227. return record
  228. elsif data[:name]
  229. cache = cache_get(data[:name])
  230. return cache if cache
  231. # do lookup with == to handle case insensitive databases
  232. records = if Rails.application.config.db_case_sensitive
  233. where('LOWER(name) = LOWER(?)', data[:name])
  234. else
  235. where(name: data[:name])
  236. end
  237. records.each {|loop_record|
  238. if loop_record.name == data[:name]
  239. cache_set(data[:name], loop_record)
  240. return loop_record
  241. end
  242. }
  243. return
  244. elsif data[:login]
  245. cache = cache_get(data[:login])
  246. return cache if cache
  247. # do lookup with == to handle case insensitive databases
  248. records = if Rails.application.config.db_case_sensitive
  249. where('LOWER(login) = LOWER(?)', data[:login])
  250. else
  251. where(login: data[:login])
  252. end
  253. records.each {|loop_record|
  254. if loop_record.login == data[:login]
  255. cache_set(data[:login], loop_record)
  256. return loop_record
  257. end
  258. }
  259. return
  260. elsif data[:email]
  261. cache = cache_get(data[:email])
  262. return cache if cache
  263. # do lookup with == to handle case insensitive databases
  264. records = if Rails.application.config.db_case_sensitive
  265. where('LOWER(email) = LOWER(?)', data[:email])
  266. else
  267. where(email: data[:email])
  268. end
  269. records.each {|loop_record|
  270. if loop_record.email == data[:email]
  271. cache_set(data[:email], loop_record)
  272. return loop_record
  273. end
  274. }
  275. return
  276. end
  277. raise 'Need name, id, login or email for lookup()'
  278. end
  279. =begin
  280. create model if not exists (check exists based on id, name, login, email or locale)
  281. result = Model.create_if_not_exists(attributes)
  282. returns
  283. result = model # with all attributes
  284. =end
  285. def self.create_if_not_exists(data)
  286. if data[:id]
  287. record = find_by(id: data[:id])
  288. return record if record
  289. elsif data[:name]
  290. # do lookup with == to handle case insensitive databases
  291. records = if Rails.application.config.db_case_sensitive
  292. where('LOWER(name) = LOWER(?)', data[:name])
  293. else
  294. where(name: data[:name])
  295. end
  296. records.each {|loop_record|
  297. return loop_record if loop_record.name == data[:name]
  298. }
  299. elsif data[:login]
  300. # do lookup with == to handle case insensitive databases
  301. records = if Rails.application.config.db_case_sensitive
  302. where('LOWER(login) = LOWER(?)', data[:login])
  303. else
  304. where(login: data[:login])
  305. end
  306. records.each {|loop_record|
  307. return loop_record if loop_record.login == data[:login]
  308. }
  309. elsif data[:email]
  310. # do lookup with == to handle case insensitive databases
  311. records = if Rails.application.config.db_case_sensitive
  312. where('LOWER(email) = LOWER(?)', data[:email])
  313. else
  314. where(email: data[:email])
  315. end
  316. records.each {|loop_record|
  317. return loop_record if loop_record.email == data[:email]
  318. }
  319. elsif data[:locale] && data[:source]
  320. # do lookup with == to handle case insensitive databases
  321. records = if Rails.application.config.db_case_sensitive
  322. where('LOWER(locale) = LOWER(?) AND LOWER(source) = LOWER(?)', data[:locale], data[:source])
  323. else
  324. where(locale: data[:locale], source: data[:source])
  325. end
  326. records.each {|loop_record|
  327. return loop_record if loop_record.source == data[:source]
  328. }
  329. end
  330. create(data)
  331. end
  332. =begin
  333. create or update model (check exists based on id, name, login, email or locale)
  334. result = Model.create_or_update(attributes)
  335. returns
  336. result = model # with all attributes
  337. =end
  338. def self.create_or_update(data)
  339. if data[:id]
  340. record = find_by(id: data[:id])
  341. if record
  342. record.update_attributes(data)
  343. return record
  344. end
  345. record = new(data)
  346. record.save
  347. return record
  348. elsif data[:name]
  349. # do lookup with == to handle case insensitive databases
  350. records = if Rails.application.config.db_case_sensitive
  351. where('LOWER(name) = LOWER(?)', data[:name])
  352. else
  353. where(name: data[:name])
  354. end
  355. records.each {|loop_record|
  356. if loop_record.name == data[:name]
  357. loop_record.update_attributes(data)
  358. return loop_record
  359. end
  360. }
  361. record = new(data)
  362. record.save
  363. return record
  364. elsif data[:login]
  365. # do lookup with == to handle case insensitive databases
  366. records = if Rails.application.config.db_case_sensitive
  367. where('LOWER(login) = LOWER(?)', data[:login])
  368. else
  369. where(login: data[:login])
  370. end
  371. records.each {|loop_record|
  372. if loop_record.login.casecmp(data[:login]).zero?
  373. loop_record.update_attributes(data)
  374. return loop_record
  375. end
  376. }
  377. record = new(data)
  378. record.save
  379. return record
  380. elsif data[:email]
  381. # do lookup with == to handle case insensitive databases
  382. records = if Rails.application.config.db_case_sensitive
  383. where('LOWER(email) = LOWER(?)', data[:email])
  384. else
  385. where(email: data[:email])
  386. end
  387. records.each {|loop_record|
  388. if loop_record.email.casecmp(data[:email]).zero?
  389. loop_record.update_attributes(data)
  390. return loop_record
  391. end
  392. }
  393. record = new(data)
  394. record.save
  395. return record
  396. elsif data[:locale]
  397. # do lookup with == to handle case insensitive databases
  398. records = if Rails.application.config.db_case_sensitive
  399. where('LOWER(locale) = LOWER(?)', data[:locale])
  400. else
  401. where(locale: data[:locale])
  402. end
  403. records.each {|loop_record|
  404. if loop_record.locale.casecmp(data[:locale]).zero?
  405. loop_record.update_attributes(data)
  406. return loop_record
  407. end
  408. }
  409. record = new(data)
  410. record.save
  411. return record
  412. else
  413. raise 'Need name, login, email or locale for create_or_update()'
  414. end
  415. end
  416. =begin
  417. activate latest change on create, update, touch and destroy
  418. class Model < ApplicationModel
  419. latest_change_support
  420. end
  421. =end
  422. def self.latest_change_support
  423. after_create :latest_change_set_from_observer
  424. after_update :latest_change_set_from_observer
  425. after_touch :latest_change_set_from_observer
  426. after_destroy :latest_change_set_from_observer_destroy
  427. end
  428. def latest_change_set_from_observer
  429. self.class.latest_change_set(updated_at)
  430. end
  431. def latest_change_set_from_observer_destroy
  432. self.class.latest_change_set(nil)
  433. end
  434. def self.latest_change_set(updated_at)
  435. key = "#{new.class.name}_latest_change"
  436. expires_in = 31_536_000 # 1 year
  437. if updated_at.nil?
  438. Cache.delete(key)
  439. else
  440. Cache.write(key, updated_at, { expires_in: expires_in })
  441. end
  442. end
  443. =begin
  444. get latest updated_at object timestamp
  445. latest_change = Ticket.latest_change
  446. returns
  447. result = timestamp
  448. =end
  449. def self.latest_change
  450. key = "#{new.class.name}_latest_change"
  451. updated_at = Cache.get(key)
  452. # if we do not have it cached, do lookup
  453. if !updated_at
  454. o = select(:updated_at).order(updated_at: :desc).limit(1).first
  455. if o
  456. updated_at = o.updated_at
  457. latest_change_set(updated_at)
  458. end
  459. end
  460. updated_at
  461. end
  462. =begin
  463. activate client notify support on create, update, touch and destroy
  464. class Model < ApplicationModel
  465. notify_clients_support
  466. end
  467. =end
  468. def self.notify_clients_support
  469. after_create :notify_clients_after_create
  470. after_update :notify_clients_after_update
  471. after_touch :notify_clients_after_touch
  472. after_destroy :notify_clients_after_destroy
  473. end
  474. =begin
  475. notify_clients_after_create after model got created
  476. used as callback in model file
  477. class OwnModel < ApplicationModel
  478. after_create :notify_clients_after_create
  479. after_update :notify_clients_after_update
  480. after_touch :notify_clients_after_touch
  481. after_destroy :notify_clients_after_destroy
  482. [...]
  483. =end
  484. def notify_clients_after_create
  485. # return if we run import mode
  486. return if Setting.get('import_mode')
  487. logger.debug "#{self.class.name}.find(#{id}) notify created " + created_at.to_s
  488. class_name = self.class.name
  489. class_name.gsub!(/::/, '')
  490. Sessions.broadcast(
  491. event: class_name + ':create',
  492. data: { id: id, updated_at: updated_at }
  493. )
  494. end
  495. =begin
  496. notify_clients_after_update after model got updated
  497. used as callback in model file
  498. class OwnModel < ApplicationModel
  499. after_create :notify_clients_after_create
  500. after_update :notify_clients_after_update
  501. after_touch :notify_clients_after_touch
  502. after_destroy :notify_clients_after_destroy
  503. [...]
  504. =end
  505. def notify_clients_after_update
  506. # return if we run import mode
  507. return if Setting.get('import_mode')
  508. logger.debug "#{self.class.name}.find(#{id}) notify UPDATED " + updated_at.to_s
  509. class_name = self.class.name
  510. class_name.gsub!(/::/, '')
  511. Sessions.broadcast(
  512. event: class_name + ':update',
  513. data: { id: id, updated_at: updated_at }
  514. )
  515. end
  516. =begin
  517. notify_clients_after_touch after model got touched
  518. used as callback in model file
  519. class OwnModel < ApplicationModel
  520. after_create :notify_clients_after_create
  521. after_update :notify_clients_after_update
  522. after_touch :notify_clients_after_touch
  523. after_destroy :notify_clients_after_destroy
  524. [...]
  525. =end
  526. def notify_clients_after_touch
  527. # return if we run import mode
  528. return if Setting.get('import_mode')
  529. logger.debug "#{self.class.name}.find(#{id}) notify TOUCH " + updated_at.to_s
  530. class_name = self.class.name
  531. class_name.gsub!(/::/, '')
  532. Sessions.broadcast(
  533. event: class_name + ':touch',
  534. data: { id: id, updated_at: updated_at }
  535. )
  536. end
  537. =begin
  538. notify_clients_after_destroy after model got destroyed
  539. used as callback in model file
  540. class OwnModel < ApplicationModel
  541. after_create :notify_clients_after_create
  542. after_update :notify_clients_after_update
  543. after_touch :notify_clients_after_touch
  544. after_destroy :notify_clients_after_destroy
  545. [...]
  546. =end
  547. def notify_clients_after_destroy
  548. # return if we run import mode
  549. return if Setting.get('import_mode')
  550. logger.debug "#{self.class.name}.find(#{id}) notify DESTOY " + updated_at.to_s
  551. class_name = self.class.name
  552. class_name.gsub!(/::/, '')
  553. Sessions.broadcast(
  554. event: class_name + ':destroy',
  555. data: { id: id, updated_at: updated_at }
  556. )
  557. end
  558. =begin
  559. serve methode to configure and enable search index support for this model
  560. class Model < ApplicationModel
  561. search_index_support
  562. ignore_attributes: {
  563. create_article_type_id: true,
  564. create_article_sender_id: true,
  565. article_count: true,
  566. },
  567. ignore_ids: [1,2,4]
  568. end
  569. =end
  570. def self.search_index_support(data = {})
  571. @search_index_support_config = data
  572. end
  573. =begin
  574. update search index, if configured - will be executed automatically
  575. model = Model.find(123)
  576. model.search_index_update
  577. =end
  578. def search_index_update
  579. config = self.class.search_index_support_config
  580. return if !config
  581. return if config[:ignore_ids] && config[:ignore_ids].include?(id)
  582. # start background job to transfer data to search index
  583. return if !SearchIndexBackend.enabled?
  584. Delayed::Job.enqueue(ApplicationModel::BackgroundJobSearchIndex.new(self.class.to_s, id))
  585. end
  586. =begin
  587. delete search index object, will be executed automatically
  588. model = Model.find(123)
  589. model.search_index_destroy
  590. =end
  591. def search_index_destroy
  592. config = self.class.search_index_support_config
  593. return if !config
  594. return if config[:ignore_ids] && config[:ignore_ids].include?(id)
  595. SearchIndexBackend.remove(self.class.to_s, id)
  596. end
  597. =begin
  598. reload search index with full data
  599. Model.search_index_reload
  600. =end
  601. def self.search_index_reload
  602. config = @search_index_support_config
  603. return if !config
  604. all_ids = select('id').all.order('created_at DESC')
  605. all_ids.each { |item_with_id|
  606. next if config[:ignore_ids] && config[:ignore_ids].include?(item_with_id.id)
  607. item = find(item_with_id.id)
  608. item.search_index_update_backend
  609. }
  610. end
  611. =begin
  612. serve methode to configure and enable activity stream support for this model
  613. class Model < ApplicationModel
  614. activity_stream_support role: 'Admin'
  615. end
  616. =end
  617. def self.activity_stream_support(data = {})
  618. @activity_stream_support_config = data
  619. end
  620. =begin
  621. log object create activity stream, if configured - will be executed automatically
  622. model = Model.find(123)
  623. model.activity_stream_create
  624. =end
  625. def activity_stream_create
  626. return if !self.class.activity_stream_support_config
  627. activity_stream_log('create', self['created_by_id'])
  628. end
  629. =begin
  630. log object update activity stream, if configured - will be executed automatically
  631. model = Model.find(123)
  632. model.activity_stream_update
  633. =end
  634. def activity_stream_update
  635. return if !self.class.activity_stream_support_config
  636. return if !changed?
  637. # default ignored attributes
  638. ignore_attributes = {
  639. created_at: true,
  640. updated_at: true,
  641. created_by_id: true,
  642. updated_by_id: true,
  643. }
  644. if self.class.activity_stream_support_config[:ignore_attributes]
  645. self.class.activity_stream_support_config[:ignore_attributes].each {|key, value|
  646. ignore_attributes[key] = value
  647. }
  648. end
  649. log = false
  650. changes.each {|key, _value|
  651. # do not log created_at and updated_at attributes
  652. next if ignore_attributes[key.to_sym] == true
  653. log = true
  654. }
  655. return if !log
  656. activity_stream_log('update', self['updated_by_id'])
  657. end
  658. =begin
  659. delete object activity stream, will be executed automatically
  660. model = Model.find(123)
  661. model.activity_stream_destroy
  662. =end
  663. def activity_stream_destroy
  664. return if !self.class.activity_stream_support_config
  665. ActivityStream.remove(self.class.to_s, id)
  666. end
  667. =begin
  668. serve methode to configure and enable history support for this model
  669. class Model < ApplicationModel
  670. history_support
  671. end
  672. class Model < ApplicationModel
  673. history_support ignore_attributes: { article_count: true }
  674. end
  675. =end
  676. def self.history_support(data = {})
  677. @history_support_config = data
  678. end
  679. =begin
  680. log object create history, if configured - will be executed automatically
  681. model = Model.find(123)
  682. model.history_create
  683. =end
  684. def history_create
  685. return if !self.class.history_support_config
  686. #logger.debug 'create ' + self.changes.inspect
  687. history_log('created', created_by_id)
  688. end
  689. =begin
  690. log object update history with all updated attributes, if configured - will be executed automatically
  691. model = Model.find(123)
  692. model.history_update
  693. =end
  694. def history_update
  695. return if !self.class.history_support_config
  696. return if !changed?
  697. # return if it's no update
  698. return if new_record?
  699. # new record also triggers update, so ignore new records
  700. changes = self.changes
  701. if history_changes_last_done
  702. history_changes_last_done.each {|key, value|
  703. if changes.key?(key) && changes[key] == value
  704. changes.delete(key)
  705. end
  706. }
  707. end
  708. self.history_changes_last_done = changes
  709. #logger.info 'updated ' + self.changes.inspect
  710. return if changes['id'] && !changes['id'][0]
  711. # default ignored attributes
  712. ignore_attributes = {
  713. created_at: true,
  714. updated_at: true,
  715. created_by_id: true,
  716. updated_by_id: true,
  717. }
  718. if self.class.history_support_config[:ignore_attributes]
  719. self.class.history_support_config[:ignore_attributes].each {|key, value|
  720. ignore_attributes[key] = value
  721. }
  722. end
  723. changes.each {|key, value|
  724. # do not log created_at and updated_at attributes
  725. next if ignore_attributes[key.to_sym] == true
  726. # get attribute name
  727. attribute_name = key.to_s
  728. if attribute_name[-3, 3] == '_id'
  729. attribute_name = attribute_name[ 0, attribute_name.length - 3 ]
  730. end
  731. value_id = []
  732. value_str = [ value[0], value[1] ]
  733. if key.to_s[-3, 3] == '_id'
  734. value_id[0] = value[0]
  735. value_id[1] = value[1]
  736. if respond_to?(attribute_name) && send(attribute_name)
  737. relation_class = send(attribute_name).class
  738. if relation_class && value_id[0]
  739. relation_model = relation_class.lookup(id: value_id[0])
  740. if relation_model
  741. if relation_model['name']
  742. value_str[0] = relation_model['name']
  743. elsif relation_model.respond_to?('fullname')
  744. value_str[0] = relation_model.send('fullname')
  745. end
  746. end
  747. end
  748. if relation_class && value_id[1]
  749. relation_model = relation_class.lookup(id: value_id[1])
  750. if relation_model
  751. if relation_model['name']
  752. value_str[1] = relation_model['name']
  753. elsif relation_model.respond_to?('fullname')
  754. value_str[1] = relation_model.send('fullname')
  755. end
  756. end
  757. end
  758. end
  759. end
  760. data = {
  761. history_attribute: attribute_name,
  762. value_from: value_str[0].to_s,
  763. value_to: value_str[1].to_s,
  764. id_from: value_id[0],
  765. id_to: value_id[1],
  766. }
  767. #logger.info "HIST NEW #{self.class.to_s}.find(#{self.id}) #{data.inspect}"
  768. history_log('updated', updated_by_id, data)
  769. }
  770. end
  771. =begin
  772. delete object history, will be executed automatically
  773. model = Model.find(123)
  774. model.history_destroy
  775. =end
  776. def history_destroy
  777. return if !self.class.history_support_config
  778. History.remove(self.class.to_s, id)
  779. end
  780. =begin
  781. get list of attachments of this object
  782. item = Model.find(123)
  783. list = item.attachments
  784. returns
  785. # array with Store model objects
  786. =end
  787. def attachments
  788. Store.list(object: self.class.to_s, o_id: id)
  789. end
  790. =begin
  791. store attachments for this object
  792. item = Model.find(123)
  793. item.attachments = [ Store-Object1, Store-Object2 ]
  794. =end
  795. def attachments=(attachments)
  796. self.attachments_buffer = attachments
  797. # update if object already exists
  798. return if !(id && id != 0)
  799. attachments_buffer_check
  800. end
  801. =begin
  802. return object and assets
  803. data = Model.full(123)
  804. data = {
  805. id: 123,
  806. assets: assets,
  807. }
  808. =end
  809. def self.full(id)
  810. object = find(id)
  811. assets = object.assets({})
  812. {
  813. id: id,
  814. assets: assets,
  815. }
  816. end
  817. =begin
  818. get assets of object list
  819. list = [
  820. {
  821. object => 'Ticket',
  822. o_id => 1,
  823. },
  824. {
  825. object => 'User',
  826. o_id => 121,
  827. },
  828. ]
  829. assets = Model.assets_of_object_list(list, assets)
  830. =end
  831. def self.assets_of_object_list(list, assets = {})
  832. list.each {|item|
  833. require item['object'].to_filename
  834. record = Kernel.const_get(item['object']).find(item['o_id'])
  835. assets = record.assets(assets)
  836. if item['created_by_id']
  837. user = User.find(item['created_by_id'])
  838. assets = user.assets(assets)
  839. end
  840. if item['updated_by_id']
  841. user = User.find(item['updated_by_id'])
  842. assets = user.assets(assets)
  843. end
  844. }
  845. assets
  846. end
  847. private
  848. def attachments_buffer
  849. @attachments_buffer_data
  850. end
  851. def attachments_buffer=(attachments)
  852. @attachments_buffer_data = attachments
  853. end
  854. def attachments_buffer_check
  855. # do nothing if no attachment exists
  856. return 1 if attachments_buffer.nil?
  857. # store attachments
  858. article_store = []
  859. attachments_buffer.each do |attachment|
  860. article_store.push Store.add(
  861. object: self.class.to_s,
  862. o_id: id,
  863. data: attachment.content,
  864. filename: attachment.filename,
  865. preferences: attachment.preferences,
  866. created_by_id: created_by_id,
  867. )
  868. end
  869. attachments_buffer = nil
  870. end
  871. =begin
  872. delete object recent viewed list, will be executed automatically
  873. model = Model.find(123)
  874. model.recent_view_destroy
  875. =end
  876. def recent_view_destroy
  877. RecentView.log_destroy(self.class.to_s, id)
  878. end
  879. =begin
  880. check string/varchar size and cut them if needed
  881. =end
  882. def check_limits
  883. attributes.each {|attribute|
  884. next if !self[ attribute[0] ]
  885. next if self[ attribute[0] ].class != String
  886. next if self[ attribute[0] ].empty?
  887. column = self.class.columns_hash[ attribute[0] ]
  888. next if !column
  889. limit = column.limit
  890. if column && limit
  891. current_length = attribute[1].to_s.length
  892. if limit < current_length
  893. logger.warn "WARNING: cut string because of database length #{self.class}.#{attribute[0]}(#{limit} but is #{current_length}:#{attribute[1]})"
  894. self[ attribute[0] ] = attribute[1][ 0, limit ]
  895. end
  896. end
  897. # strip 4 bytes utf8 chars if needed
  898. if column && self[ attribute[0] ]
  899. self[attribute[0]] = self[ attribute[0] ].utf8_to_3bytesutf8
  900. end
  901. }
  902. end
  903. =begin
  904. destory object dependencies, will be executed automatically
  905. =end
  906. def destroy_dependencies
  907. end
  908. end