]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/QnA/QnAPlugin.php
Update translator documentation.
[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              // TRANS: Plugin description.
171              _m('Question and Answers micro-app.')
172         );
173         return true;
174     }
175
176     function appTitle() {
177         // TRANS: Application title.
178         return _m('TITLE','Question');
179     }
180
181     function tag() {
182         return 'question';
183     }
184
185     function types() {
186         return array(
187             QnA_Question::OBJECT_TYPE,
188             QnA_Answer::OBJECT_TYPE
189         );
190     }
191
192     /**
193      * Given a parsed ActivityStreams activity, save it into a notice
194      * and other data structures.
195      *
196      * @param Activity $activity
197      * @param Profile $actor
198      * @param array $options=array()
199      *
200      * @return Notice the resulting notice
201      */
202     function saveNoticeFromActivity($activity, $actor, $options=array())
203     {
204         if (count($activity->objects) != 1) {
205             // TRANS: Exception thrown when there are too many activity objects.
206             throw new Exception(_m('Too many activity objects.'));
207         }
208
209         $questionObj = $activity->objects[0];
210
211         if ($questionObj->type != QnA_Question::OBJECT_TYPE) {
212             // TRANS: Exception thrown when an incorrect object type is encountered.
213             throw new Exception(_m('Wrong type for object.'));
214         }
215
216         $notice = null;
217
218         switch ($activity->verb) {
219         case ActivityVerb::POST:
220             $notice = QnA_Question::saveNew(
221                 $actor,
222                 $questionObj->title,
223                 $questionObj->summary,
224                 $options
225             );
226             break;
227         case Answer::ObjectType:
228             $question = QnA_Question::staticGet('uri', $questionObj->id);
229             if (empty($question)) {
230                 // FIXME: save the question
231                 // TRANS: Exception thrown when answering a non-existing question.
232                 throw new Exception(_m('Answer to unknown question.'));
233             }
234             $notice = QnA_Answer::saveNew($actor, $question, $options);
235             break;
236         default:
237             // TRANS: Exception thrown when an object type is encountered that cannot be handled.
238             throw new Exception(_m('Unknown object type.'));
239         }
240
241         return $notice;
242     }
243
244     /**
245      * Turn a Notice into an activity object
246      *
247      * @param Notice $notice
248      *
249      * @return ActivityObject
250      */
251
252     function activityObjectFromNotice($notice)
253     {
254         $question = null;
255
256         switch ($notice->object_type) {
257         case QnA_Question::OBJECT_TYPE:
258             $question = QnA_Question::fromNotice($notice);
259             break;
260         case QnA_Answer::OBJECT_TYPE:
261             $answer   = QnA_Answer::fromNotice($notice);
262             $question = $answer->getQuestion();
263             break;
264         }
265
266         if (empty($question)) {
267             // TRANS: Exception thrown when an object type is encountered that cannot be handled.
268             throw new Exception(_m('Unknown object type.'));
269         }
270
271         $notice = $question->getNotice();
272
273         if (empty($notice)) {
274             // TRANS: Exception thrown when requesting a non-existing question notice.
275             throw new Exception(_m('Unknown question notice.'));
276         }
277
278         $obj = new ActivityObject();
279
280         $obj->id      = $question->uri;
281         $obj->type    = QnA_Question::OBJECT_TYPE;
282         $obj->title   = $question->title;
283         $obj->link    = $notice->bestUrl();
284
285         // XXX: probably need other stuff here
286
287         return $obj;
288     }
289
290     /**
291      * Output our CSS class for QnA notice list elements
292      *
293      * @param NoticeListItem $nli The item being shown
294      *
295      * @return boolean hook value
296      */
297
298     function onStartOpenNoticeListItemElement($nli)
299     {
300         $type = $nli->notice->object_type;
301
302         switch($type)
303         {
304         case QnA_Question::OBJECT_TYPE:
305             $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
306             $class = 'hentry notice question';
307             if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
308                 $class .= ' limited-scope';
309             }
310
311             $question = QnA_Question::staticGet('uri', $nli->notice->uri);
312
313             if (!empty($question->closed)) {
314                 $class .= ' closed';
315             }
316
317             $nli->out->elementStart(
318                 'li', array(
319                     'class' => $class,
320                     'id'    => 'notice-' . $id
321                 )
322             );
323             Event::handle('EndOpenNoticeListItemElement', array($nli));
324             return false;
325             break;
326         case QnA_Answer::OBJECT_TYPE:
327             $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
328
329             $cls = array('hentry', 'notice', 'answer');
330
331             $answer = QnA_Answer::staticGet('uri', $nli->notice->uri);
332
333             if (!empty($answer) && !empty($answer->best)) {
334                 $cls[] = 'best';
335             }
336
337             $nli->out->elementStart(
338                 'li',
339                 array(
340                     'class' => implode(' ', $cls),
341                     'id'    => 'notice-' . $id
342                 )
343             );
344             Event::handle('EndOpenNoticeListItemElement', array($nli));
345             return false;
346             break;
347         default:
348             return true;
349         }
350
351         return true;
352     }
353
354     /**
355      * Custom HTML output for our notices
356      *
357      * @param Notice $notice
358      * @param HTMLOutputter $out
359      */
360     function showNotice($notice, $out)
361     {
362         switch ($notice->object_type) {
363         case QnA_Question::OBJECT_TYPE:
364             return $this->showNoticeQuestion($notice, $out);
365         case QnA_Answer::OBJECT_TYPE:
366             return $this->showNoticeAnswer($notice, $out);
367         default:
368             throw new Exception(
369                 // TRANS: Exception thrown when performing an unexpected action on a question.
370                 // TRANS: %s is the unpexpected object type.
371                 sprintf(_m('Unexpected type for QnA plugin: %s.'),
372                         $notice->object_type
373                 )
374             );
375         }
376     }
377
378     function showNoticeQuestion($notice, $out)
379     {
380         $user = common_current_user();
381
382         // @hack we want regular rendering, then just add stuff after that
383         $nli = new NoticeListItem($notice, $out);
384         $nli->showNotice();
385
386         $out->elementStart('div', array('class' => 'entry-content question-description'));
387
388         $question = QnA_Question::getByNotice($notice);
389
390         if (!empty($question)) {
391
392             $form = new QnashowquestionForm($out, $question);
393             $form->show();
394
395         } else {
396             // TRANS: Error message displayed when question data is not present.
397             $out->text(_m('Question data is missing.'));
398         }
399         $out->elementEnd('div');
400
401         // @fixme
402         $out->elementStart('div', array('class' => 'entry-content'));
403     }
404
405     /**
406      * Output the HTML for this kind of object in a list
407      *
408      * @param NoticeListItem $nli The list item being shown.
409      *
410      * @return boolean hook value
411      *
412      * @todo FIXME: WARNING WARNING WARNING this closes a 'div' that is implicitly opened in BookmarkPlugin's showNotice implementation
413      */
414     function onStartShowNoticeItem($nli)
415     {
416         if (!$this->isMyNotice($nli->notice)) {
417             return true;
418         }
419
420         $out = $nli->out;
421         $notice = $nli->notice;
422
423         $this->showNotice($notice, $out);
424
425         $nli->showNoticeLink();
426         $nli->showNoticeSource();
427         $nli->showNoticeLocation();
428         $nli->showContext();
429         $nli->showRepeat();
430
431         $out->elementEnd('div');
432
433         $nli->showNoticeOptions();
434
435         if ($notice->object_type == QnA_Question::OBJECT_TYPE) {
436             $user = common_current_user();
437             $question = QnA_Question::getByNotice($notice);
438
439             if (!empty($user)) {
440                 $profile = $user->getProfile();
441                 $answer = $question->getAnswer($profile);
442
443                 // Output a placeholder input -- clicking on it will
444                 // bring up a real answer form
445
446                 // NOTE: this whole ul is just a placeholder
447                 if (empty($question->closed) && empty($answer)) {
448                     $out->elementStart('ul', 'notices qna-dummy');
449                     $out->elementStart('li', 'qna-dummy-placeholder');
450                     $out->element(
451                         'input',
452                         array(
453                             'class' => 'placeholder',
454                             // TRANS: Placeholder value for a possible answer to a question
455                             // TRANS: by the logged in user.
456                             'value' => _m('Your answer...')
457                         )
458                     );
459                     $out->elementEnd('li');
460                     $out->elementEnd('ul');
461                 }
462             }
463         }
464
465         return false;
466     }
467
468     function showNoticeAnswer($notice, $out)
469     {
470         $user = common_current_user();
471
472         $answer   = QnA_Answer::getByNotice($notice);
473         $question = $answer->getQuestion();
474
475         $nli = new NoticeListItem($notice, $out);
476         $nli->showNotice();
477
478         $out->elementStart('div', array('class' => 'entry-content answer-content'));
479
480         if (!empty($answer)) {
481             $form = new QnashowanswerForm($out, $answer);
482             $form->show();
483         } else {
484             // TRANS: Error message displayed when answer data is not present.
485             $out->text(_m('Answer data is missing.'));
486         }
487
488         $out->elementEnd('div');
489
490         // @todo FIXME
491         $out->elementStart('div', array('class' => 'entry-content'));
492     }
493
494     static function shorten($content, $notice)
495     {
496         $short = null;
497
498         if (Notice::contentTooLong($content)) {
499             common_debug("content too long");
500             $max = Notice::maxContent();
501             // TRANS: Link description for link to full notice text if it is longer than
502             // TRANS: what will be dispplayed.
503             $ellipsis = _m('…');
504             $short = mb_substr($content, 0, $max - 1);
505             $short .= sprintf('<a href="%1$s" rel="more" title="%2$s">%3$s</a>',
506                               $notice->uri,
507                               // TRANS: Title for link that is an ellipsis in English.
508                               _m('more...'),
509                               $ellipsis);
510         } else {
511             $short = $content;
512         }
513
514         return $short;
515     }
516
517     /**
518      * Form for our app
519      *
520      * @param HTMLOutputter $out
521      * @return Widget
522      */
523     function entryForm($out)
524     {
525         return new QnanewquestionForm($out);
526     }
527
528     /**
529      * When a notice is deleted, clean up related tables.
530      *
531      * @param Notice $notice
532      */
533     function deleteRelated($notice)
534     {
535         switch ($notice->object_type) {
536         case QnA_Question::OBJECT_TYPE:
537             common_log(LOG_DEBUG, "Deleting question from notice...");
538             $question = QnA_Question::fromNotice($notice);
539             $question->delete();
540             break;
541         case QnA_Answer::OBJECT_TYPE:
542             common_log(LOG_DEBUG, "Deleting answer from notice...");
543             $answer = QnA_Answer::fromNotice($notice);
544             common_log(LOG_DEBUG, "to delete: $answer->id");
545             $answer->delete();
546             break;
547         default:
548             common_log(LOG_DEBUG, "Not deleting related, wtf...");
549         }
550     }
551
552     function onEndShowScripts($action)
553     {
554         $action->script($this->path('js/qna.js'));
555         return true;
556     }
557
558     function onEndShowStyles($action)
559     {
560         $action->cssLink($this->path('css/qna.css'));
561         return true;
562     }
563 }