]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/QnA/QnAPlugin.php
OMG I think ajax works right now
[quix0rs-gnu-social.git] / plugins / QnA / QnAPlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2011, StatusNet, Inc.
5  *
6  * Microapp plugin for Questions and Answers
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  QnA
24  * @package   StatusNet
25  * @author    Zach Copley <zach@status.net>
26  * @copyright 2011 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     // This check helps protect against security problems;
33     // your code file can't be executed directly from the web.
34     exit(1);
35 }
36
37 /**
38  * Question and Answer plugin
39  *
40  * @category  Plugin
41  * @package   StatusNet
42  * @author    Zach Copley <zach@status.net>
43  * @copyright 2011 StatusNet, Inc.
44  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
45  * @link      http://status.net/
46  */
47 class QnAPlugin extends MicroAppPlugin
48 {
49     /**
50      * Set up our tables (question and answer)
51      *
52      * @see Schema
53      * @see ColumnDef
54      *
55      * @return boolean hook value; true means continue processing, false means stop.
56      */
57     function onCheckSchema()
58     {
59         $schema = Schema::get();
60
61         $schema->ensureTable('qna_question', QnA_Question::schemaDef());
62         $schema->ensureTable('qna_answer', QnA_Answer::schemaDef());
63         $schema->ensureTable('qna_vote', QnA_Vote::schemaDef());
64
65         return true;
66     }
67
68     /**
69      * Load related modules when needed
70      *
71      * @param string $cls Name of the class to be loaded
72      *
73      * @return boolean hook value; true means continue processing, false means stop.
74      */
75     function onAutoload($cls)
76     {
77         $dir = dirname(__FILE__);
78
79         switch ($cls)
80         {
81         case 'QnanewquestionAction':
82         case 'QnanewanswerAction':
83         case 'QnashowquestionAction':
84         case 'QnaclosequestionAction':
85         case 'QnashowanswerAction':
86         case 'QnareviseanswerAction':
87         case 'QnavoteAction':
88             include_once $dir . '/actions/'
89                 . strtolower(mb_substr($cls, 0, -6)) . '.php';
90             return false;
91         case 'QnanewquestionForm':
92         case 'QnashowquestionForm':
93         case 'QnanewanswerForm':
94         case 'QnashowanswerForm':
95         case 'QnareviseanswerForm':
96         case 'QnavoteForm':
97             include_once $dir . '/lib/' . strtolower($cls).'.php';
98             break;
99         case 'QnA_Question':
100         case 'QnA_Answer':
101         case 'QnA_Vote':
102             include_once $dir . '/classes/' . $cls.'.php';
103             return false;
104             break;
105         default:
106             return true;
107         }
108     }
109
110     /**
111      * Map URLs to actions
112      *
113      * @param Net_URL_Mapper $m path-to-action mapper
114      *
115      * @return boolean hook value; true means continue processing, false means stop.
116      */
117
118     function onRouterInitialized($m)
119     {
120         $UUIDregex = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
121
122         $m->connect(
123             'main/qna/newquestion',
124             array('action' => 'qnanewquestion')
125         );
126         $m->connect(
127             'answer/qna/closequestion',
128             array('action' => 'qnaclosequestion')
129         );
130         $m->connect(
131             'main/qna/newanswer',
132             array('action' => 'qnanewanswer')
133         );
134         $m->connect(
135             'main/qna/reviseanswer',
136             array('action' => 'qnareviseanswer')
137         );
138         $m->connect(
139             'question/vote/:id',
140             array('action' => 'qnavote', 'type' => 'question'),
141             array('id' => $UUIDregex)
142         );
143         $m->connect(
144             'question/:id',
145             array('action' => 'qnashowquestion'),
146             array('id' => $UUIDregex)
147         );
148         $m->connect(
149             'answer/vote/:id',
150             array('action' => 'qnavote', 'type' => 'answer'),
151             array('id' => $UUIDregex)
152         );
153         $m->connect(
154             'answer/:id',
155             array('action' => 'qnashowanswer'),
156             array('id' => $UUIDregex)
157         );
158
159         return true;
160     }
161
162     function onPluginVersion(&$versions)
163     {
164         $versions[] = array(
165             'name'        => 'QnA',
166             'version'     => STATUSNET_VERSION,
167             'author'      => 'Zach Copley',
168             'homepage'    => 'http://status.net/wiki/Plugin:QnA',
169             'description' =>
170              _m('Question and Answers micro-app.')
171         );
172         return true;
173     }
174
175     function appTitle() {
176         return _m('Question');
177     }
178
179     function tag() {
180         return 'question';
181     }
182
183     function types() {
184         return array(
185             QnA_Question::OBJECT_TYPE,
186             QnA_Answer::OBJECT_TYPE
187         );
188     }
189
190     /**
191      * Given a parsed ActivityStreams activity, save it into a notice
192      * and other data structures.
193      *
194      * @param Activity $activity
195      * @param Profile $actor
196      * @param array $options=array()
197      *
198      * @return Notice the resulting notice
199      */
200     function saveNoticeFromActivity($activity, $actor, $options=array())
201     {
202         if (count($activity->objects) != 1) {
203             throw new Exception('Too many activity objects.');
204         }
205
206         $questionObj = $activity->objects[0];
207
208         if ($questionObj->type != QnA_Question::OBJECT_TYPE) {
209             throw new Exception('Wrong type for object.');
210         }
211
212         $notice = null;
213
214         switch ($activity->verb) {
215         case ActivityVerb::POST:
216             $notice = QnA_Question::saveNew(
217                 $actor,
218                 $questionObj->title,
219                 $questionObj->summary,
220                 $options
221             );
222             break;
223         case Answer::ObjectType:
224             $question = QnA_Question::staticGet('uri', $questionObj->id);
225             if (empty($question)) {
226                 // FIXME: save the question
227                 throw new Exception("Answer to unknown question.");
228             }
229             $notice = QnA_Answer::saveNew($actor, $question, $options);
230             break;
231         default:
232             throw new Exception("Unknown object type received by QnA Plugin");
233         }
234
235         return $notice;
236     }
237
238     /**
239      * Turn a Notice into an activity object
240      *
241      * @param Notice $notice
242      *
243      * @return ActivityObject
244      */
245
246     function activityObjectFromNotice($notice)
247     {
248         $question = null;
249
250         switch ($notice->object_type) {
251         case QnA_Question::OBJECT_TYPE:
252             $question = QnA_Question::fromNotice($notice);
253             break;
254         case QnA_Answer::OBJECT_TYPE:
255             $answer   = QnA_Answer::fromNotice($notice);
256             $question = $answer->getQuestion();
257             break;
258         }
259
260         if (empty($question)) {
261             throw new Exception("Unknown object type.");
262         }
263
264         $notice = $question->getNotice();
265
266         if (empty($notice)) {
267             throw new Exception("Unknown question notice.");
268         }
269
270         $obj = new ActivityObject();
271
272         $obj->id      = $question->uri;
273         $obj->type    = QnA_Question::OBJECT_TYPE;
274         $obj->title   = $question->title;
275         $obj->link    = $notice->bestUrl();
276
277         // XXX: probably need other stuff here
278
279         return $obj;
280     }
281
282     /**
283      * Output our CSS class for QnA notice list elements
284      *
285      * @param NoticeListItem $nli The item being shown
286      *
287      * @return boolean hook value
288      */
289
290     function onStartOpenNoticeListItemElement($nli)
291     {
292         $type = $nli->notice->object_type;
293
294         switch($type)
295         {
296         case QnA_Question::OBJECT_TYPE:
297             $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
298             $class = 'hentry notice question';
299             if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
300                 $class .= ' limited-scope';
301             }
302             $nli->out->elementStart(
303                 'li', array(
304                     'class' => $class,
305                     'id'    => 'notice-' . $id
306                 )
307             );
308             Event::handle('EndOpenNoticeListItemElement', array($nli));
309             return false;
310             break;
311         case QnA_Answer::OBJECT_TYPE:
312             $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
313
314             $cls = array('hentry', 'notice', 'answer');
315
316             $answer = QnA_Answer::staticGet('uri', $nli->notice->uri);
317
318             if (!empty($answer) && !empty($answer->best)) {
319                 $cls[] = 'best';
320             }
321
322             $nli->out->elementStart(
323                 'li',
324                 array(
325                     'class' => implode(' ', $cls),
326                     'id'    => 'notice-' . $id
327                 )
328             );
329             Event::handle('EndOpenNoticeListItemElement', array($nli));
330             return false;
331             break;
332         default:
333             return true;
334         }
335
336         return true;
337     }
338
339     /**
340      * Custom HTML output for our notices
341      *
342      * @param Notice $notice
343      * @param HTMLOutputter $out
344      */
345
346     function showNotice($notice, $out)
347     {
348         switch ($notice->object_type) {
349         case QnA_Question::OBJECT_TYPE:
350             return $this->showNoticeQuestion($notice, $out);
351         case QnA_Answer::OBJECT_TYPE:
352             return $this->showNoticeAnswer($notice, $out);
353         default:
354             // TRANS: Exception thrown when performing an unexpected action on a question.
355             // TRANS: %s is the unpexpected object type.
356             throw new Exception(
357                 sprintf(
358                     _m('Unexpected type for QnA plugin: %s.'),
359                     $notice->object_type
360                 )
361             );
362         }
363     }
364
365     function showNoticeQuestion($notice, $out)
366     {
367         $user = common_current_user();
368
369         // @hack we want regular rendering, then just add stuff after that
370         $nli = new NoticeListItem($notice, $out);
371         $nli->showNotice();
372
373         $out->elementStart('div', array('class' => 'entry-content question-description'));
374
375         $question = QnA_Question::getByNotice($notice);
376
377         if (!empty($question)) {
378
379             $form = new QnashowquestionForm($out, $question);
380             $form->show();
381
382         } else {
383             $out->text(_m('Question data is missing.'));
384         }
385         $out->elementEnd('div');
386
387         // @fixme
388         $out->elementStart('div', array('class' => 'entry-content'));
389     }
390
391
392     /**
393      * Output the HTML for this kind of object in a list
394      *
395      * @param NoticeListItem $nli The list item being shown.
396      *
397      * @return boolean hook value
398      *
399      * @fixme WARNING WARNING WARNING this closes a 'div' that is implicitly opened in BookmarkPlugin's showNotice implementation
400      */
401     function onStartShowNoticeItem($nli)
402     {
403         if (!$this->isMyNotice($nli->notice)) {
404             return true;
405         }
406
407         $out = $nli->out;
408         $notice = $nli->notice;
409
410         $this->showNotice($notice, $out);
411
412         $nli->showNoticeLink();
413         $nli->showNoticeSource();
414         $nli->showNoticeLocation();
415         $nli->showContext();
416         $nli->showRepeat();
417
418         $out->elementEnd('div');
419
420         $nli->showNoticeOptions();
421
422         if ($notice->object_type == QnA_Question::OBJECT_TYPE) {
423
424             $user = common_current_user();
425             $question = QnA_Question::getByNotice($notice);
426
427             if (!empty($user)) {
428
429                 $profile = $user->getProfile();
430                 $answer = $question->getAnswer($profile);
431
432                 // Output a placeholder input -- clicking on it will
433                 // bring up a real answer form
434
435                 // NOTE: this whole ul is just a placeholder
436                 if (empty($question->closed) && empty($answer)) {
437                     $out->elementStart('ul', 'notices qna-dummy');
438                     $out->elementStart('li', 'qna-dummy-placeholder');
439                     $out->element(
440                         'input',
441                         array(
442                             'class' => 'placeholder',
443                             'value' => _m('Your answer...')
444                         )
445                     );
446                     $out->elementEnd('li');
447                     $out->elementEnd('ul');
448                 }
449             }
450         }
451
452         return false;
453     }
454
455
456     function showNoticeAnswer($notice, $out)
457     {
458         $user = common_current_user();
459
460         $answer   = QnA_Answer::getByNotice($notice);
461         $question = $answer->getQuestion();
462
463         $nli = new NoticeListItem($notice, $out);
464         $nli->showNotice();
465
466         $out->elementStart('div', array('class' => 'entry-content answer-content'));
467
468         if (!empty($answer)) {
469             $form = new QnashowanswerForm($out, $answer);
470             $form->show();
471         } else {
472             $out->text(_m('Answer data is missing.'));
473         }
474
475         $out->elementEnd('div');
476
477         // @fixme
478         $out->elementStart('div', array('class' => 'entry-content'));
479     }
480
481     static function shorten($content, $notice)
482     {
483         $short = null;
484
485         if (Notice::contentTooLong($content)) {
486             common_debug("content too long");
487             $max = Notice::maxContent();
488             $short = mb_substr($content, 0, $max - 1);
489             $short .= sprintf(
490                 '<a href="%s" rel="more" title="%s">…</a>',
491                 $notice->uri,
492                 _m('more')
493             );
494         } else {
495             $short = $content;
496         }
497
498         return $short;
499     }
500
501     /**
502      * Form for our app
503      *
504      * @param HTMLOutputter $out
505      * @return Widget
506      */
507
508     function entryForm($out)
509     {
510         return new QnanewquestionForm($out);
511     }
512
513     /**
514      * When a notice is deleted, clean up related tables.
515      *
516      * @param Notice $notice
517      */
518
519     function deleteRelated($notice)
520     {
521         switch ($notice->object_type) {
522         case QnA_Question::OBJECT_TYPE:
523             common_log(LOG_DEBUG, "Deleting question from notice...");
524             $question = QnA_Question::fromNotice($notice);
525             $question->delete();
526             break;
527         case QnA_Answer::OBJECT_TYPE:
528             common_log(LOG_DEBUG, "Deleting answer from notice...");
529             $answer = QnA_Answer::fromNotice($notice);
530             common_log(LOG_DEBUG, "to delete: $answer->id");
531             $answer->delete();
532             break;
533         default:
534             common_log(LOG_DEBUG, "Not deleting related, wtf...");
535         }
536     }
537
538     function onEndShowScripts($action)
539     {
540         $action->script($this->path('js/qna.js'));
541         return true;
542     }
543
544     function onEndShowStyles($action)
545     {
546         $action->cssLink($this->path('css/qna.css'));
547         return true;
548     }
549 }