/
AnswerParser.php
465 lines (401 loc) · 14.9 KB
/
AnswerParser.php
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php
/**
*
* License, TERMS and CONDITIONS
*
* This software is licensed under the GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
* Please read the license here : http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* ATTRIBUTION REQUIRED
* 4. All web pages generated by the use of this software, or at least
* the page that lists the recent questions (usually home page) must include
* a link to the http://www.lampcms.com and text of the link must indicate that
* the website's Questions/Answers functionality is powered by lampcms.com
* An example of acceptable link would be "Powered by <a href="http://www.lampcms.com">LampCMS</a>"
* The location of the link is not important, it can be in the footer of the page
* but it must not be hidden by style attributes
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This product includes GeoLite data created by MaxMind,
* available from http://www.maxmind.com/
*
*
* @author Dmitri Snytkine <cms@lampcms.com>
* @copyright 2005-2012 (or current year) Dmitri Snytkine
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
* @link http://www.lampcms.com Lampcms.com project
* @version Release: @package_version@
*
*
*/
namespace Lampcms;
use Lampcms\String\HTMLStringParser;
/**
* Class responsible for parsing submitted
* answer object.
* It will create new record in ANSWERS collection,
* update QUESTIONS collection to increase answer count
* of parent question, update UNANSWERED_TAGS collection,
* update user's answers count
* post event onNewAnswer
*
* @author Dmitri Snytkine
*
*/
class Answerparser extends LampcmsObject
{
/**
* Object of type SubmittedAnswer
* (or any sub-class of it)
*
* @var Object SubmittedAnswer
*/
protected $SubmittedAnswer;
/**
* Object represents question for which
* we are processing the answer
*
* @var object of type Question
*/
protected $Question;
/**
* Cache object
* @var object of type \Lampcms\Cache\Cache
*/
protected $Cache;
/**
* Object of newly created answer
* an object of type Answer represents one
* answer and is a MongoDoc object
*
* @var object of type Answer (extends \Lampcms\Mongo\Doc object)
*/
protected $Answer = null;
public function __construct(Registry $Registry)
{
$this->Registry = $Registry;
/**
* Need to instantiate Cache so that it
* will listen to event and unset some keys
*/
$this->Cache = $this->Registry->Cache;
$this->Registry->registerObservers('INPUT_FILTERS');
}
/**
* Getter for SubmittedAnswer
*
* @return object of type SubmittedAnswer
*/
public function getSubmittedAnswer()
{
return $this->SubmittedAnswer;
}
/**
* Getter for $this->Answer
*
* @return mixed object of type Answer or null
* if answer object has not yet been created
*/
public function getAnswer()
{
return $this->Answer;
}
/**
* Main entry point to parse
* submitted answer
*
* @param object SubmittedAnswer $o
* @param \Lampcms\Question|null $q
*
* @internal param \Lampcms\Question $object $q represents the parent question
* this is optional, if not passed, this class will
* find parent question based on 'qid' from submitted answer
*
* @return object of type Answer representing the new
* answer (which is also MongoDoc ArrayObject)
*/
public function parse(SubmittedAnswer $o, Question $q = null)
{
$this->SubmittedAnswer = $o;
$this->Question = (null !== $q) ? $q : $this->getQuestion();
$this->makeAnswer();
$this->followQuestion();
$this->updateQuestion();
$this->updateCategory();
return $this->Answer;
}
/**
* Prepare array of data for the answer,
* then create Answer object from it and
* save. It will also fire onBeforeNewAnswer
* and onNewAnswer events
*
* @throws AnswerParserException
*
* @return object $this
*/
protected function makeAnswer()
{
/**
* Must pass array('drop-proprietary-attributes' => false)
* otherwise tidy removes rel="code"
*/
$aEditorConfig = $this->Registry->Ini->getSection('EDITOR');
$tidyConfig = ($aEditorConfig['ENABLE_CODE_EDITOR']) ? array('drop-proprietary-attributes' => false) : null;
$Body = $this->SubmittedAnswer->getBody()->tidy($tidyConfig)->safeHtml()->asHtml();
$htmlBody = HTMLStringParser::stringFactory($Body)->parseCodeTags()->linkify()->importCDATA()->setNofollow()->valueOf();
d('after HTMLStringParser: ' . $htmlBody);
$username = $this->SubmittedAnswer->getUserObject()->getDisplayName();
$uid = $this->SubmittedAnswer->getUserObject()->getUid();
$qid = $this->SubmittedAnswer->getQid();
$hash = hash('md5', \mb_strtolower($htmlBody . $qid));
/**
*
* We need to copy the title
* here too because Answer by itself does not have own
* title but we need a title when displaying links
* to answer on profile pages
*
* @todo later can also parse for smilies here
*
*/
$this->checkForDuplicate($hash);
$aData = array(
'_id' => $this->Registry->Resource->create('ANSWER'),
'i_qid' => $qid,
'i_uid' => $uid,
'i_quid' => $this->Question->getOwnerId(),
'title' => $this->Question->getTitle(),
'hash' => $hash,
'username' => $username,
'ulink' => '<a href="' . $this->SubmittedAnswer->getUserObject()->getProfileUrl() . '">' . $username . '</a>',
'avtr' => $this->SubmittedAnswer->getUserObject()->getAvatarSrc(),
'i_words' => $Body->asPlainText()->getWordsCount(),
'i_up' => 0,
'i_down' => 0,
'i_votes' => 0,
'i_cat' => $this->Question->getCategoryId(),
'b' => $htmlBody,
'i_ts' => time(),
'i_lm_ts' => time(),
'hts' => date('F j, Y g:i a T'),
'v_s' => 's',
'accepted' => false,
'ip' => $this->SubmittedAnswer->getIP(),
'app' => 'web'
);
/**
* Submitted answer object may provide
* extra elements to be added to aData array
* This is usually useful for parsing answers that
* came from external API
*
* as well as adding 'credit' div
*/
$aExtraData = $this->SubmittedAnswer->getExtraData();
d('$aExtraData: ' . print_r($aExtraData, 1));
if (!empty($aExtraData)) {
$aData = array_merge($aData, $aExtraData);
}
d('$aData: ' . print_r($aData, 1));
$this->Answer = new Answer($this->Registry, $aData);
/**
* Post onBeforeNewQuestion event
* and watch for filter either cancelling the event
* or throwing FilterException (preferred way because
* a specific error message can be passed in FilterException
* this way)
*
* In either case we throw QuestionParserException
* Controller that handles the question form should be ready
* to handle this exception and set the form error using
* message from exception. This way the error will be shown to
* the user right on the question form while question form's data
* is preserved in form.
*/
try {
$oNotification = $this->Registry->Dispatcher->post($this->Answer, 'onBeforeNewAnswer');
if ($oNotification->isNotificationCancelled()) {
throw new AnswerParserException('@@Sorry, we are unable to process your answer at this time@@');
}
} catch (FilterException $e) {
e('Got filter exception: ' . $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage() . ' ' . $e->getTraceAsString());
throw new AnswerParserException($e->getMessage());
}
/**
* Do ensureIndexes() now and not before we are sure that we even going
* to add a new question.
*/
$this->ensureIndexes();
$this->Answer->insert();
d('cp');
$this->Registry->Dispatcher->post($this->Answer, 'onNewAnswer', array('question' => $this->Question));
d('cp');
/**
* Reuse $uid since we already resolved it here,
* so no need to go through the same
* $this->SubmittedAnswer->getUserObject()->getUid() again
*/
$this->addUserTags($uid);
d('cp');
return $this;
}
/**
* Ensure indexes in all collections involved
* in storing question data
*
* @return object $this
*/
protected function ensureIndexes()
{
$ans = $this->Registry->Mongo->ANSWERS;
/**
* There is no reason to index by original timestamp
* (i_ts) because if we want to order by added time
* we can just sort by _id since value
* of _id in already in the order from oldest to newest
* (which is a primary key and alwasy indexed anyway)
*/
$ans->ensureIndex(array('i_lm_ts' => 1));
$ans->ensureIndex(array('i_votes' => 1));
$ans->ensureIndex(array('i_uid' => 1));
$ans->ensureIndex(array('i_qid' => 1));
$ans->ensureIndex(array('hash' => 1), array('unique' => true));
/**
* Index by ip address will help when we need to find
* all posts from the same ip which we need for
* flood check
*/
$ans->ensureIndex(array('ip' => 1));
return $this;
}
/**
* Detect exact same answer submitted for same
* question, regardless of who submitted the answer
*
* Even when submitted by 2 different users, duplicate answers
* are not allowed
*
* @param $hash hash of the answer text
*
* @throws AnswerParserException
* @return object $this
*/
protected function checkForDuplicate($hash)
{
$a = $this->Registry->Mongo->ANSWERS->findOne(array('hash' => $hash));
if (!empty($a)) {
throw new AnswerParserException('@@Someone (possibly you) has already added exact same answer for this question. Duplicate answers are not allowed@@');
}
return $this;
}
/**
* Increase answer count
* for question.
* Also set Last Answerer details
* and add Answerer User to list
* of Question contributors
* (this is for the dot-folders feature)
*
* The increaseAnswerCount will also update
* the last modified timestamp for question
*
* @return object $this
*/
protected function updateQuestion()
{
d('cp');
$User = $this->SubmittedAnswer->getUserObject();
d('cp');
$this->Question->updateAnswerCount();
$this->Question->addContributor($User);
$this->Question->setLatestAnswer($User, $this->Answer);
$this->Question->touch();
$this->Question->save();
return $this;
}
protected function updateCategory()
{
$Updator = new \Lampcms\Category\Updator($this->Registry->Mongo);
$Updator->addAnswer($this->Answer);
return $this;
}
/**
* Answer author will automatically
* start following this question
*
* @return object $this
*/
protected function followQuestion()
{
$FollowManager = new FollowManager($this->Registry);
$FollowManager->followQuestion($this->Registry->Viewer, $this->Question);
return $this;
}
/**
* Updates USER_TAGS collection
* Takes into account the tags from the
* Question for which the user just submitted
* an answer.
* This is run via shutdown function
*
* @param $uid
*
* @return object $this
*/
protected function addUserTags($uid)
{
d('cp');
$Tags = UserTags::factory($this->Registry);
d('cp');
$Question = $this->Question;
d('cp');
$func = function() use ($Tags, $uid, $Question)
{
$Tags->addTags($uid, $Question);
};
d('cp');
runLater($func);
d('cp');
return $this;
}
/**
* Getter for $this->Question
*
* @throws Exception
* @return object of type Question representing the Question
* for which we parsing the answer
*/
public function getQuestion()
{
if (!isset($this->Question)) {
$a = $this->Registry->Mongo->QUESTIONS->findOne(array('_id' => $this->SubmittedAnswer->getQid()));
if (empty($a)) {
e('Cannot find question with _id: ' . $this->Answer['qid']);
throw new Exception('@@Unable to find parent question for this answer@@');
}
$this->Question = new Question($this->Registry, $a);
}
return $this->Question;
}
}