search.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. module User::Search
  3. =begin
  4. search tickets
  5. result = Ticket.search(
  6. :current_user => User.find(123),
  7. :query => 'search something',
  8. :limit => 15,
  9. )
  10. returns
  11. result = [ticket_model1, ticket_model2]
  12. =end
  13. =begin
  14. search user
  15. result = User.search(
  16. :query => 'some search term'
  17. :limit => 15,
  18. :current_user => user_model,
  19. )
  20. returns
  21. result = [user_model1, user_model2, ...]
  22. =end
  23. def search(params)
  24. # get params
  25. query = params[:query]
  26. limit = params[:limit] || 10
  27. current_user = params[:current_user]
  28. # enable search only for agents and admins
  29. return [] if !current_user.is_role('Agent') && !current_user.is_role('Admin')
  30. # try search index backend
  31. if SearchIndexBackend.enabled?
  32. ids = SearchIndexBackend.search( query, limit, 'User' )
  33. users = []
  34. ids.each { |id|
  35. users.push User.lookup( :id => id )
  36. }
  37. return users
  38. end
  39. # fallback do sql query
  40. # - stip out * we already search for *query* -
  41. query.gsub! '*', ''
  42. users = User.where(
  43. '(firstname LIKE ? or lastname LIKE ? or email LIKE ?) AND id != 1', "%#{query}%", "%#{query}%", "%#{query}%",
  44. ).order('firstname').limit(limit)
  45. return users
  46. end
  47. end