PageRenderTime 37ms CodeModel.GetById 2ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 1ms

/phpmyfaq/ajaxservice.php

https://github.com/NHLH-ITM/phpMyFAQ-kindeditor
PHP | 850 lines | 649 code | 141 blank | 60 comment | 141 complexity | 968434af3588833e9e1c8fabf6c50ca2 MD5 | raw file
  1<?php
  2/**
  3 * The Ajax Service Layer
  4 *
  5 * PHP Version 5.4
  6 *
  7 * This Source Code Form is subject to the terms of the Mozilla Public License,
  8 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
  9 * obtain one at http://mozilla.org/MPL/2.0/.
 10 *
 11 * @category  phpMyFAQ
 12 * @package   Ajax 
 13 * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
 14 * @copyright 2010-2014 phpMyFAQ Team
 15 * @license   http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
 16 * @link      http://www.phpmyfaq.de
 17 * @since     2010-09-15
 18 */
 19
 20use Symfony\Component\HttpFoundation\JsonResponse;
 21
 22use PMF\Helper\ResponseWrapper;
 23
 24define('IS_VALID_PHPMYFAQ', null);
 25
 26//
 27// Bootstrapping
 28//
 29require 'inc/Bootstrap.php';
 30
 31$action       = PMF_Filter::filterInput(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
 32$ajaxlang     = PMF_Filter::filterInput(INPUT_POST, 'lang', FILTER_SANITIZE_STRING);
 33$code         = PMF_Filter::filterInput(INPUT_POST, 'captcha', FILTER_SANITIZE_STRING);
 34$currentToken = PMF_Filter::filterInput(INPUT_POST, 'csrf', FILTER_SANITIZE_STRING);
 35
 36$Language     = new PMF_Language($faqConfig);
 37$languageCode = $Language->setLanguage($faqConfig->get('main.languageDetection'), $faqConfig->get('main.language'));
 38require_once 'lang/language_en.php';
 39$faqConfig->setLanguage($Language);
 40
 41if (PMF_Language::isASupportedLanguage($ajaxlang)) {
 42    $languageCode = trim($ajaxlang);
 43    require_once 'lang/language_' . $languageCode . '.php';
 44} else {
 45    $languageCode = 'en';
 46    require_once 'lang/language_en.php';
 47}
 48
 49//Load plurals support for selected language
 50$plr = new PMF_Language_Plurals($PMF_LANG);
 51
 52//
 53// Initalizing static string wrapper
 54//
 55PMF_String::init($languageCode);
 56
 57// Check captcha
 58$captcha = new PMF_Captcha($faqConfig);
 59$captcha->setSessionId(
 60    PMF_Filter::filterInput(INPUT_COOKIE, PMF_Session::PMF_COOKIE_NAME_SESSIONID, FILTER_VALIDATE_INT)
 61);
 62
 63// Prepare response
 64$response = new JsonResponse;
 65$responseWrapper = new ResponseWrapper($response);
 66$responseWrapper->addCommonHeaders();
 67
 68// Set session
 69$faqsession = new PMF_Session($faqConfig);
 70$network    = new PMF_Network($faqConfig);
 71$stopwords  = new PMF_Stopwords($faqConfig);
 72
 73if (!$network->checkIp($_SERVER['REMOTE_ADDR'])) {
 74    $message = array('error' => $PMF_LANG['err_bannedIP']);
 75}
 76
 77// Check, if user is logged in
 78$user = PMF_User_CurrentUser::getFromSession($faqConfig);
 79if ($user instanceof PMF_User_CurrentUser) {
 80    $isLoggedIn = true;
 81} else {
 82    $isLoggedIn = false;
 83}
 84
 85if ('savevoting' !== $action && 'saveuserdata' !== $action && 'changepassword' !== $action &&
 86    !$captcha->checkCaptchaCode($code) && !$isLoggedIn) {
 87    $message = array('error' => $PMF_LANG['msgCaptcha']);
 88}
 89    
 90if (isset($message['error'])) {
 91    $response->setData($message)->send();
 92    exit;
 93}
 94
 95// Save user generated content
 96switch ($action) {
 97
 98    // Comments
 99    case 'savecomment':
100
101        if (!$faqConfig->get('records.allowCommentsForGuests') &&
102            $user->perm->checkRight($user->getUserId(), 'addcomment')) {
103            $message = array('error' => $PMF_LANG['err_NotAuth']);
104            break;
105        }
106
107        $faq      = new PMF_Faq($faqConfig);
108        $oComment = new PMF_Comment($faqConfig);
109        $type     = PMF_Filter::filterInput(INPUT_POST, 'type', FILTER_SANITIZE_STRING);
110        $faqid    = PMF_Filter::filterInput(INPUT_POST, 'id', FILTER_VALIDATE_INT, 0);
111        $newsid   = PMF_Filter::filterInput(INPUT_POST, 'newsid', FILTER_VALIDATE_INT);
112        $username = PMF_Filter::filterInput(INPUT_POST, 'user', FILTER_SANITIZE_STRING);
113        $mail     = PMF_Filter::filterInput(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL);
114        $comment  = PMF_Filter::filterInput(INPUT_POST, 'comment_text', FILTER_SANITIZE_SPECIAL_CHARS);
115
116        switch ($type) {
117            case 'news':
118                $id = $newsid;
119                break;
120            case 'faq';
121                $id = $faqid;
122                break;
123        }
124
125        // If e-mail address is set to optional
126        if (!$faqConfig->get('main.optionalMailAddress') && is_null($mail)) {
127            $mail = $faqConfig->get('main.administrationMail');
128        }
129
130        if (!is_null($username) && !empty($username) && !empty($mail) && !is_null($mail) && !is_null($comment) &&
131            !empty($comment) && $stopwords->checkBannedWord($comment) && !$faq->commentDisabled($id, $languageCode, $type)) {
132
133            try {
134                $faqsession->userTracking('save_comment', $id);
135            } catch (PMF_Exception $e) {
136                // @todo handle the exception
137            }
138
139            $commentData = array(
140                'record_id' => $id,
141                'type'      => $type,
142                'username'  => $username,
143                'usermail'  => $mail,
144                'comment'   => nl2br($comment),
145                'date'      => $_SERVER['REQUEST_TIME'],
146                'helped'    => '');
147
148            if ($oComment->addComment($commentData)) {
149                $emailTo = $faqConfig->get('main.administrationMail');
150                $urlToContent = '';
151                if ('faq' == $type) {
152                    $faq->getRecord($id);
153                    if ($faq->faqRecord['email'] != '') {
154                        $emailTo = $faq->faqRecord['email'];
155                    }
156                    $faqUrl = sprintf(
157                        '%s?action=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
158                        $faqConfig->get('main.referenceURL'),
159                        0,
160                        $faq->faqRecord['id'],
161                        $faq->faqRecord['lang']
162                    );
163
164                    $oLink            = new PMF_Link($faqUrl, $faqConfig);
165                    $oLink->itemTitle = $faq->faqRecord['title'];
166                    $urlToContent     = $oLink->toString();
167                } else {
168
169                    $oNews = new PMF_News($faqConfig);
170                    $news  = $oNews->getNewsEntry($id);
171                    if ($news['authorEmail'] != '') {
172                        $emailTo = $news['authorEmail'];
173                    }
174                    $link = sprintf('%s?action=news&amp;newsid=%d&amp;newslang=%s',
175                        $faqConfig->get('main.referenceURL'),
176                        $news['id'],
177                        $news['lang']
178                    );
179                    $oLink            = new PMF_Link($link, $faqConfig);
180                    $oLink->itemTitle = $news['header'];
181                    $urlToContent     = $oLink->toString();
182                }
183                
184                $commentMail =
185                    'User: ' . $commentData['username'] . ', mailto:'. $commentData['usermail'] . "\n".
186                    'New comment posted on: ' . $urlToContent .
187                    "\n\n" .
188                    wordwrap($comment, 72);
189
190                $send = [];
191                $mail = new PMF_Mail($faqConfig);
192                $mail->setReplyTo($commentData['usermail'], $commentData['username']);
193                $mail->addTo($emailTo);
194                $send[$emailTo] = 1;
195
196                // Let the admin get a copy of the message
197                if (!isset($send[$faqConfig->get('main.administrationMail')])) {
198                    $mail->addCc($faqConfig->get('main.administrationMail'));
199                    $send[$faqConfig->get('main.administrationMail')] = 1;
200                }
201
202                // Let the category owner get a copy of the message
203                $category   = new PMF_Category($faqConfig, $current_groups);
204                $categories = $category->getCategoryIdsFromArticle($faq->faqRecord['id']);
205                foreach ($categories as $_category) {
206                    $userId = $category->getCategoryUser($_category);
207                    $catUser = new PMF_User($faqConfig);
208                    $catUser->getUserById($userId);
209                    $catOwnerEmail = $catUser->getUserData('email');
210
211                    if ($catOwnerEmail != '') {
212                        if (!isset($send[$catOwnerEmail])) {
213                            $mail->addCc($catOwnerEmail);
214                            $send[$catOwnerEmail] = 1;
215                        }
216                    }
217                }
218
219                $mail->subject = '%sitename%';
220                $mail->message = strip_tags($commentMail);
221                $result = $mail->send();
222                unset($mail);
223
224                $message = array('success' => $PMF_LANG['msgCommentThanks']);
225            } else {
226                try {
227                    $faqsession->userTracking('error_save_comment', $id);
228                } catch (PMF_Exception $e) {
229                    // @todo handle the exception
230                }
231                $message = array('error' => $PMF_LANG['err_SaveComment']);
232            }
233        } else {
234            $message = array('error' => 'Please add your name, your e-mail address and a comment!');
235        }
236        break;
237
238    case 'savefaq':
239
240        if (!$faqConfig->get('records.allowNewFaqsForGuests') &&
241            $user->perm->checkRight($user->getUserId(), 'addfaq')) {
242            $message = array('error' => $PMF_LANG['err_NotAuth']);
243            break;
244        }
245
246
247        $faq         = new PMF_Faq($faqConfig);
248        $category    = new PMF_Category($faqConfig);
249        $name        = PMF_Filter::filterInput(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
250        $email       = PMF_Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
251        $faqid       = PMF_Filter::filterInput(INPUT_POST, 'faqid', FILTER_VALIDATE_INT);
252        $faqlanguage = PMF_Filter::filterInput(INPUT_POST, 'faqlanguage', FILTER_SANITIZE_STRING);
253        $question    = PMF_Filter::filterInput(INPUT_POST, 'question', FILTER_SANITIZE_STRIPPED);
254        if ($faqConfig->get('main.enableWysiwygEditorFrontend')) {
255            $answer = PMF_Filter::filterInput(INPUT_POST, 'answer', FILTER_SANITIZE_SPECIAL_CHARS);
256            $answer = html_entity_decode($answer);
257        } else {
258            $answer = PMF_Filter::filterInput(INPUT_POST, 'answer', FILTER_SANITIZE_STRIPPED);
259            $answer = nl2br($answer);
260        }
261        $translation = PMF_Filter::filterInput(INPUT_POST, 'translated_answer', FILTER_SANITIZE_STRING);
262        $contentlink = PMF_Filter::filterInput(INPUT_POST, 'contentlink', FILTER_VALIDATE_URL);
263        $keywords    = PMF_Filter::filterInput(INPUT_POST, 'keywords', FILTER_SANITIZE_STRIPPED);
264        $categories  = PMF_Filter::filterInputArray(
265            INPUT_POST,
266            array(
267                'rubrik' => array(
268                    'filter' => FILTER_VALIDATE_INT,
269                    'flags'  => FILTER_REQUIRE_ARRAY
270                )
271            )
272        );
273
274        // Check on translation
275        if (empty($answer) && !is_null($translation)) {
276            $answer = $translation;
277        }
278
279        if (!is_null($name) && !empty($name) && !is_null($email) && !empty($email) &&
280            !is_null($question) && !empty($question) && $stopwords->checkBannedWord(strip_tags($question)) &&
281            !is_null($answer) && !empty($answer) && $stopwords->checkBannedWord(strip_tags($answer)) &&
282            ((is_null($faqid) && !is_null($categories['rubrik'])) || (!is_null($faqid) && !is_null($faqlanguage) &&
283            PMF_Language::isASupportedLanguage($faqlanguage)))) {
284
285            $isNew = true;
286            if (!is_null($faqid)) {
287                $isNew = false;
288                try {
289                    $faqsession->userTracking('save_new_translation_entry', 0);
290                } catch (PMF_Exception $e) {
291                    // @todo handle the exception
292                }
293            } else {
294                try {
295                    $faqsession->userTracking('save_new_entry', 0);
296                } catch (PMF_Exception $e) {
297                    // @todo handle the exception
298                }
299            }
300
301            $isTranslation = false;
302            if (!is_null($faqlanguage)) {
303                $isTranslation = true;
304                $newLanguage   = $faqlanguage;
305            }
306
307            if (PMF_String::substr($contentlink, 7) != "") {
308                $answer = sprintf(
309                    '%s<br /><div id="newFAQContentLink">%s<a href="http://%s" target="_blank">%s</a></div>',
310                    $answer,
311                    $PMF_LANG['msgInfo'],
312                    PMF_String::substr($contentlink, 7),
313                    $contentlink
314                );
315            }
316
317            $autoActivate = $faqConfig->get('records.defaultActivation');
318
319            $newData = array(
320                'lang'          => ($isTranslation == true ? $newLanguage : $languageCode),
321                'thema'         => $question,
322                'active'        => ($autoActivate ? FAQ_SQL_ACTIVE_YES : FAQ_SQL_ACTIVE_NO),
323                'sticky'        => 0,
324                'content'       => $answer,
325                'keywords'      => $keywords,
326                'author'        => $name,
327                'email'         => $email,
328                'comment'       => FAQ_SQL_YES,
329                'date'          => date('YmdHis'),
330                'dateStart'     => '00000000000000',
331                'dateEnd'       => '99991231235959',
332                'linkState'     => '',
333                'linkDateCheck' => 0);
334
335            if ($isNew) {
336                $categories = $categories['rubrik'];
337            } else {
338                $newData['id'] = $faqid;
339                $categories    = $category->getCategoryIdsFromArticle($newData['id']);
340            }
341
342            $recordId = $faq->addRecord($newData, $isNew);
343
344            $faq->addCategoryRelations($categories, $recordId, $newData['lang']);
345
346            $openQuestionId = PMF_Filter::filterInput(INPUT_POST, 'openQuestionID', FILTER_VALIDATE_INT);
347            if ($openQuestionId) {
348                if ($faqConfig->get('records.enableDeleteQuestion')) {
349                    $faq->deleteQuestion($openQuestionId);
350                } else { // adds this faq record id to the related open question
351                    $faq->updateQuestionAnswer($openQuestionId, $recordId, $categories[0]);
352                }
353            }
354
355            // Activate visits
356            $visits = new PMF_Visits($faqConfig);
357            $visits->add($recordId, $newData['lang']);
358
359            if ($autoActivate) {
360                // Add user permissions
361                $faq->addPermission('user', $recordId, array(-1));
362                $category->addPermission('user', $categories['rubrik'], array(-1));
363                // Add group permission
364                if ($faqConfig->get('security.permLevel') != 'basic') {
365                    $faq->addPermission('group', $recordId, array(-1));
366                    $category->addPermission('group', $categories['rubrik'], array(-1));
367                }
368            }
369
370            // Let the PMF Administrator and the Category Owner to be informed by email of this new entry
371            $send = [];
372            $mail = new PMF_Mail($faqConfig);
373            $mail->setReplyTo($email, $name);
374            $mail->addTo($faqConfig->get('main.administrationMail'));
375            $send[$faqConfig->get('main.administrationMail')] = 1;
376
377            foreach ($categories as $_category) {
378
379                $userId = $category->getCategoryUser($_category);
380
381                // @todo Move this code to Category.php
382                $oUser = new PMF_User($faqConfig);
383                $oUser->getUserById($userId);
384                $catOwnerEmail = $oUser->getUserData('email');
385
386                // Avoid to send multiple emails to the same owner
387                if (!isset($send[$catOwnerEmail])) {
388                    $mail->addCc($catOwnerEmail);
389                    $send[$catOwnerEmail] = 1;
390                }
391            }
392
393            $mail->subject = '%sitename%';
394
395            // @todo let the email contains the faq article both as plain text and as HTML
396            $mail->message = html_entity_decode(
397                $PMF_LANG['msgMailCheck']) . "\n\n" .
398                $faqConfig->get('main.titleFAQ') . ": " .
399                $faqConfig->get('main.referenceURL') . '/admin/';
400            $result = $mail->send();
401            unset($mail);
402
403            $message = array(
404                'success' => ($isNew ? $PMF_LANG['msgNewContentThanks'] : $PMF_LANG['msgNewTranslationThanks'])
405            );
406
407        } else {
408            $message = array('error' => $PMF_LANG['err_SaveEntries']);
409        }
410
411        break;
412
413    case 'savequestion':
414
415        if (!$faqConfig->get('records.allowQuestionsForGuests') &&
416            $user->perm->checkRight($user->getUserId(), 'addquestion')) {
417            $message = array('error' => $PMF_LANG['err_NotAuth']);
418            break;
419        }
420
421        $faq        = new PMF_Faq($faqConfig);
422        $cat        = new PMF_Category($faqConfig);
423        $categories = $cat->getAllCategories();
424        $name       = PMF_Filter::filterInput(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
425        $email      = PMF_Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
426        $ucategory  = PMF_Filter::filterInput(INPUT_POST, 'category', FILTER_VALIDATE_INT);
427        $question   = PMF_Filter::filterInput(INPUT_POST, 'question', FILTER_SANITIZE_STRIPPED);
428        $save       = PMF_Filter::filterInput(INPUT_POST, 'save', FILTER_VALIDATE_INT, 0);
429
430        // If e-mail address is set to optional
431        if (!$faqConfig->get('main.optionalMailAddress') && is_null($email)) {
432            $email = $faqConfig->get('main.administrationMail');
433        }
434
435        if (!is_null($name) && !empty($name) && !is_null($email) && !empty($email) &&
436            !is_null($question) && !empty($question) && $stopwords->checkBannedWord(PMF_String::htmlspecialchars($question))) {
437
438            if ($faqConfig->get('records.enableVisibilityQuestions')) {
439                $visibility = 'N';
440            } else {
441                $visibility = 'Y';
442            }
443
444            $questionData = array(
445                'username'    => $name,
446                'email'       => $email,
447                'category_id' => $ucategory,
448                'question'    => $question,
449                'is_visible'  => $visibility
450            );
451
452            if (1 != $save) {
453
454                $cleanQuestion = $stopwords->clean($question);
455
456                $user            = new PMF_User_CurrentUser($faqConfig);
457                $faqSearch       = new PMF_Search($faqConfig);
458                $faqSearchResult = new PMF_Search_Resultset($user, $faq, $faqConfig);
459                $searchResult    = [];
460                $mergedResult    = [];
461
462                foreach ($cleanQuestion as $word) {
463                    $searchResult[] = $faqSearch->search($word);
464                }
465                foreach ($searchResult as $resultSet) {
466                    foreach($resultSet as $result) {
467                        $mergedResult[] = $result;
468                    }
469                }
470                $faqSearchResult->reviewResultset($mergedResult);
471
472                if (0 < $faqSearchResult->getNumberOfResults()) {
473
474                    $response = sprintf('<p>%s</p>',
475                        $plr->GetMsg('plmsgSearchAmount', $faqSearchResult->getNumberOfResults()));
476
477                    $response .= '<ul>';
478
479                    foreach ($faqSearchResult->getResultset() as $result) {
480                        $url = sprintf(
481                            '%s/index.php?action=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
482                            $faqConfig->get('main.referenceURL'),
483                            $result->category_id,
484                            $result->id,
485                            $result->lang
486                        );
487                        $oLink       = new PMF_Link($url, $faqConfig);
488                        $oLink->text = PMF_Utils::chopString($result->question, 15);
489                        $oLink->itemTitle = $result->question;
490                        $response   .= sprintf('<li>%s<br /><div class="searchpreview">%s...</div></li>',
491                            $oLink->toHtmlAnchor(),
492                            PMF_Utils::chopString(strip_tags($result->answer), 10)
493                        );
494                    }
495                    $response .= '</ul>';
496
497                    $message = array('result' => $response);
498                    
499                } else {
500
501                    $faq->addQuestion($questionData);
502
503                    $questionMail = "User: " . $questionData['username'] .
504                                ", mailto:".$questionData['email'] . "\n" . $PMF_LANG["msgCategory"] .
505                                ": " . $categories[$questionData['category_id']]["name"] . "\n\n" .
506                                wordwrap($question, 72) . "\n\n" .
507                                $faqConfig->get('main.referenceURL') . '/admin/';
508
509                    $userId = $cat->getCategoryUser($questionData['category_id']);
510                    $oUser  = new PMF_User($faqConfig);
511                    $oUser->getUserById($userId);
512
513                    $userEmail      = $oUser->getUserData('email');
514                    $mainAdminEmail = $faqConfig->get('main.administrationMail');
515
516                    $mail = new PMF_Mail($faqConfig);
517                    $mail->setReplyTo($questionData['email'], $questionData['username']);
518                    $mail->addTo($mainAdminEmail);
519                    // Let the category owner get a copy of the message
520                    if ($userEmail && $mainAdminEmail != $userEmail) {
521                        $mail->addCc($userEmail);
522                    }
523                    $mail->subject = '%sitename%';
524                    $mail->message = $questionMail;
525                    $mail->send();
526                    unset($mail);
527
528                    $message = array('success' => $PMF_LANG['msgAskThx4Mail']);
529                }
530                
531            } else {
532
533                $faq->addQuestion($questionData);
534
535                $questionMail = "User: " . $questionData['username'] .
536                                ", mailto:".$questionData['email'] . "\n" . $PMF_LANG["msgCategory"] .
537                                ": " . $categories[$questionData['category_id']]["name"] . "\n\n" .
538                                wordwrap($question, 72) . "\n\n" .
539                                $faqConfig->get('main.referenceURL') . '/admin/';
540
541                $userId = $cat->getCategoryUser($questionData['category_id']);
542                $oUser  = new PMF_User($faqConfig);
543                $oUser->getUserById($userId);
544
545                $userEmail      = $oUser->getUserData('email');
546                $mainAdminEmail = $faqConfig->get('main.administrationMail');
547
548                $mail = new PMF_Mail($faqConfig);
549                $mail->setReplyTo($questionData['email'], $questionData['username']);
550                $mail->addTo($mainAdminEmail);
551                // Let the category owner get a copy of the message
552                if ($userEmail && $mainAdminEmail != $userEmail) {
553                    $mail->addCc($userEmail);
554                }
555                $mail->subject = '%sitename%';
556                $mail->message = $questionMail;
557                $mail->send();
558                unset($mail);
559
560                $message = array('success' => $PMF_LANG['msgAskThx4Mail']);
561            }
562
563        } else {
564            $message = array('error' => $PMF_LANG['err_SaveQuestion']);
565        }
566
567        break;
568
569    case 'saveregistration':
570
571        $realname  = PMF_Filter::filterInput(INPUT_POST, 'realname', FILTER_SANITIZE_STRING);
572        $loginname = PMF_Filter::filterInput(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
573        $email     = PMF_Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
574
575        if (!is_null($loginname) && !empty($loginname) && !is_null($email) && !empty($email) &&
576            !is_null($realname) && !empty($realname)) {
577
578            $message = [];
579            $user    = new PMF_User($faqConfig);
580
581            // Create user account (login and password)
582            // Note: password be automatically generated and sent by email as soon if admin switch user to "active"
583            if (!$user->createUser($loginname, '')) {
584                $message = array('error' => $user->error());
585            } else {
586                $user->userdata->set(
587                    array('display_name', 'email'),
588                    array($realname, $email)
589                );
590                // set user status
591                $user->setStatus('blocked');
592
593                $text = sprintf(
594                    "New user has been registrated:\n\nName: %s\nLogin name: %s\n\n" .
595                    "To activate this user do please use the administration interface at %s.",
596                    $realname,
597                    $loginname,
598                    $faqConfig->get('main.referenceURL')
599                );
600
601                $mail = new PMF_Mail($faqConfig);
602                $mail->setReplyTo($email, $realname);
603                $mail->addTo($faqConfig->get('main.administrationMail'));
604                $mail->subject = PMF_Utils::resolveMarkers($PMF_LANG['emailRegSubject'], $faqConfig);
605                $mail->message = $text;
606                $result = $mail->send();
607                unset($mail);
608
609                $message = array(
610                    'success' => trim($PMF_LANG['successMessage']) .
611                                 ' ' .
612                                 trim($PMF_LANG['msgRegThankYou'])
613                );
614            }
615
616        } else {
617            $message = array('error' => $PMF_LANG['err_sendMail']);
618        }
619        break;
620
621    case 'savevoting':
622
623        $faq      = new PMF_Faq($faqConfig);
624        $type     = PMF_Filter::filterInput(INPUT_POST, 'type', FILTER_SANITIZE_STRING, 'faq');
625        $recordId = PMF_Filter::filterInput(INPUT_POST, 'id', FILTER_VALIDATE_INT, 0);
626        $vote     = PMF_Filter::filterInput(INPUT_POST, 'vote', FILTER_VALIDATE_INT);
627        $userIp   = PMF_Filter::filterVar($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
628
629        if (isset($vote) && $faq->votingCheck($recordId, $userIp) && $vote > 0 && $vote < 6) {
630
631            try {
632                $faqsession->userTracking('save_voting', $recordId);
633            } catch (PMF_Exception $e) {
634                // @todo handle the exception
635            }
636
637            $votingData = array(
638                'record_id' => $recordId,
639                'vote'      => $vote,
640                'user_ip'   => $userIp);
641
642            if (!$faq->getNumberOfVotings($recordId)) {
643                $faq->addVoting($votingData);
644            }  else {
645                $faq->updateVoting($votingData);
646            }
647            $faqRating   = new PMF_Rating($faqConfig);
648            $message = array(
649                'success' => $PMF_LANG['msgVoteThanks'],
650                'rating'  => $faqRating->getVotingResult($recordId)
651            );
652        } elseif (!$faq->votingCheck($recordId, $userIp)) {
653            try {
654                $faqsession->userTracking('error_save_voting', $recordId);
655            } catch (PMF_Exception $e) {
656                // @todo handle the exception
657            }
658            $message = array('error' => $PMF_LANG['err_VoteTooMuch']);
659
660        } else {
661            try {
662                $faqsession->userTracking('error_save_voting', $recordId);
663            } catch (PMF_Exception $e) {
664                // @todo handle the exception
665            }
666            $message = array('error' => $PMF_LANG['err_noVote']);
667        }
668
669        break;
670
671    // Send user generated mails
672    case 'sendcontact':
673
674        $name     = PMF_Filter::filterInput(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
675        $email    = PMF_Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
676        $question = PMF_Filter::filterInput(INPUT_POST, 'question', FILTER_SANITIZE_STRIPPED);
677
678        // If e-mail address is set to optional
679        if (!$faqConfig->get('main.optionalMailAddress') && is_null($email)) {
680            $email = $faqConfig->get('main.administrationMail');
681        }
682
683        if (!is_null($name) && !empty($name) && !is_null($email) && !empty($email) && !is_null($question) &&
684            !empty($question) && $stopwords->checkBannedWord(PMF_String::htmlspecialchars($question))) {
685
686            $question = sprintf(
687                "%s %s\n%s %s\n\n %s",
688                $PMF_LANG["msgNewContentName"],
689                $name,
690                $PMF_LANG["msgNewContentMail"],
691                $email,
692                $question
693            );
694
695            $mail = new PMF_Mail($faqConfig);
696            $mail->setReplyTo($email, $name);
697            $mail->addTo($faqConfig->get('main.administrationMail'));
698            $mail->subject = 'Feedback: %sitename%';;
699            $mail->message = $question;
700            $result = $mail->send();
701            unset($mail);
702
703            $message = array('success' => $PMF_LANG['msgMailContact']);
704
705        } else {
706            $message = array('error' => $PMF_LANG['err_sendMail']);
707        }
708        break;
709
710    // Send mails to friends
711    case 'sendtofriends':
712
713        $name     = PMF_Filter::filterInput(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
714        $email    = PMF_Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
715        $link     = PMF_Filter::filterInput(INPUT_POST, 'link', FILTER_VALIDATE_URL);
716        $attached = PMF_Filter::filterInput(INPUT_POST, 'message', FILTER_SANITIZE_STRIPPED);
717        $mailto   = PMF_Filter::filterInputArray(INPUT_POST,
718            array('mailto' =>
719                array('filter' => FILTER_VALIDATE_EMAIL,
720                      'flags'  => FILTER_REQUIRE_ARRAY | FILTER_NULL_ON_FAILURE
721                )
722            )
723        );
724
725        if (!is_null($name) && !empty($name) && !is_null($email) && !empty($email) &&
726            is_array($mailto) && !empty($mailto['mailto'][0]) &&
727                $stopwords->checkBannedWord(PMF_String::htmlspecialchars($attached))) {
728
729            foreach($mailto['mailto'] as $recipient) {
730                $recipient = trim(strip_tags($recipient));
731                if (!empty($recipient)) {
732                    $mail = new PMF_Mail($faqConfig);
733                    $mail->setReplyTo($email, $name);
734                    $mail->addTo($recipient);
735                    $mail->subject = $PMF_LANG["msgS2FMailSubject"].$name;
736                    $mail->message = sprintf("%s\r\n\r\n%s\r\n%s\r\n\r\n%s",
737                        $faqConfig->get('main.send2friendText'),
738                        $PMF_LANG['msgS2FText2'],
739                        $link,
740                        $attached);
741
742                    // Send the email
743                    $result = $mail->send();
744                    unset($mail);
745                    usleep(250);
746                }
747            }
748
749            $message = array('success' => $PMF_LANG['msgS2FThx']);
750        } else {
751            $message = array('error' => $PMF_LANG['err_sendMail']);
752        }
753        break;
754
755    // Save user data from UCP
756    case 'saveuserdata':
757
758        if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $currentToken) {
759            $message = array('error' => $PMF_LANG['ad_msg_noauth']);
760            break;
761        }
762
763        $userId   = PMF_Filter::filterInput(INPUT_POST, 'userid', FILTER_VALIDATE_INT);
764        $name     = PMF_Filter::filterInput(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
765        $email    = PMF_Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
766        $password = PMF_Filter::filterInput(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
767        $confirm  = PMF_Filter::filterInput(INPUT_POST, 'password_confirm', FILTER_SANITIZE_STRING);
768
769        $user = PMF_User_CurrentUser::getFromSession($faqConfig);
770
771        if ($userId !== $user->getUserId()) {
772            $message = array('error' => 'User ID mismatch!');
773            break;
774        }
775
776        if ($password !== $confirm) {
777            $message = array('error' => $PMF_LANG['ad_user_error_passwordsDontMatch']);
778            break;
779        }
780
781        $userData = array(
782            'display_name' => $name,
783            'email'        => $email);
784        $success = $user->setUserData($userData);
785
786        if (0 !== strlen($password) && 0 !== strlen($confirm)) {
787            foreach ($user->getAuthContainer() as $name => $auth) {
788                if ($auth->setReadOnly()) {
789                    continue;
790                }
791                if (!$auth->changePassword($user->getLogin(), $password)) {
792                    $message = array('error' => $auth->error());
793                    $success = false;
794                } else {
795                    $success = true;
796                }
797            }
798        }
799
800        if ($success) {
801            $message = array('success' => $PMF_LANG['ad_entry_savedsuc']);
802        } else {
803            $message = array('error' => $PMF_LANG['ad_entry_savedfail']);
804        }
805        break;
806
807    case 'changepassword':
808
809        $username = PMF_Filter::filterInput(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
810        $email    = PMF_Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
811
812        if (!is_null($username) && !is_null($email)) {
813
814            $user       = new PMF_User_CurrentUser($faqConfig);
815            $loginExist = $user->getUserByLogin($username);
816
817            if ($loginExist && ($email == $user->getUserData('email'))) {
818                $consonants = array(
819                    'b','c','d','f','g','h','j','k','l','m','n','p','r','s','t','v','w','x','y','z'
820                );
821                $vowels = array(
822                    'a','e','i','o','u'
823                );
824                $newPassword = '';
825                srand((double)microtime()*1000000);
826                for ($i = 1; $i <= 4; $i++) {
827                    $newPassword .= $consonants[rand(0,19)];
828                    $newPassword .= $vowels[rand(0,4)];
829                }
830                $user->changePassword($newPassword);
831                $text = $PMF_LANG['lostpwd_text_1']."\nUsername: ".$username."\nNew Password: ".$newPassword."\n\n".$PMF_LANG["lostpwd_text_2"];
832
833                $mail = new PMF_Mail($faqConfig);
834                $mail->addTo($email);
835                $mail->subject = '[%sitename%] Username / password request';
836                $mail->message = $text;
837                $result = $mail->send();
838                unset($mail);
839                // Trust that the email has been sent
840                $message = array('success' => $PMF_LANG['lostpwd_mail_okay']);
841            } else {
842                $message = array('error' => $PMF_LANG['lostpwd_err_1']);
843            }
844        } else {
845            $message = array('error' => $PMF_LANG['lostpwd_err_2']);
846        }
847        break;
848}
849
850$response->setData($message)->send();