summaryrefslogtreecommitdiffstats
path: root/etherpad/src/plugins/twitterStyleTags/controllers/tagBrowser.js
blob: f5e63f7abe6677c72f4ff3d7d8dca0b83ce40bde (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/**
 * Copyright 2009 RedHog, Egil Möller <egil.moller@piratpartiet.se>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import("faststatic");
import("dispatch.{Dispatcher,PrefixMatcher,forward}");

import("etherpad.utils.*");
import("etherpad.collab.server_utils");
import("etherpad.globals.*");
import("etherpad.log");
import("etherpad.pad.padusers");
import("etherpad.pro.pro_utils");
import("etherpad.helpers");
import("etherpad.pro.pro_accounts.getSessionProAccount");
import("sqlbase.sqlbase");
import("sqlbase.sqlcommon");
import("sqlbase.sqlobj");

function tagsToQuery(tags, antiTags) {
 var prefixed = [];
 for (i = 0; i < antiTags.length; i++)
  prefixed[i] = '!' + antiTags[i];
 return tags.concat(prefixed).join(',');
}

function stringFormat(text, obj) {
  var name;
  for (name in obj) {
    //iterate through the params and replace their placeholders from the original text
    text = text.replace(new RegExp('%\\(' + name + '\\)s', 'gi' ), obj[name]);
  }
  return text;
}

function getQueryToSql(tags, antiTags, querySql) {
  var queryTable;
  var queryParams;

  if (querySql == null) {
    queryTable = 'PAD_META';
    queryParams = [];
  } else {
    queryTable = querySql.sql;
    queryParams = querySql.params;
  }

  var exceptArray = [];
  var joinArray = [];
  var whereArray = [];
  var exceptParamArray = [];
  var joinParamArray = [];

  var info = new Object();
  info.queryTable = queryTable;
  info.n = 0;
  var i;

  for (i = 0; i < antiTags.length; i++) {
    tag = antiTags[i];
    exceptArray.push(
     stringFormat(
      'left join (PAD_TAG as pt%(n)s ' +
      '	      join TAG AS t%(n)s on ' +
      '	       t%(n)s.NAME = ? ' +
      '	       and t%(n)s.ID = pt%(n)s.TAG_ID) on ' +
      ' pt%(n)s.PAD_ID = p.ID ',
      info));
    whereArray.push(stringFormat('pt%(n)s.TAG_ID is null', info));
    exceptParamArray.push(tag);
    info.n += 1;
  }
  for (i = 0; i < tags.length; i++) {
    tag = tags[i];
    joinArray.push(
     stringFormat(
      'join PAD_TAG as pt%(n)s on ' +
      ' pt%(n)s.PAD_ID = p.ID ' +
      'join TAG as t%(n)s on ' +
      ' t%(n)s.ID = pt%(n)s.TAG_ID ' +
      ' and t%(n)s.NAME = ? ',
      info));
    joinParamArray.push(tag);
    info.n += 1;
  }

  info["joins"] = joinArray.join(' ');
  info["excepts"] = exceptArray.join(' ');
  info["wheres"] = whereArray.length > 0 ? ' where ' + whereArray.join(' and ') : '';
 
  return {
   sql: stringFormat(
    '(select distinct ' +
    '  p.ID ' +
    ' from ' +
    '  %(queryTable)s as p ' +
    '  %(joins)s ' +
    '  %(excepts)s ' +
    ' %(wheres)s ' +
    ') ',
    info),
   params: queryParams.concat(joinParamArray).concat(exceptParamArray)};
}

function nrSql(querySql) {
  var queryTable;
  var queryParams;

  if (querySql == null) {
    queryTable = 'PAD_META';
    queryParams = [];
  } else {
    queryTable = querySql.sql;
    queryParams = querySql.params;
  }

  var info = [];
  info['query_sql'] = queryTable
  return {
   sql: stringFormat('(select count(*) as total from %(query_sql)s as q)', info),
   params: queryParams};
}

function newTagsSql(querySql) {
  var queryTable;
  var queryParams;

  if (querySql == null) {
    queryTable = 'PAD_META';
    queryParams = [];
  } else {
    queryTable = querySql.sql;
    queryParams = querySql.params;
  }

  var info = [];
  info["query_post_table"] = queryTable;
  var queryNrSql = nrSql(querySql);
  info["query_nr_sql"] = queryNrSql.sql;
  queryNrParams = queryNrSql.params;

  return {
   sql: stringFormat('' +
    'select ' +
    ' t.NAME tagname, ' +
    ' count(tp.PAD_ID) as matches, ' +
    ' tn.total - count(tp.PAD_ID) as antimatches, ' +
    ' abs(count(tp.PAD_ID) - (tn.total / 2)) as weight ' +
    'from ' +
    ' TAG as t, ' +
    ' PAD_TAG as tp, ' +
    ' %(query_nr_sql)s as tn ' +
    'where ' +
    ' tp.TAG_ID = t.ID ' +
    ' and tp.PAD_ID in %(query_post_table)s ' +
    'group by t.NAME, tn.total ' +
    'having ' +
    ' count(tp.PAD_ID) > 0 and count(tp.PAD_ID) < tn.total ' +
    'order by ' +
    ' abs(count(tp.PAD_ID) - (tn.total / 2)) asc ' +
    'limit 10 ' +
    '', info),
   params: queryNrParams.concat(queryParams)};
}


function onRequest() {  
  var tags = new Array();
  var antiTags = new Array();

  if (request.params.query != undefined && request.params.query != '') {
    var query = request.params.query.split(',');
    for (i = 0; i < query.length; i++)
     if (query[i][0] == '!')
      antiTags.push(query[i].substring(1));
     else
      tags.push(query[i]);
  }

  var querySql = getQueryToSql(tags.concat(['public']), antiTags);
  //log.info(querySql.sql);

  var queryNewTagsSql = newTagsSql(querySql);
  var newTags = sqlobj.executeRaw(queryNewTagsSql.sql, queryNewTagsSql.params);

  var matchingPads;
  if (tags.length > 0 || antiTags.length > 0) {
    var sql = "select p.PAD_ID as ID, p.TAGS from PAD_TAG_CACHE as p, " + querySql.sql + " as q where p.PAD_ID = q.ID limit 10"
    matchingPads = sqlobj.executeRaw(sql, querySql.params);
  } else {
    matchingPads = [];
  }

  for (i = 0; i < matchingPads.length; i++) {
    matchingPads[i].TAGS = matchingPads[i].TAGS.split('#');
  }

  var isPro = pro_utils.isProDomainRequest();
  var userId = padusers.getUserId();

  helpers.addClientVars({
   userAgent: request.headers["User-Agent"],
   debugEnabled: request.params.djs,
   clientIp: request.clientAddr,
   colorPalette: COLOR_PALETTE,
   serverTimestamp: +(new Date),
   isProPad: isPro,
   userIsGuest: padusers.isGuest(userId),
   userId: userId,
  });

  var isProUser = (isPro && ! padusers.isGuest(userId));

  renderHtml("tagBrowser.ejs",
   {
    config: appjet.config,
    tagsToQuery: tagsToQuery,
    padIdToReadonly: server_utils.padIdToReadonly,
    tags: tags,
    antiTags: antiTags,
    newTags: newTags,
    matchingPads: matchingPads,
    bodyClass: 'nonpropad',
    isPro: isPro,
    isProAccountHolder: isProUser,
    account: getSessionProAccount(), // may be falsy
   }, 'twitterStyleTags');
  return true;
}