/**
 * This function exports the given item
 * @param    integer    Id from learnpath_items table
 * @param    integer    Item id
 * @param    string    Itm type
 * @param    boolean    Shall the SCORM communications features be added? (true). Default: false.
 * @return    void (outputs a zip file)
 * @todo    Try using the SCORM communications addition (adding a button and several javascript calls to the SCORM API) elsewhere than just in the export feature, so it doesn't look like an incoherent feature
 */
function exportitem($id, $item_id, $item_type, $add_scorm_communications = false)
{
    $course_id = api_get_course_int_id();
    global $circle1_files, $expdir, $_course, $_SESSION, $GLOBALS;
    global $timeNoSecFormat, $dateFormatLong, $language_interface, $langPubl, $langDone, $langThisCourseDescriptionIsEmpty, $lg_course_description, $lg_introduction_text, $_cid, $langHotPotatoesFinished, $lg_author, $lg_date, $lg_groups, $lg_users, $lg_ass, $lg_dropbox, $test, $langQuestion;
    $libp = api_get_path(SYS_CODE_PAH);
    include_once $libp . 'exercice/exercise.class.php';
    include_once $libp . 'question.class.php';
    include_once $libp . 'answer.class.php';
    $langLasting = '';
    //avoid code parser warning
    include_once '../resourcelinker/resourcelinker.inc.php';
    $LPname = display_addedresource_link_in_learnpath($item_type, $item_id, '', $id, 'builder', 'nolink');
    $expcontent = "<!--\n        This is an exported file from Chamilo Learning Path belonging to a Scorm compliant content package.\n        Do not modify or replace individually.\n\n        Export module author : Denes Nagy <*****@*****.**>\n\n        -->\n\n        ";
    // Files needed for communicating with the scos.
    $scocomfiles = "<script type='text/javascript' src='../js/APIWrapper.js'></script>" . "<script type='text/javascript' src='../js/SCOFunctions.js'></script>";
    $expcontent .= '<html><head><link rel="stylesheet" href="../css/default.css" type="text/css" media="screen,projection" />' . $scocomfiles . '</head><body>';
    $donebutton .= "<script type='text/javascript'>\n            /* <![CDATA[ */\n            loadPage();\n            var   studentName = '!';\n            var   lmsStudentName = doLMSGetValue(  'cmi.core.student_name' );\n            if ( lmsStudentName  != '' )\n            {\n               studentName = ' ' + lmsStudentName +   '!';\n            }\n            /* ]]> */\n            </script>\n            <br /><br />\n            <form><input type=\"hidden\" name=\"SQMSESSID\" value=\"36812c2dea7d8d6e708d5e6a2f09b0b9\" />\n                <table cols='3'\twidth='100%' align='center'>\n                    <tr>\n                    <td\talign='middle'><input type = 'button' value\t= '  " . $langDone . "  ' onclick = \"javascript: doQuit('completed');\" id='button2' name='button2'></td>\n                    </tr>\n                </table>\n            </form>";
    /**
     * Switch between the different element types, namely:
     * - Agenda
     * - Ad_Valvas
     * - Course_description
     * - Document
     * - Introduction_text
     * - HotPotatoes
     * - Exercise
     * - Post
     * - Forum          ]
     * - Thread         ]
     * - Dropbox        ]
     * - Assignments    ] These elements are all replaced by a simple message in the exported document.
     * - Groups         ]
     * - Users          ]
     * - Link _self
     * - Link _blank
     */
    switch ($item_type) {
        // AGENDA BEGIN
        case 'Agenda':
            // 1. Get agenda event data from the database table.
            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
            $sql = "SELECT * FROM " . $TABLEAGENDA . " where c_id = {$course_id} AND (id={$item_id})";
            $result = Database::query($sql);
            // 2. Prepare table output.
            $expcontent .= "<table class=\"data_table\" >";
            $barreMois = '';
            // 3. For each event corresponding to this agenda, do the following:
            while ($myrow = Database::fetch_array($result)) {
                $start_date_local = api_get_local_time($myrow['start_date'], null, date_default_timezone_get());
                //3.1 Make the blue month bar appear only once.
                if ($barreMois != api_format_date($start_date_local, "%m")) {
                    // 3.1.1 Update the check value for the month bar.
                    $barreMois = api_format_date($start_date_local, "%m");
                    // 3.1.2 Display the month bar.
                    $expcontent .= "<tr><td id=\"title\" colspan=\"2\" class=\"month\" valign=\"top\">" . api_format_date($start_date_local, "%B %Y") . "</td></tr>";
                }
                // 3.2 Display the agenda items (of this month): the date, hour and title.
                $db_date = (int) api_format_date($start_date_local, "%d");
                if ($_GET['day'] != $db_date) {
                    // 3.2.1.a If the day given in the URL (might not be set) is different from this element's day, use style 'data'.
                    $expcontent .= "<tr><td class=\"data\" colspan='2'>";
                } else {
                    // 3.2.1.b Else (same day) use style 'datanow'.
                    $expcontent .= "<tr><td class=\"datanow\" colspan='2'>";
                }
                // 3.2.2 Mark an anchor for this date.
                $expcontent .= "<a name=\"" . $db_date . "\"></a>";
                // anchoring
                // 3.2.3 Write the date and time of this event to the export string.
                $expcontent .= api_format_date($start_date_local);
                // 3.2.4 If a duration is set, write it, otherwise ignore.
                if ($myrow['duration'] == '') {
                    $expcontent .= "<br />";
                } else {
                    $expcontent .= " / " . $langLasting . " " . $myrow['duration'] . "<br />";
                    //langLasting comes from lang/x/agenda.inc.php
                }
                // 3.2.5 Write the title.
                $expcontent .= $myrow['title'];
                $expcontent .= "</td></tr>";
                // 3.2.6 Prepare the content of the agenda item.
                $content = $myrow['content'];
                // 3.2.7 Make clickable???
                $content = Text::make_clickable($content);
                // 3.2.8 Write the prepared content to the export string.
                $expcontent .= "<tr><td class=\"text\" colspan='2'>";
                $expcontent .= $content;
                $expcontent .= "</td></tr>";
                // Displaying the agenda item of this month: the added resources.
                // This part is not included into LP export.
                /*if (check_added_resources("Agenda", $myrow['id'])) {
                      $content.= "<tr><td colspan='2'>";
                      $content.= "<i>".get_lang('AddedResources')."</i><br />";
                      display_added_resources("Agenda", $myrow['id']);
                      $content.= "</td></tr>";
                  }*/
            }
            // 4. Finish the export string.
            $expcontent .= "<tr></table>";
            break;
            // ANNOUNCEMENT BEGIN
        // ANNOUNCEMENT BEGIN
        case 'Ad_Valvas':
            // 1. Get the announcement data from the database
            $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
            $sql = "SELECT * FROM {$tbl_announcement} WHERE c_id = {$course_id} AND id='{$item_id}'";
            $result = Database::query($sql);
            // 2. Initialise export string
            $expcontent .= "<table class=\"data_table\">";
            // 3. For each announcement matching the query
            while ($myrow = Database::fetch_array($result)) {
                // 3.1 Get the __ field data.
                $content = $myrow[1];
                //$content = nl2br($content);
                // 3.2 Prepare the data for export.
                $content = Text::make_clickable($content);
                // 3.3 Get a UNIX(?<-mktime) Timestamp of the end_date for this announcement.
                $last_post_datetime = $myrow['end_date'];
                // post time format  datetime of database layer (MySQL is assumed)
                list($last_post_date, $last_post_time) = split(' ', $last_post_datetime);
                list($year, $month, $day) = explode('-', $last_post_date);
                list($hour, $min) = explode(':', $last_post_time);
                $announceDate = mktime($hour, $min, 0, $month, $day, $year);
                // 3.4 Compare the end date to the last login date of the user (mark it in red if he has not already read it).
                if ($announceDate > $_SESSION['user_last_login_datetime']) {
                    $colorBecauseNew = " color=\"red\" ";
                } else {
                    $colorBecauseNew = '  ';
                }
                // 3.5 Write this content to the export string (formatted HTML array).
                $expcontent .= "<tr>\n" . "<td class=\"cell_header\">\n" . "<font " . $colorBecauseNew . ">" . $langPubl . " : " . api_convert_and_format_date($last_post_datetime, null, date_default_timezone_get()) . "</font>\n" . "</td>\n" . "</tr>\n" . "<tr>\n" . "<td>\n" . $content . "</td>\n" . "</tr>\n";
            }
            // while loop
            // 4 Finish the export string.
            $expcontent .= "</table>";
            break;
            // Course_description BEGIN
        // Course_description BEGIN
        case 'Course_description':
            // 1. Get course description data from database.
            $tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
            $result = Database::query("SELECT id, title, content FROM " . $tbl_course_description . " WHERE c_id = {$course_id}  ORDER BY id");
            // 2. Check this element.
            if (Database::num_rows($result)) {
                // 2.a This course has one (or more) description in the database.
                $expcontent .= "<hr noshade=\"noshade\" size=\"1\" />";
                // 2.a.1 For each description available for this course.
                while ($row = Database::fetch_array($result)) {
                    // 2.a.1.1 Write title to export string.
                    $expcontent .= "<h4>" . $row['title'] . "</h4>";
                    // 2.a.1.2 Prepare content.
                    $content = Text::make_clickable(nl2br($row['content']));
                    // 2.a.1.3 Write content to the export string.
                    $expcontent .= $content;
                }
            } else {
                // 2.b This course has no description available.
                $expcontent .= "<br /><h4>{$langThisCourseDescriptionIsEmpty}</h4>";
            }
            break;
            // DOCUMENT BEGIN
        // DOCUMENT BEGIN
        case 'Document':
            // 1. Get the document data from the database.
            $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
            $sql_query = "SELECT * FROM {$tbl_document} WHERE c_id = {$course_id} AND id={$item_id}";
            $sql_result = Database::query($sql_query);
            $myrow = Database::fetch_array($sql_result);
            // 2. Get the origin path of the document to treat it internally.
            $orig = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . $myrow['path'];
            // 3. Make some kind of strange transformation to get the destination filepath ???
            $pathname = explode('/', $myrow['path']);
            $last = count($pathname) - 1;
            $filename = 'data/' . $filename . $pathname[$last];
            $copyneeded = true;
            // Html files do not need to be copied as the ok button is inserted into them,
            // so don't copy directly.
            $extension = explode('.', $pathname[$last]);
            // This old condition was WRONG for names like design.html.old. Instead, we now get the extension
            // by using preg_match to match case-insensitive (probably faster than 4 conditions).
            //if (($extension[1]=='htm') or ($extension[1]=='html') or ($extension[1]=='HTM') or ($extension[1]=='HTML')) {
            // 4. Check the file extension.
            if (preg_match('/.*(\\.htm(l)?)$/i', $pathname[$last])) {
                // 4.a If this file ends with ".htm(l)", we consider it's an HTML file.
                // src tag check begin
                // We now check if there is any src attribute in htm(l) files, if yes, we have to also export
                // the target file (swf, mp3, video,...) of that src tag.
                // In case of absolute links (http://) this is not neccessary, but makes no error.
                // However still missing : relative links case with subdirs -> the necessary dirs are not created in the exported package.
                // 4.a.1 Get the file contents into $file.
                $file = file_get_contents($orig);
                // 4.a.2 Get all the src links in this file.
                //preg_match_all("|((?i)src=\".*\" )|U",$file,$match);
                $match = GetSRCTags($orig);
                // 4.a.3 For each src tag found, do the following:
                for ($i = 0; $i < count($match); $i++) {
                    // 4.a.3.1 Get the tag (split from the key).
                    list($key, $srctag) = each($match);
                    $src = $srctag;
                    // 4.a.3.2 Check the link kind (web or absolute/relative).
                    if (stristr($src, 'http') === false) {
                        // 4.a.3.2.a Do something only if relative (otherwise the user will be able to see it too anyway).
                        // 4.a.3.2.a.1 Get a proper URL and remove all './'
                        $src = urldecode($src);
                        //mp3
                        //$src=str_replace('./','',$src);
                        $src = preg_replace('/^\\.\\//', '', $src);
                        // 4.a.3.2.a.2 Remove the player link from the URL (only use the mp3 file).
                        $src = str_replace('mp3player.swf?son=', '', $src);
                        //mp3
                        // 4.a.3.2.a.3 Remove funny link parts.
                        $src = str_replace('?0', '', $src);
                        //mp3
                        // The previous lines are used when creating docs with Chamilo Document tool's htmlarea
                        // Rows marked by 'mp3' are needed because the mp3 plugin inserts the swf-mp3 links in a very strange way
                        // and we can decode them with those 3 lines, hoping this will not cause errors in case of other htmls,
                        // created by any other software.
                        // 4.a.3.2.a.4 Prepare source and destination paths.
                        $source = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . dirname($myrow['path']) . '/' . $src;
                        $dest = $expdir . '/data/' . $src;
                        //CopyNCreate($source,$dest);
                        rcopy($source, $dest);
                    }
                    //else...?
                }
                // src tag check end
                // sco communication insertion begin
                // 4.a.4 If we want to add SCORM actions and a "Done" button, do the following:
                if ($add_scorm_communications === true) {
                    if ($bodyclose = strpos($file, '</body>')) {
                        $file = substr_replace($file, $scocomfiles . $donebutton, $bodyclose, 7);
                    } elseif ($htmlclose = strpos($file, '</html>')) {
                        $file = substr_replace($file, $scocomfiles . $donebutton, $htmlclose, 7);
                        $file .= '</html>';
                    } else {
                        $file .= $scocomfiles . $donebutton;
                    }
                }
                //sco communication insertion end
                // 4.a.5 Replace the file's name by adding the element's ID before htm.
                // This will not work with uppercase HTML though. Maybe use the preg_replace syntax proposed...
                $filename = str_replace('.htm', $id . '.htm', $filename);
                //$filename=preg_replace('/.*(\.htm(l)?)$/i',$id.$1,$filename);
                // 4.a.6 Export these contents to a file and set the circle1_files array for later reuse.
                exporttofile($filename, $LPname, $id, $file);
                // The file has been copied, so ask not to copy it again.
                $copyneeded = false;
            }
            //if (htm(l) files) end
            // 5. If we still need to copy the file (e.g. it was not an HTML file), then copy and set circle1_files for later reuse.
            if ($copyneeded) {
                copy($orig, $expdir . '/' . $filename);
                $circle1_files[0][] = $filename;
                $circle1_files[1][] = $LPname;
                $circle1_files[2][] = $id;
            }
            //echo $orig;
            return;
            // Introduction_text BEGIN
        // Introduction_text BEGIN
        case 'Introduction_text':
            // 1 Get the introduction text data from the database.
            $TBL_INTRO = Database::get_course_tool_intro_table();
            // Modified by Ivan Tcholakov, 15-SEP-2008.
            //$result = Database::query("SELECT * FROM ".$TBL_INTRO." WHERE id=1");
            $result = Database::query("SELECT * FROM " . $TBL_INTRO . " WHERE c_id = {$course_id} AND id='course_homepage'");
            //
            $myrow = Database::fetch_array($result);
            $intro = $myrow['intro_text'];
            // 2 Write introduction text to the export string.
            $expcontent .= '<br />' . $intro;
            break;
            // HotPotatoes BEGIN
        // HotPotatoes BEGIN
        case 'HotPotatoes':
            // 1. Get HotPotatoes data from the document table.
            $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
            $result = Database::query("SELECT * FROM {$tbl_document} WHERE c_id = {$course_id} AND id={$item_id}");
            $myrow = Database::fetch_array($result);
            // 2. Get the document path.
            $testfile = api_get_path(SYS_COURSE_PATH) . $_course['path'] . "/document" . urldecode($myrow['path']);
            // 3. Get the document contents into a string.
            $content = file_get_contents($testfile);
            // 4. Get the document filename (just the file, no path) - would probably be better to use PHP native function.
            $pathname = explode('/', $myrow['path']);
            $last = count($pathname) - 1;
            $filename = 'data/' . $filename . $pathname[$last];
            // 4beta - get all linked files and copy them (procedure copied from documents type).
            // Get all the src links in this file.
            $match = GetSRCTags($testfile);
            // For each src tag found, do the following:
            foreach ($match as $src) {
                //Check the link kind (web or absolute/relative)
                if (stristr($src, 'http') === false) {
                    // Do something only if relative (otherwise the user will be able to see it too anyway).
                    // Get a proper URL and remove all './'
                    $src = urldecode($src);
                    //mp3
                    $src = str_replace('./', '', $src);
                    // Remove the player link from the URL (only use the mp3 file).
                    $src = str_replace('mp3player.swf?son=', '', $src);
                    //mp3
                    // Remove funny link parts.
                    $src = str_replace('?0', '', $src);
                    //mp3
                    // The previous lines are used when creating docs with Chamilo Document tool's htmlarea.
                    // Rows marked by 'mp3' are needed because the mp3 plugin inserts the swf-mp3 links in a very strange way
                    // and we can decode them with those 3 lines, hoping this will not cause errors in case of other htmls,
                    // created by any other software.
                    // Prepare source and destination paths.
                    $source = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . dirname($myrow['path']) . '/' . $src;
                    $dest = $expdir . '/data/' . $src;
                    //CopyNCreate($source,$dest);
                    rcopy($source, $dest);
                }
                //else...?
            }
            // 5. Prepare the special "close window" for this test.
            $closewindow = "<html><head><link rel='stylesheet' type='text/css' href='../css/default.css'></head><body>" . "<br /><div class='message'>{$langHotPotatoesFinished}</div></body></html>";
            // Finish is the function of HP to save scores, we insert our scorm function calls to its beginning
            // 'Score' is the variable that tracks the score in HP tests.
            // 6.
            $mit = "function Finish(){";
            $js_content = "var SaveScoreVariable = 0; // This variable is included by Chamilo LP export\n" . "function mySaveScore() // This function is included by Chamilo LP export\n" . "{\n" . "   if (SaveScoreVariable==0)\n" . "\t\t{\n" . "\t   SaveScoreVariable = 1;\n" . "      exitPageStatus = true;\n" . "      computeTime();\n" . "      doLMSSetValue( 'cmi.core.score.raw', Score );\n" . "      doLMSSetValue( 'cmi.core.lesson_status', 'completed' );\n" . "      doLMSCommit();\n" . "      doLMSFinish();\n" . "\t\t}\n" . "}\n" . "function Finish(){\n" . " mySaveScore();";
            $start = "<script type='text/javascript'> loadPage(); </script>";
            // 7. Replace the current MIT function call by our set of functions. In clear, transform HP to SCORM.
            $content = str_replace($mit, $js_content, $content);
            // 8. Finally, add the API loading calls (although that might have been done first).
            $content = str_replace("</script>", "</script>" . $scocomfiles . $start, $content);
            // 9. Change the filename to add the database ID and export to a new file,
            // setting the circle1_files array for later reuse.
            $filename = str_replace('.htm', $id . '.htm', $filename);
            exporttofile($filename, $LPname, $id, $content);
            return;
            // Chamilo test BEGIN
        // Chamilo test BEGIN
        case 'Exercise':
            //1 Use the export_exercise() function to do the job of constructing the question's HTML table
            $expcontent .= export_exercise($item_id);
            break;
            // POST BEGIN
        // POST BEGIN
        case 'Post':
            // 1. Get the forum post data from the database.
            $tbl_posts = Database::get_course_table(TABLE_FORUM_POST);
            $tbl_posts_text = Database::get_course_table(TOOL_FORUM_POST_TEXT_TABLE);
            $result = Database::query("SELECT * FROM {$tbl_posts} where c_id = {$course_id} AND post_id={$item_id}");
            $myrow = Database::fetch_array($result);
            // Grabbing the title of the post.
            $sql_titel = "SELECT * FROM {$tbl_posts_text} WHERE c_id = {$course_id} AND post_id=" . $myrow['post_id'];
            $result_titel = Database::query($sql_titel);
            $myrow_titel = Database::fetch_array($result_titel);
            $posternom = $myrow['nom'];
            $posterprenom = $myrow['prenom'];
            $posttime = $myrow['post_time'];
            $posttext = $myrow_titel['post_text'];
            $posttitle = $myrow_titel['post_title'];
            $posttext = str_replace('"', "'", $posttext);
            //2 Export contents as an HTML table
            $expcontent .= "<table border='0' cellpadding='3' cellspacing='1' width='100%'>\n                            <tr>\n                                <td colspan='2' bgcolor='#e6e6e6'><b>{$posttitle}</b><br />{$posttext}</td>\n                            </tr>\n                            <tr>\n                                <td colspan='2'></td>\n                            </tr>\n                            <tr>\n                                <td bgcolor='#cccccc' align='left'>{$lg_author} : {$posterprenom} {$posternom}</td>\n                                <td align='right' bgcolor='#cccccc'>{$lg_date} : {$posttime}</td>\n                            </tr>\n                            <tr><td colspan='2' height='10'></td></tr>\n                        </table>";
            break;
            // NOT IMPLEMENTED ITEMS BEGIN
        // NOT IMPLEMENTED ITEMS BEGIN
        case 'Forum':
        case 'Thread':
        case 'Dropbox':
        case 'Assignments':
        case 'Groups':
        case 'Users':
            // 1. Instead of building something, put an info message.
            $langItemMissing1 = "There was a ";
            $langItemMissing2 = "page (step) here in the original Chamilo Learning Path.";
            $expcontent .= "<div class='message'>{$langItemMissing1} {$item_type} {$langItemMissing2}</div>";
            break;
            // Link BEGIN
        // Link BEGIN
        case 'Link _self':
        case 'Link _blank':
            // 1. Get the link data from the database.
            $TABLETOOLLINK = Database::get_course_link_table();
            $result = Database::query("SELECT * FROM {$TABLETOOLLINK} WHERE c_id = {$course_id} AND id={$item_id}");
            $myrow = Database::fetch_array($result);
            $thelink = $myrow['url'];
            // 2. Check the link type (open in blank page or in current page).
            if ($item_type == 'Link _blank') {
                $target = '_blank';
            }
            // 3. Write the link to the export string.
            $expcontent .= "<a href='{$thelink}?SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9' target='" . $target . "'>{$LPname}</a>";
            // 4. Change the element type for later changes (this is lost, however, so useless here).
            $item_type = 'Link';
            // To put this to the filename.
            //$LPname="<a href='$thelink?SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9' target=".$target.">$LPname</a>";
            // I am still not sure about Link export : to export them as files or they can appear in the TOC at once ?
            // To enable the second possibility, unrem the row $LPname=...
            break;
    }
    // Now we add the Done button and the initialize function : loadpage()
    // not in the case of Documents, HotP
    if ($item_type != 'Exercise' and $add_scorm_communications === true) {
        $expcontent .= $donebutton;
    }
    // End the export string with valid HTML tags.
    $expcontent .= "</body></html>";
    // Prepare new file name.
    $filename = $item_type . $id . ".htm";
    // Write the export content to the new file.
    exporttofile('data/' . $filename, $LPname, $id, $expcontent);
}