<?php
/**
* Module for search
*
* This file is included when a user wants to search for a string
* @package eFront
* @version 2.0
* Last change: 3/25/2008
* Changes from version 1.0 to 2.0:
* - Made new forum compatible
* - Added a wealth of new features
*/

//error_reporting(E_ALL);
//echo "<pre>";print_r($_POST);print_r($_GET);echo"</pre>";

if (isset($_POST['search_text'])) {
    $search_results_data            = array();
    $search_results_forum           = array();
    $search_results_pmsgs           = array();
    $search_results_lessons         = array();
    $search_results_current_lesson  = array();
    $lesson_names                   = array();
    $tmp_data                       = array();

    $cr             = explode(" ", $_POST['search_text']);
    $results        = EfrontSearch :: searchFull($_POST['search_text']);
    $lessons_have   = $courses_have = null;
    $currentUser    = EfrontUserFactory :: factory($_SESSION['s_login']);   //Get active lessons of this user

    if ($currentUser instanceOf EfrontLessonUser) {
        $smarty -> assign("T_CURRENT_USER", $currentUser);
        $userLessons = $currentUser -> getLessons(true);
        foreach ($userLessons as $key => $value){
            if (!$value -> lesson['active']) {
                unset($userLessons[$key]);
            } else {
                $lessons_have[] = $value->lesson['id'];
            }
        }
        $userCourses = $currentUser -> getCourses(true);
        foreach ($userCourses as $key => $value){
            if (!$value->course['active']) {
                unset($userCourses[$key]);
            } else {
                $courses_have[] = $value->course['id'];
            }
        }

    }

    $have_results = false;

    if ($currentUser -> user['user_type'] == 'administrator') {
        $results_users = EfrontSearch :: searchUsers($_POST['search_text']);
        if (sizeof($results_users)>0) {
            $search_results_data[] = $results_users;
        }
    }

    if ($results) {
        for ($i = 0; $i < sizeof($results); $i++) {
            if ($results[$i]['table_name'] == "comments") {
                $res1     = eF_getTableData("content,comments", "content.name AS name,content.id AS id,content.lessons_ID AS lessons_ID", "comments.content_ID=content.id AND comments.id=".$results[$i]['foreign_ID']);
                $type_str = _COMMENTS;
            } elseif ($results[$i]['table_name'] == "news") {
                $res1     = eF_getTableData($results[$i]['table_name'], "id,title AS name,lessons_ID", "id=".$results[$i]['foreign_ID']);
                $type_str = _ANNOUNCEMENTS;
            } elseif ($results[$i]['table_name'] == "content") {
                $res1     = eF_getTableData($results[$i]['table_name'], "id,name,lessons_ID,ctg_type, data", "id=".$results[$i]['foreign_ID']);
                $type_str = _LESSONCONTENT;
            } elseif ($results[$i]['table_name'] == "f_messages") {
                $res1     = eF_getTableData("f_messages, f_topics, f_forums", "f_forums.id as category_id, f_forums.lessons_ID, f_messages.id, f_messages.title, f_messages.f_topics_ID, f_topics.title as topic_title", "f_topics_ID = f_topics.id and f_forums.id = f_forums_ID and f_messages.id=".$results[$i]['foreign_ID']);
                $type_str = _MESSAGESATFORUM;
            } elseif ($results[$i]['table_name'] == "f_personal_messages") {
                $res1     = eF_getTableData("f_personal_messages, f_folders", "f_personal_messages.id, f_personal_messages.title, f_personal_messages.users_LOGIN, f_personal_messages.body, f_personal_messages.sender, f_personal_messages.recipient , f_folders.name, f_folders.id as folder_id", "f_personal_messages.f_folders_ID = f_folders.id and f_personal_messages.id=".$results[$i]['foreign_ID']);
                $type_str = _MESSAGESATFORUM;
            } elseif ($results[$i]['table_name'] == "lessons") {
                $res1     = eF_getTableData($results[$i]['table_name'], "id as lessons_ID,name", "id=".$results[$i]['foreign_ID']." and active=1");
                $type_str = _LESSON;
            } elseif ($results[$i]['table_name'] == "courses") {
                $res1     = eF_getTableData($results[$i]['table_name'], "id as courses_ID,name", "id=".$results[$i]['foreign_ID']." and active=1");
                $type_str = _LESSON;
            } elseif ($results[$i]['table_name'] == "f_topics") {
                $res1     = eF_getTableData("f_messages, f_topics, f_forums", "f_forums.id as category_id, f_forums.lessons_ID, f_messages.id, f_messages.title, f_messages.f_topics_ID, f_topics.title as topic_title", "f_topics_ID = f_topics.id and f_forums.id = f_forums_ID and f_topics.id=".$results[$i]['foreign_ID']);
                $type_str = _MESSAGESATFORUM;
            }

            if (sizeof($res1) > 0) {
                $results[$i]['position'] == "title" ? $position_str = _TITLE : $position_str = _TEXT;
                if ((isset($res1[0]['lessons_ID']) && in_array($res1[0]['lessons_ID'], $lessons_have) || $res1[0]['lessons_ID'] == '0') || ($results[$i]['table_name'] == "f_messages" && $_SESSION['s_type'] == "administrator") || ($results[$i]['table_name'] == "f_topics" && $_SESSION['s_type'] == "administrator")  || (isset($res1[0]['lessons_ID']) && $_SESSION['s_type'] == "administrator") || (isset($res1[0]['courses_ID']) && (in_array($res1[0]['courses_ID'], $courses_have) || $_SESSION['s_type'] == "administrator"))) {

                    $lesson = eF_getTableData("lessons", "name", "id=".$res1[0]['lessons_ID']);
                    if(strlen($lesson[0]['name'])<2) $lesson[0]['name'] = _ALL;
                    if ($results[$i]['table_name'] == 'courses') {
                        $search_results_courses[] = array('id'    => $res1[0]['courses_ID'],
                                                          'score' => sprintf("%.0f %%", $results[$i]['score'] * 100),
                                                          'name'  => $res1[0]['name']);
                    } elseif ($results[$i]['table_name'] != 'f_messages' && $results[$i]['table_name'] != 'f_topics') {
                        if($results[$i]['table_name'] == "lessons"){
                            $basic_user_type = eF_getUserBasicType(false, $res1[0]['lessons_ID']);
                                $tmp_data =  array('id'          => $res1[0]['id'],
                                                               'name'        => EfrontSearch :: highlightText($res1[0]['name'],$cr, 'resultsTitleBold'),
                                                               'table_name'  => $results[$i]['table_name'],
                                                               'lessons_ID'  => $res1[0]['lessons_ID'],
                                                               'lesson_name' => EfrontSearch :: highlightText($lesson[0]['name'],$cr, 'resultsTitleBold'),
                                                               'score'       => sprintf("%.0f %%", $results[$i]['score'] * 100),
                                                               'type'        => $type_str,
                                                               'user_type'   => $basic_user_type,
                                                               'position'    => $position_str);
                                $search_results_data[] = $tmp_data;
                                if ($res1[0]['lessons_ID'] != $_SESSION['s_lessons_ID']) {
                                    $search_results_lessons[$res1[0]['lessons_ID']][] = $tmp_data;
                                    $lesson_names[$res1[0]['lessons_ID']]['name'] = $lesson[0]['name'];
                                } else {
                                    $search_results_current_lesson[$res1[0]['lessons_ID']][] = $tmp_data;
                                    $current_lesson_name = $lesson[0]['name'];
                                }

                        }elseif ($results[$i]['table_name'] != "lessons" && eF_isDoneContent($res1[0]['id'])) {
                            $basic_user_type = eF_getUserBasicType(false, $res1[0]['lessons_ID']);
                                $tmp_data = array('id'          => $res1[0]['id'],
                                                               'name'        => EfrontSearch :: highlightText($res1[0]['name'],$cr, 'resultsTitleBold'),
                                                               'table_name'  => $results[$i]['table_name'],
                                                               'lessons_ID'  => $res1[0]['lessons_ID'],
                                                               'lesson_name' => EfrontSearch :: highlightText($lesson[0]['name'],$cr, 'resultsTitleBold'),
                                                               'ctg_type'    => $res1[0]['ctg_type'],
                                                               'content'     => EfrontSearch :: resultsTextLimit($res1[0]['data'], $cr, 'resultsText'),
                                                              // 'content'   => EfrontSearch :: highlightText(EfrontSearch :: wordLimiter(mb_substr(strip_tags($res1[0]['data']),strpos(strip_tags($res1[0]['data']), $cr[0]),2000), 40), $cr, 'resultsText'),
                                                               //'content1'  => strpos(strip_tags($res1[0]['data']), $cr[0]).EfrontSearch :: highlightText(strip_tags($res1[0]['data']), $cr, 'resultsText'),
                                                               'score'       => sprintf("%.0f %%", $results[$i]['score'] * 100),
                                                               'type'        => $type_str,
                                                               'user_type'   => $basic_user_type,
                                                               'position'    => $position_str);
                                $search_results_data[] = $tmp_data;
                                if ($res1[0]['lessons_ID'] != $_SESSION['s_lessons_ID']) {
                                    $search_results_lessons[$res1[0]['lessons_ID']][] = $tmp_data;
                                    $lesson_names[$res1[0]['lessons_ID']]['name'] = $lesson[0]['name'];
                                } else {
                                    $search_results_current_lesson[$res1[0]['lessons_ID']][] = $tmp_data;
                                    $current_lesson_name = $lesson[0]['name'];
                                }
                        }
                    } else {
                        $search_results_forum[] = array('category_id'     => $res1[0]['category_id'],
                                                        'lesson_name'     => $lesson[0]['name'],
                                                        'topic_subject'   => $res1[0]['topic_title'],
                                                        'topic_id'        => $res1[0]['f_topics_ID'],
                                                        'message_subject' => $res1[0]['title'],
                                                        'message_id'      => $res1[0]['id'],
                                                        'position'        => $position_str);
                    }
                } elseif ($results[$i]['table_name'] == 'f_personal_messages' && $_SESSION['s_login'] == $res1[0]['users_LOGIN']) {
                    $search_results_pmsgs[] = array('message_subject' => EfrontSearch :: highlightText($res1[0]['title'],$cr,'resultsTitleBold'),
                                                    'message_id'      => $res1[0]['id'],
                                                    'folder_name'     => $res1[0]['name'],
                                                    'folder_id'       => $res1[0]['folder_id'],
                                                    'body'            => EfrontSearch :: highlightText($res1[0]['body'],$cr,'resultsTitleBold'),
                                                    'recipient'       => $res1[0]['recipient'],
                                                    'sender'          => $res1[0]['sender'],
                                                    'position'        => $position_str);
                }
            }
        }
    }
    //highlight_search(word_limiter(substr($text,strpos($text, "Breathing"),1000), 20), $cr);
    //pr($search_results_lessons);
    //pr($search_results_current_lesson);
    //pr($search_results_pmsgs);
    $smarty -> assign("T_SEARCH_RESULTS_USERS", $results_users);
    $smarty -> assign("T_SEARCH_RESULTS", $search_results_data);
    $smarty -> assign("T_SEARCH_RESULTS_LESSONS", $search_results_lessons);
    $smarty -> assign("T_LESSON_NAMES", $lesson_names);
    $smarty -> assign("T_SEARCH_RESULTS_CURRENT_LESSON", $search_results_current_lesson);
    $smarty -> assign("T_CURRENT_LESSON_NAME", $current_lesson_name);
    $smarty -> assign("T_SEARCH_RESULTS_FORUM", $search_results_forum);
    $smarty -> assign("T_SEARCH_RESULTS_PERSONAL_MESSAGES", $search_results_pmsgs);
    $smarty -> assign("T_SEARCH_RESULTS_COURSES", $search_results_courses);

    if (!$search_results_data AND !$search_results_forum AND !$search_results_pmsgs AND !$search_results_courses) {
        $message = _NOSEARCHRESULTSFOUND;
        if (sizeof(explode("?", $_POST['current_location'])) > 1) {                                 //Check if there is a query string after the url, so we can append the message using a '&' or a '?'
            header("location: ".$_POST['current_location']."&message=".urlencode($message));
        } else {
            header("location: ".$_POST['current_location']."?message=".urlencode($message));
        }
    }
}
?>