<?php
session_cache_limiter('none');
session_start();

$path = "../libraries/";

/** Configuration file.*/
include_once $path."configuration.php";

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past

$message        = isset($_GET['message'])      ? $_GET['message']      : $message;
$message_type   = isset($_GET['message_type']) ? $_GET['message_type'] : $message_type;

$loadScripts = array('EfrontScripts', 'scriptaculous/prototype', 'scriptaculous/scriptaculous', 'scriptaculous/effects');
$smarty -> assign("T_CONFIGURATION", $configuration);           //Assign global configuration values to smarty
$smarty -> assign("T_CURRENCYSYMBOLS", $CURRENCYSYMBOLS);  

if (!preg_match('/index.php/i', $_SERVER['PHP_SELF'])) {
    if ($configuration['lessons_directory'] == '3') {
        $message        = _VIEWDIRECTORYDISABLED;
        $message_type   = 'failure';
        if (!eF_checkUser($_SESSION['s_login'], $_SESSION['s_password'])) {                                       //Any logged-in user may proceed
            header('location: index.php?message='.$message.'&message_type='.$message_type);     
        } else {
            header('location: student.php?message='.$message.'&message_type='.$message_type);
        }
        exit();
    }
}

//If there is a valid session, try to instantiate current user
if (isset($_SESSION['s_login']) && $_SESSION['s_password']) {
    try {
        $currentUser = EfrontUserFactory :: factory($_SESSION['s_login']);
        $smarty -> assign("T_CURRENT_USER", $currentUser);
        if ($currentUser instanceOf EfrontLessonUser) {
            $userLessons = $currentUser -> getLessons();
            $userCourses = $currentUser -> getCourses();
        } else {
            $userLessons = $userCourses = null;
        }
    } catch (EfrontException $e) {
        $message = $e -> getMessage().' ('.$e -> getCode().')';
    }
} else {
    try {
        $logoFile = new EfrontFile($configuration['logo']);
        $smarty -> assign("T_LOGO", 'logo/'.$logoFile['physical_name']);
    } catch (EfrontFileException $e) {
        $smarty -> assign("T_LOGO", "logo.png");
    }   
}
$announcements = eF_getNews();
$smarty -> assign("T_NEWS", $announcements);
$smarty -> assign("T_TIMESTAMP", time());
$smarty -> assign("T_LOGOLINK", $configuration[G_ROOTPATH]);
/**
 *
 * MAIN PART
 *
 */

$fct        = eF_checkParameter($_GET['fct'], 'string') && isset($_GET['fct'])          ? $_GET['fct']          : null;
$direction  = eF_checkParameter($_GET['direction'], 'id') && isset($_GET['direction'])  ? $_GET['direction']    : null;
$course     = eF_checkParameter($_GET['course'], 'id') && isset($_GET['course'])        ? $_GET['course']       : null;
$lesson     = eF_checkParameter($_GET['lesson'], 'id') && isset($_GET['lesson'])        ? $_GET['lesson']       : null;
$id         = eF_checkParameter($_GET['id'], 'id') && isset($_GET['id'])                ? $_GET['id']           : null;

switch($fct) {
    case 'cartPreview':
        
        if (!eF_checkUser($_SESSION['s_login'], $_SESSION['s_password'])) {                                       //Any logged-in user may proceed
            $message        = _LOGINFIRST;
            $message_type   = 'failure';
            header('location: index.php?message='.$message.'&message_type='.$message_type);     
        }
        
        $smarty -> assign("T_SESSION_DATA", sizeof($_SESSION['cart']['lesson']));
        
        if (sizeof($_SESSION['cart']['lesson']) > 0) {
            $p          = new paypal_class;                             //Load paypal class
            $pconfig    = $p->configuration();                          //Load paypal configuration

            $finalPrice = $lessonsNames = $lessonsIds = null;           //Initiates some variables
        
            foreach ($_SESSION['cart']['lesson'] as $key => $value) {   //Calculate paypals variables
                $lessonsNames   .= $value['name'].", ";
                $lessonsIds     .= $value['id'].", ";
                $finalPrice     += $value['price'];
                
            }

            $lessonsNames   = mb_substr($lessonsNames, 0, -2);  
            $lessonsIds     = mb_substr($lessonsIds, 0, -2);

            $config_data = eF_getTableData("paypal_configuration", "*", "");
            if (($finalPrice == 0) || (sizeof($config_data) > 0 && strlen($config_data[0]['paypalbusiness']) > 4)) {
                if (($finalPrice == 0) || $pconfig) {
                    $transactionID = date('ymdHms') . substr(md5(G_MD5KEY . $_SESSION['s_login']), 0, 4);

                    //$p -> paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; //DEMO - MUST BE DELETED
                    if ($finalPrice > 0) {
                        $form = new HTML_QuickForm("order_lessons_form", "post", $p -> paypal_url, 'onSubmit="document.savedata.submit();"', null, true);
                        $form -> addElement('hidden', 'business', $config_data[0]['paypalbusiness']);
                        $form -> addElement('hidden', 'return', G_SERVERNAME."studentpage.php?message="._PAYPALORDERSUCCESS."&message_type=success");
                        $form -> addElement('hidden', 'cancel_return', G_SERVERNAME."studentpage.php?message="._PAYPALORDERFAILURE."&message_type=failure");
                        $form -> addElement('hidden', 'notify_url', G_SERVERNAME."ipn.php");
                        $form -> addElement('hidden', 'item_name', $lessonsNames);
                        $form -> addElement('hidden', 'rm', '2');       // Return method = POST         
                        $form -> addElement('hidden', 'cmd', '_xclick');
                        $form -> addElement('hidden', 'currency_code', $configuration['currency']);
                        $form -> addElement('hidden', 'item_number', $lessonsIds);
                        $form -> addElement('hidden', 'amount', $finalPrice);
                        $form -> addElement('hidden', 'custom', $transactionID);
                        $form -> addElement('hidden', 'charset', 'utf-8');
                        $form -> addElement('submit', 'order', _PAYPALPAYNOW, 'class = "flatButton" onclick="document.savedata.submit();"');

                        //form to save data in the database
                        $formdata = new HTML_QuickForm("savedata", "post", "directory.php?fct=saveOrder", "", null, true);
                        $formdata -> addElement('hidden', 'business', $config_data[0]['paypalbusiness']);
                        $formdata -> addElement('hidden', 'item_name', $lessonsNames);
                        $formdata -> addElement('hidden', 'amount', $finalPrice);
                        $formdata -> addElement('hidden', 'item_number', $lessonsIds);
                        $formdata -> addElement('hidden', 'status', 'submitted');
                        $formdata -> addElement('hidden', 'currency_code', $configuration['currency']);
                        $formdata -> addElement('hidden', 'custom', $transactionID);

                        $rendererdata =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
                        $formdata -> accept($rendererdata);

                        $smarty -> assign('T_ORDER_LESSONS_FORMDATA', $rendererdata -> toArray());
                    } else {
                        $form = new HTML_QuickForm("order_lessons_form", "post", 'directory.php?fct=registerFree', '', null, true);
                        $form -> addElement('hidden', 'item_name', $lessonsNames);
                        $form -> addElement('hidden', 'item_number', $lessonsIds);
                        $form -> addElement('submit', 'order', _FREEREGISTRATION, 'class = "flatButton"');                  
                    }
                    $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
                    $form -> accept($renderer);

                    $smarty -> assign('T_ORDER_LESSONS_FORM', $renderer -> toArray());
                    $smarty -> assign("T_LESSONS_FINAL_PRICE", $finalPrice);
                    $smarty -> assign("T_LESSONS_DATA", $_SESSION['cart']['lesson']);
                } else {
                    $message        = _PAYPALNOCONFIGURATION;
                    $message_type   = 'failure';
                    header('location: directory.php?message='.$message.'&message_type='.$message_type);     
                }   
            } else {
                $message        = _PAYPALNOCONFIGURATION;
                $message_type   = 'failure';
                header('location: directory.php?message='.$message.'&message_type='.$message_type);     
            }               
        }
        
        break;
    case 'registerFree':
        $lessons_id = explode(", ", $_POST['item_number']);
        foreach($lessons_id AS $id){
            if ($id < 100000) {
                $fields_insert = array("users_LOGIN"    => $_SESSION['s_login'],
                                       "lessons_ID"     =>  $id,
                                       "active"         =>  1,
                                       "user_type"      =>  'student',
                                       "from_timestamp" =>  time());
                eF_insertTableData("users_to_lessons", $fields_insert);
            } else {
                $courseId = $id - 100000;
                $editCourse = new EfrontCourse($courseId);
                $userType = 'student';
                $courseUsers    = $editCourse-> getUsers();                         //Get all users that have this course
                $nonCourseUsers = $editCourse -> getNonUsers();                     //Get all the users that can, but don't, have this course
                $users          = array_merge($courseUsers, $nonCourseUsers);       //Merge users to a single array, which will be useful for displaying them
                if (in_array($_SESSION['s_login'], array_keys($nonCourseUsers))) {
                    $editCourse -> addUsers($_SESSION['s_login'], $userType);
                }
                if (in_array($_SESSION['s_login'], array_keys($courseUsers))) {
                    $userType != $courseUsers[$_SESSION['s_login']]['user_type'] ? $editCourse -> setRoles($_SESSION['s_login'], $userType) : $editCourse -> removeUsers($_SESSION['s_login']);
                }
            }
        }

        unset($_SESSION['cart']['lesson']);
        $message        = _PAYPALFREEORDERSUCCESS;
        $message_type   = 'success';
        header('location: student.php?ctg=lessons&message='.$message.'&message_type='.$message_type);
        break;
    case 'saveOrder':
        $log = fopen("ipn.log", "a");
        foreach ($_POST as $key => $value){
            $emailtext .= $key . " = " .$value ."\n";
        }
        $fields      = array('business'     => $_POST['business'],
                             'item_name'    => $_POST['item_name'],
                             'mc_gross'     => $_POST['amount'],
                             'item_number'  => $_POST['item_number'],
                             'mc_currency'  => $_POST['currency_code'],
                             'status'       => $_POST['status'],
                             'timestamp'    => time(),
                             'transactionID'=> $_POST['custom'],
                             'user'         => $_SESSION['s_login']);

        $result = eF_insertTableData("paypal_data", $fields);
        fwrite($log, "POST - " . gmstrftime ("%b %d %Y %H:%M:%S", time()) . "\n");
        fwrite($log, "POST DATA \n");
        fwrite($log, $emailtext."\n");
        if($result){
            unset($_SESSION['cart']['lesson']);
            $message        = _PAYPALORDERPROCESSING;
            $message_type   = 'success';
            header('location: directory.php?message='.$message.'&message_type='.$message_type);     
        }else{
            $message        = _PAYPALORDERPROCESSINGERROR;
            $message_type   = 'failure';
            header('location: directory.php?message='.$message.'&message_type='.$message_type);     
        }
        break;
    case 'addLessonToCart':
        if ($id) {
            $found = false;
            foreach ($_SESSION['cart']['lesson'] as $key => $value) {
                if ($value['id'] == $id) {
                    $found = true;
                }
            }
            if (!$found) {
                if ($id > 50000) {
                    $idReal = $id - 100000;
                    $course = new EfrontCourse($idReal);
                    $_SESSION['cart']['lesson'][] = array("id" => $id, "did" => $course -> course['directions_ID'], "price" => $course->course['price'], "name" => $course->course['name']);
                } else {
                    $lesson = new EfrontLesson($id);
                    $_SESSION['cart']['lesson'][] = array("id" => $id, "did" => $lesson -> lesson['directions_ID'], "price" => $lesson->lesson['price'], "name" => $lesson->lesson['name']);
                }
            }
        }
        
        print_cart();
        exit;
        break;
    case 'removeLessonFromCart':
        if ($id) {
            foreach ($_SESSION['cart']['lesson'] as $key => $value) {
                if ($value['id'] == $id) {
                    unset($_SESSION['cart']['lesson'][$key]);
                }
            }           
        }
        print_cart();
        exit();
        break;
    case 'removeLessonAllFromCart':
        foreach ($_SESSION['cart']['lesson'] as $key => $value) {
            unset($_SESSION['cart']['lesson'][$key]);
        }           
        print_cart();
        exit();
        break;
    case 'searchResults':   
            if (eF_checkParameter($_POST['name'], 'text')) {            //validate the text
                $queryString        = mb_strtolower($_POST['name']);    //we tranform letter to lower case in order to search them in the index
                $queryStringArray   = explode(' ', $queryString);       //explode search terms in an array
                $haveResults        = false;
                $last = null;
                for ($i = 0; $i < count($queryStringArray); $i++)  {
                    if (mb_strlen($queryStringArray[$i]) > 1 ) {
                        $resultsDirection   = eF_getTableData("directions", "name, id", "active = '1' and name like '%".$queryStringArray[$i]."%'");
                        //pr($resultsDirection);
                        if (sizeof($resultsDirection) > 0) { 
                            $resultsDirections[$i]  = $resultsDirection;
                        }
                    }
                    if (mb_strlen($queryStringArray[$i]) > 3 ) {
                        $resultsLesson      = eF_getTableData("lessons", "name, id", "active = '1' and name like '%".$queryStringArray[$i]."%'");
                        
                        if (sizeof($resultsLesson) > 0) { 
                            $resultsLessons[$i]     = $resultsLesson;
                        }
                    }
                    if (mb_strlen($queryStringArray[$i]) > 1 ) {
                        $resultsCourse      = eF_getTableData("courses", "name, id", "active = '1' and name like '%".$queryStringArray[$i]."%'");
                        if (sizeof($resultsCourse) > 0) { 
                            $resultsCourses[$i]     = $resultsCourse;
                        }   
                    }
                }
                
                if (sizeof($resultsLessons) > 0) {
                    $lessons = array();                                                                         //Create the lessons results array
                    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($resultsLessons));
                    foreach ($iterator as $key => $value) {
                        if ($key == 'id' && !in_array($value, array_keys($lessons))) {                          //Find the ID rows
                            $lessons[$value] = new EfrontLesson($value);                                        //Create a new lesson object for this ID
                            if (!$lessons[$value] -> lesson['active']) {                                            //If lesson is inactive 
                                unset($lessons[$key]);                                                              //Exclude it from results array
                            } else {
                                if (in_array($value, array_keys($userLessons))) {
                                    $lessons[$value]->lesson['my'] = '1';                                           //Add flag is student has already this lesson
                                } else {
                                    $lessons[$value]->lesson['my'] = '0';
                                }
                                $lessons[$value]->lesson['information'] = $lessons[$value] -> getInformation(); //Add extra information about this lesson
                                $lessons[$value]->lesson['link'] = $lessons[$value] -> toHTMLTooltipLink(basename($_SERVER['PHP_SELF'])."?direction=".$lessons[$value] -> lesson['directions_ID']."&lesson=".$lessons[$value] -> lesson['id']);
                                if (isset($_SESSION['s_login']) && $_SESSION['s_password']) {
                                    if ($lessons[$value]->lesson['languages_NAME'] != $currentUser -> user['languages_NAME']) {   //If lesson is in other lang 
                                        unset($lessons[$value]);
                                    } 
                                }
                            }
                        }
                    }
                }

                if (sizeof($resultsDirections) > 0) {
                    $directions = array();
                    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($resultsDirections));
                    foreach ($iterator as $key => $value) {
                        if ($key == 'id' && !in_array($value, array_keys($directions))) {
                            $directions[$value] = new EfrontDirection($value);
                            if ($directions[$value]['active'] == '0') {
                                unset($directions[$value]);
                            } else {
                                $directionLessons               = $directions[$value] -> getLessons(true,true);
                                $directions[$value]['lessons']  = sizeof($directionLessons);                    //Find number of lessons in each Direction
                            }
                        }
                    }
                }

                if (sizeof($resultsCourses) > 0) {
                    $courses = array();
                    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($resultsCourses));
                    foreach ($iterator as $key => $value) {
                        if ($key == 'id' && !in_array($value, array_keys($courses))) {
                            $courses[$value] = new EfrontCourse($value);
                            $courses[$value]-> course['link'] = $courses[$value] -> toHTMLTooltipLink(basename($_SERVER['PHP_SELF'])."?direction=".$courses[$value] -> course['directions_ID']."&course=".$courses[$value] -> course['id']);
                            if (in_array($value, array_keys($userCourses))) {
                                $courses[$value]->course['my'] = '1';                                           //Add flag is student has already this course
                            } else {
                                $courses[$value]->course['my'] = '0';
                            }
                        }
                    }
                }

                $smarty -> assign("T_COURSE_DATA_NUM", sizeof($courses));
                $smarty -> assign("T_DIRECTIONS_DATA_NUM", sizeof($directions));
                $smarty -> assign("T_DIRECTIONS_LESSONS_NUM", sizeof($lessons));
                $smarty -> assign("T_COURSE_DATA", $courses);
                $smarty -> assign("T_DIRECTIONS_DATA", $directions);
                $smarty -> assign("T_DIRECTIONS_LESSONS", $lessons);
                $smarty -> assign("T_TITLE_SEARCH", _EDITOR_SEARCHREPLACE_SEARCHREPLACE_FINDWHAT);
                //pr(sizeof($directions));
            } else {
                $message        = _NOSEARCHRESULTSFOUND;
                $message_type   = 'failure';
                header('location: '.basename($_SERVER['PHP_SELF']).'?message='.$message.'&message_type='.$message_type);
            }
        break;
    default:
        $directionsTree = new EfrontDirectionsTree();                                                   //Load Direction Tree
        if (isset($direction)) {                                                                        //Directions in second or more level
            $fullPath           = array_reverse($directionsTree -> getNodeAncestors($direction));       //Find the path to the root direction
            //pr($fullPath);
            if (isset($lesson)) {
                $curLesson          = new EfrontLesson($lesson);
                $lessonContent      = new EFrontContentTree($lesson);
                $lessonContentTree  = $lessonContent -> toHTMLSelectOptions();
                $lessonInfo         = $curLesson -> getInformation();
                if (in_array($lesson, array_keys($userLessons))) {
                    $curLesson->lesson['my'] = '1';                                         //Add flag is student has already this lesson
                } else {
                    $curLesson->lesson['my'] = '0';
                }
                $smarty -> assign("T_CURRENT_LESSON", $curLesson);
                $smarty -> assign("T_CURRENT_LESSON_TREE", $lessonContentTree);
                $smarty -> assign("T_CURRENT_LESSON_INFO", $lessonInfo);
                $smarty -> assign("T_CURRENT_LESSON_INFO_NUM", sizeof($lessonInfo));
            } elseif (isset($course)) {
                $course     = new EfrontCourse($course);
                $courseInfo = $course -> getInformation();
                if (in_array($course -> course['id'], array_keys($userCourses))) {
                    $course -> course['my'] = '1';                                          //Add flag is student has already this course
                } else {
                    $course -> course['my'] = '0';
                }
                
                $smarty -> assign("T_CURRENT_COURSE", $course);
                $smarty -> assign("T_CURRENT_COURSE_INFO", $courseInfo);
                $smarty -> assign("T_CURRENT_COURSE_INFO_NUM", sizeof($courseInfo));
                //$smarty -> assign("T_CURRENT_COURSE", $course -> getInformation());
                //$smarty -> assign("T_CURRENT_COURSE_INFO_TIP", $course -> toHTMLTooltipLink());
            } else {    
                $children           = $directionsTree -> getNodeChildren($direction);                       //Find children Directions and the selected Direction
                $currentDirection   = $children['name'];
                $direction          = new EfrontDirection($direction);                                      //Get the object of the current Direction
                $directionLessons   = $direction -> getLessons(true);                                       //Get Directions Lessons
                $directionCourses   = $direction -> getCourses(true);                                       //Get Directions Courses
                
                foreach ($directionLessons as $key => $value){
                    if (!$value -> lesson['active'] || $value -> lesson['course_only']) {
                        unset($directionLessons[$key]);
                    } else {
                        if (in_array($key, array_keys($userLessons))) {
                            $directionLessons[$key] -> lesson['my'] = '1';                                          //Add flag is student has already this lesson
                        } else {
                            $directionLessons[$key] -> lesson['my'] = '0';
                        }
                        //$directionLessons[$key] -> lesson['information'] = $directionLessons[$key] -> getInformation();
                        $directionLessons[$key] -> lesson['link'] = $directionLessons[$key] -> toHTMLTooltipLink(basename($_SERVER['PHP_SELF'])."?direction=".$_GET['direction']."&lesson=".$directionLessons[$key] -> lesson['id']);
                        if (isset($currentUser) && $directionLessons[$key] -> lesson['languages_NAME'] != $currentUser -> user['languages_NAME']) {                 //If lesson is in other lang
                            unset($directionLessons[$key]);
                        }
                    }
                }
                //pr($directionLessons);
                //pr($userCourses);
                foreach ($directionCourses as $key => $value){
                    if (!$value->course['active']) {
                        unset($directionCourses[$key]);
                    } else {
                        if (in_array($key, array_keys($userCourses))) {
                            $directionCourses[$key] -> course['my'] = '1';                                          //Add flag is student has already this course
                        } else {
                            $directionCourses[$key] -> course['my'] = '0';
                        }
                        $directionCourses[$key] -> course['link'] = $directionCourses[$key] -> toHTMLTooltipLink(basename($_SERVER['PHP_SELF'])."?direction=".$_GET['direction']."&course=".$directionCourses[$key] -> course['id']);
                        //$directionLessons = $value -> getLessons(true,true);
                        //foreach ($directionLessons as $keys => $values) {if (!$values->lesson['active']) unset($directionLessons[$keys]);}
                        //$directionCourses[$key]['lessons']    = sizeof($directionLessons);        //Find number of lessons in each Direction
                    }
                }
                //pr($directionCourses);
                $iterator           = (new EfrontNodeFilterIterator($children));            //Hold only childrens
                
                $smarty -> assign("T_COURSE_DATA", $directionCourses);                      //Assign the current directions courses
                $smarty -> assign("T_COURSE_DATA_NUM", sizeof($directionCourses));          //Assign the sizeof current directions courses
                $smarty -> assign("T_DIRECTIONS_LESSONS", $directionLessons);               //Assign the current lessons names
                $smarty -> assign("T_DIRECTIONS_LESSONS_NUM", sizeof($directionLessons));   //Assign the sizeof current lessons names
            }
            $smarty -> assign("T_DIRECTIONS_PATH", $fullPath);                          //Assign the path to the root direction if possible
        } else {
            $iterator   = new EfrontNodeFilterIterator($directionsTree -> tree);    //Find all root Directions
        }

        foreach ($iterator as $key => $value) {
            if ($value['active'] == "1") {                                          //Select only active Directions
                $directions[$key]               = $value;                           //Create array with these Directions
                $direction                      = new EfrontDirection($key);    
                $directionLessons               = $direction -> getLessons(true,true);
                foreach ($directionLessons as $keys => $values) {if (!$values->lesson['active']) unset($directionLessons[$keys]);}
                $directions[$key]['lessons']    = sizeof($directionLessons);        //Find number of lessons in each Direction
            }
        }           
        $smarty -> assign("T_DIRECTIONS_DATA", $directions);                //Assign the direction list
        $smarty -> assign("T_DIRECTIONS_DATA_NUM", sizeof($directions));    //Assign the sizeof direction list
}

$smarty -> assign("T_CART_LESSONS", $_SESSION['cart']['lesson']);
$smarty -> assign("T_CART_LESSONS_SIZE", sizeof($_SESSION['cart']['lesson']));
$smarty -> assign("T_INDEXPAGE", preg_match("/index.php/i",basename($_SERVER['PHP_SELF'])));

/**
 *
 * END OF MAIN PART
 *
 */
$smarty -> assign("T_LANGUAGES_DEFAULT", $GLOBALS['configuration']['default_language']);
$smarty -> assign("T_LANGUAGES", EfrontSystem :: getLanguages(true));
$smarty -> assign("T_HEADER_LOAD_SCRIPTS", array_unique($loadScripts));                     //array_unique, so it doesn't send duplicate entries
$smarty -> assign("T_MESSAGE", $message);                                                   //Any messages generated during script execution
$smarty -> assign("T_MESSAGE_TYPE", $message_type);
$smarty -> assign("T_CONFIGURATION", $configuration);                                       //Assign global configuration values to smarty
$smarty -> load_filter('output', 'eF_template_formatTimestamp');                            //smartt filters, in case they are needed
$smarty -> load_filter('output', 'eF_template_formatLogins');
if ((isset($_SESSION['s_login']) && !preg_match('/index.php/i', $_SERVER['PHP_SELF'])) || ($configuration['lessons_directory'] == '2' && $configuration['interface_view'] == '1')) {
    $smarty -> display('directory.tpl');                                                        //Display template
}


function eF_truncate ($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
    if ($length == 0)
        return '';

    if (mb_strlen($string) > $length) {
        $length -= mb_strlen($etc);
        if (!$break_words && !$middle) {
            $string = preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length+1));
        }
        if(!$middle) {
            return mb_substr($string, 0, $length).$etc;
        } else {
            return mb_substr($string, 0, $length/2) . $etc . mb_substr($string, -$length/2);
        }
    } else {
        return $string;
    }
}

/**
*
*/
function print_cart() {

    $finalPrice = 0;
    
    //$str = "<form action = \"".basename($_SERVER['PHP_SELF'])."?fct=cartPreview\" method = \"post\">";
    $str .= "<table width=\"100%\">";
    foreach ($_SESSION['cart']['lesson'] as $key => $value) {
        $str .= "<tr><td width=\"70%\"><a href=\"".basename($_SERVER['PHP_SELF'])."?direction=".$value['did']."&lesson=".$value['id']."\" title=\"".$value['name']."\">".eF_truncate($value['name'], '23', '...', true)."</a></td><td align=\"right\" width=\"30%\">";
        if ($value['price'] == 0) {
            $str .= _FREEOFCHARGE;
        } else {
            $str .= $value['price']." ".$GLOBALS['CURRENCYSYMBOLS'][$GLOBLAS['configuration']['currency']];
        }
        $str .= " <a style=\"cursor:pointer;\" onclick = \"ajaxPostRemove('".$value['id']."', this);\"><img src = \"images/16x16/delete.png\" alt = \""._REMOVEFROMCART."\" title = \""._REMOVEFROMCART."\" border = \"0\"></a></td></tr>";
        $finalPrice += $value['price']; 
    }
    if (sizeof($_SESSION['cart']['lesson']) >0 ) {
        $str .= "<tr><td colspan=\"2\" align=\"right\" style=\"background:#F8F8F8 none repeat scroll 0%;\"><b>"._PAYPALFINALPRICE.": ";
        if ($finalPrice == 0) {
            $str .= _FREEOFCHARGE;
        } else {        
            $str .= $finalPrice." ".$GLOBALS['CURRENCYSYMBOLS'][$GLOBLAS['configuration']['currency']];
        }
        $str .= "</b> <a style=\"cursor:pointer;\" onclick = \"ajaxPostRemoveAll('', this);\"><img src = \"images/16x16/delete.png\" alt = \""._REMOVEALLFROMCART."\" title = \""._REMOVEALLFROMCART."\" border = \"0\"></a></td></tr>";
        $str .= '<tr><td colspan="2" align="right"><br /><input  class = "flatButton" name="cms_page" type="submit" value="'._CONTINUE.'"></td></tr></table>';
    } else {
        $str .= "<tr><td colspan = \"2\">"._NOCART."</td></tr></table>";
    }
    //$str .= '</form>';
    
    echo $str;
}

?>