ca4f5fefbb78869b9601e9e4872320f5b3e1397c
[atutor.git] / docs / mods / _core / imscc / ims_export.php
1 <?php
2 /************************************************************************/
3 /* ATutor                                                               */
4 /************************************************************************/
5 /* Copyright (c) 2002 - 2009                                            */
6 /* Inclusive Design Institute                                           */
7 /*                                                                      */
8 /* This program is free software. You can redistribute it and/or        */
9 /* modify it under the terms of the GNU General Public License          */
10 /* as published by the Free Software Foundation.                        */
11 /************************************************************************/
12 // $Id$
13 define('AT_INCLUDE_PATH', '../../../include/');
14
15 /* content id of an optional chapter */
16 $cid = isset($_REQUEST['cid']) ? intval($_REQUEST['cid']) : 0;
17
18 if (isset($_REQUEST['to_tile']) && !isset($_POST['cancel'])) {
19         /* for TILE */
20         require_once(AT_INCLUDE_PATH.'vitals.inc.php');
21         if (!authenticate(AT_PRIV_ADMIN, AT_PRIV_RETURN)) {
22                 /* user can't be authenticated */
23                 header('HTTP/1.1 404 Not Found');
24                 echo 'Document not found.';
25                 exit;
26         }
27         
28         /* to avoid timing out on large files */
29         @set_time_limit(0);
30         
31         // oauth authentication. Get oauth access token: $access_token_key
32         $client_callback_url = AT_BASE_HREF.'mods/_core/imscc/ims_export.php?to_tile=1'.SEP.'cid='.$cid;
33         if (isset($_REQUEST['to_a4a'])){
34                 $client_callback_url .= SEP.'to_a4a=1';
35         }
36         include_once('../imscp/oauth/oauth_authenticate.php');
37
38         $m = md5(DB_PASSWORD . 'x' . ADMIN_PASSWORD . 'x' . $_SERVER['SERVER_ADDR'] . 'x' . $cid . 'x' . $_SESSION['course_id'] . 'x' . date('Ymd'));
39         $export_url = AT_BASE_HREF. 'mods/_core/imscc/ims_export.php?cid='.$cid.SEP.'c='.$_SESSION['course_id'].SEP.'m='.$m;
40         if (isset($_REQUEST['to_a4a'])){
41                 $export_url .= SEP.'a4a=1';
42         }
43         
44         $tile_import_url = AT_TILE_IMPORT_URL. '?oauth_token='.$access_token_key.'&url='.urlencode($export_url);
45         
46         $oauth_server_response = @file_get_contents($tile_import_url);
47         
48         // handle OAUTH import response
49         foreach (explode('&', $oauth_server_response) as $rtn)
50         {
51                 $rtn_pair = explode('=', $rtn);
52                 
53                 if ($rtn_pair[0] == 'course_id') $tile_course_id = $rtn_pair[1];
54                 if ($rtn_pair[0] == 'error') $error = urldecode($rtn_pair[1]);
55         }
56         
57         if ($tile_course_id > 0)
58                 $msg->addFeedback(array('TILE_IMPORT_SUCCESS', AT_TILE_VIEW_COURSE_URL.$tile_course_id));
59         else
60         {
61                 // No response from transformable, the package file might be too big
62                 if (trim($error) == '') $error = _AT('tile_no_response');
63                 else {
64                         // delete this access token since it cannot import into Transformable
65                         $sql = "DELETE FROM ".TABLE_PREFIX."oauth_client_tokens
66                                  WHERE token = '".$access_token_key."'
67                                    AND token_type='access'";
68                         $result = mysql_query($sql, $db);
69                 }
70                 $msg->addError(array('TILE_IMPORT_FAIL', $error));
71         }
72         
73         header('Location: '.AT_BASE_HREF.'mods/_core/imscp/index.php');
74         exit;
75 } else if (isset($_GET['m'])) {
76         /* for TILE */
77
78         /* request (hopefully) coming from a TILE server, send the content package */
79
80         $_user_location = 'public';
81         require(AT_INCLUDE_PATH.'vitals.inc.php');
82         
83         $c   = isset($_REQUEST['c'])   ? intval($_REQUEST['c'])   : 0;
84         $m = md5(DB_PASSWORD . 'x' . ADMIN_PASSWORD . 'x' . $_SERVER['SERVER_ADDR'] . 'x' . $cid . 'x' . $c . 'x' . date('Ymd'));
85         if (($m != $_GET['m']) || !$c) {
86                 header('HTTP/1.1 404 Not Found');
87                 echo 'Document not found.';
88                 exit;
89         }
90         
91         $course_id = $c;
92         if (isset($_GET['a4a'])){
93                 $use_a4a = true;
94         }
95 } else {
96         $use_a4a = false;
97         if (isset($_REQUEST['to_a4a'])){
98                 $use_a4a = true;
99         } 
100         require(AT_INCLUDE_PATH.'vitals.inc.php');
101         $course_id = $_SESSION['course_id'];
102 }
103 //load the following after vitals is included
104 require(AT_INCLUDE_PATH.'../mods/_standard/tests/classes/testQuestions.class.php');
105 require(AT_INCLUDE_PATH.'../mods/_core/imsafa/classes/A4aExport.class.php');
106 require(AT_INCLUDE_PATH.'../mods/_core/imscc/classes/Weblinks.class.php');
107 require(AT_INCLUDE_PATH.'../mods/_core/imscc/classes/WeblinksExport.class.php');
108
109 $use_cc                  = true;
110 $instructor_id   = $system_courses[$course_id]['member_id'];
111 $course_desc     = htmlspecialchars($system_courses[$course_id]['description'], ENT_QUOTES, 'UTF-8');
112 $course_title    = htmlspecialchars($system_courses[$course_id]['title'], ENT_QUOTES, 'UTF-8');
113 $course_language = $system_courses[$course_id]['primary_language'];
114
115 $courseLanguage =& $languageManager->getLanguage($course_language);
116 //If course language cannot be found, use UTF-8 English
117 //@author harris, Oct 30,2008
118 if ($courseLanguage == null){
119         $courseLanguage =& $languageManager->getLanguage('en');
120 }
121
122 $course_language_charset = $courseLanguage->getCharacterSet();
123 $course_language_code = $courseLanguage->getCode();
124
125 require(AT_INCLUDE_PATH.'classes/zipfile.class.php');                           /* for zipfile */
126 require(AT_INCLUDE_PATH.'classes/vcard.php');                                           /* for vcard */
127 require(AT_INCLUDE_PATH.'classes/XML/XML_HTMLSax/XML_HTMLSax.php');     /* for XML_HTMLSax */
128 require(AT_INCLUDE_PATH.'classes/ContentOutputParser.class.php');   /* to retrieve content resources/medias from at_content[text] */
129 require(AT_INCLUDE_PATH.'../mods/_core/imscc/include/ims_template.inc.php');    /* for ims templates + print_organizations() */
130
131 if (isset($_POST['cancel'])) {
132         $msg->addFeedback('EXPORT_CANCELLED');
133         header('Location: ../index.php');
134         exit;
135 }
136
137 $zipfile = new zipfile(); 
138 $zipfile->create_dir('resources/');
139
140 /* get all the content */
141 $content = array();
142 $paths   = array();
143 $top_content_parent_id = 0;
144
145 $handler=new ContentOutputParser();
146 $parser = new XML_HTMLSax();
147 $parser->set_object($handler);
148 $parser->set_element_handler('openHandler','closeHandler');
149
150 if (authenticate(AT_PRIV_CONTENT, AT_PRIV_RETURN)) {
151         $sql = "SELECT *, UNIX_TIMESTAMP(last_modified) AS u_ts FROM ".TABLE_PREFIX."content WHERE course_id=$course_id ORDER BY content_parent_id, ordering";
152 } else {
153         $sql = "SELECT *, UNIX_TIMESTAMP(last_modified) AS u_ts FROM ".TABLE_PREFIX."content WHERE course_id=$course_id ORDER BY content_parent_id, ordering";
154 }
155 $cid = $_REQUEST['cid'];  //takes care of some system which lost the REQUEST[cid]
156 $result = mysql_query($sql, $db);
157 while ($row = mysql_fetch_assoc($result)) {
158         if (authenticate(AT_PRIV_CONTENT, AT_PRIV_RETURN) || $contentManager->isReleased($row['content_id']) === TRUE) {
159                 $content[$row['content_parent_id']][] = $row;
160                 if ($cid == $row['content_id']) {
161                         $top_content = $row;
162                         $top_content_parent_id = $row['content_parent_id'];
163                 }
164         }
165 }
166
167 if ($cid) {
168         /* filter out the top level sections that we don't want */
169         $top_level = $content[$top_content_parent_id];
170         foreach($top_level as $page) {
171                 if ($page['content_id'] == $cid) {
172                         $content[$top_content_parent_id] = array($page);
173                 } else {
174                         /* this is a page we don't want, so might as well remove it's children too */
175                         unset($content[$page['content_id']]);
176                 }
177         }
178         $ims_course_title = $course_title . ' - ' . $content[$top_content_parent_id][0]['title'];
179 } else {
180         $ims_course_title = $course_title;
181 }
182
183 $imsmanifest_xml = str_replace(array('{COURSE_TITLE}', '{COURSE_DESCRIPTION}', '{COURSE_PRIMARY_LANGUAGE_CHARSET}', '{COURSE_PRIMARY_LANGUAGE_CODE}'), 
184                                                           array($ims_course_title, $course_desc, $course_language_charset, $course_language_code),
185                                                           $ims_template_xml['header']);
186 //debug($imsmanifest_xml);
187 //exit;
188
189 /* get the first content page to default the body frame to */
190 $first = $content[$top_content_parent_id][0];
191
192 $test_ids = array();    //global array to store all the test ids
193
194 //TODO**************BOLOGNA***************REMOVE ME***************************/
195 //Exoprt Forum:
196 global $forum_list, $test_xml_items;;
197 $forum_list = array();
198
199 /* generate the resources and save the HTML files */
200 $used_glossary_terms = array();
201 ob_start();
202 print_organizations($top_content_parent_id, $content, 0, '', array(), $toc_html);
203
204 //Exoprt Forum:
205 print_resources_forum();
206
207 $organizations_str = ob_get_contents();
208 ob_end_clean();
209
210 if (count($used_glossary_terms)) {
211         $used_glossary_terms = array_unique($used_glossary_terms);
212         sort($used_glossary_terms);
213         reset($used_glossary_terms);
214         $terms_xml = '';
215         foreach ($used_glossary_terms as $term) {
216                 $term_key = htmlspecialchars($term, ENT_QUOTES, 'UTF-8');
217                 $glossary[$term_key] = htmlentities($glossary[$term_key], ENT_QUOTES, 'UTF-8');
218                 $glossary[$term_key] = str_replace('&', '&amp;', $glossary[$term_key]);
219                 $terms_xml .= str_replace(      array('{TERM}', '{DEFINITION}'),
220                                                                         array($term_key, $glossary[$term_key]),
221                                                                         $glossary_term_xml);
222         }
223         $glossary_xml = str_replace(array('{GLOSSARY_TERMS}', '{COURSE_PRIMARY_LANGUAGE_CHARSET}'),
224                                                             array($terms_xml, $course_language_charset),
225                                                                 $glossary_xml);
226         //add to resource
227         $resources .= $ims_template_xml['resource_glossary'];
228 } else {
229         unset($glossary_xml);
230 }
231
232 if ($glossary_xml){
233         $glossary_manifest_xml = $ims_template_xml['glossary'];
234 } else {
235         $glossary_manifest_xml = '';
236 }
237
238 /* append the Organizations and Resources to the imsmanifest */
239 $imsmanifest_xml .= str_replace(        array('{ORGANIZATIONS}', '{GLOSSARY}',  '{RESOURCES}', '{TEST_ITEMS}', '{COURSE_TITLE}'),
240                                                                         array($organizations_str, $glossary_manifest_xml,       $resources, $test_xml_items, $ims_course_title),
241                                                                         $ims_template_xml['final']);
242
243 /* generate the vcard for the instructor/author */
244 $sql = "SELECT first_name, last_name, email, website, login, phone FROM ".TABLE_PREFIX."members WHERE member_id=$instructor_id";
245 $result = mysql_query($sql, $db);
246 $vcard = new vCard();
247 if ($row = mysql_fetch_assoc($result)) {
248         $vcard->setName($row['last_name'], $row['first_name'], $row['login']);
249         $vcard->setEmail($row['email']);
250         $vcard->setNote('Originated from an ATutor at '.AT_BASE_HREF.'. See ATutor.ca for additional information.');
251         $vcard->setURL($row['website']);
252
253         $imsmanifest_xml = str_replace('{VCARD}', $vcard->getVCard(), $imsmanifest_xml);
254 } else {
255         $imsmanifest_xml = str_replace('{VCARD}', '', $imsmanifest_xml);
256 }
257
258 /* save the imsmanifest.xml file */
259 //debug($imsmanifest_xml);exit;
260 $zipfile->add_file($imsmanifest_xml, 'imsmanifest.xml');
261
262 if ($glossary_xml) {
263         $zipfile->create_dir('resources/GlossaryItem/');
264         $zipfile->add_file($glossary_xml,  'resources/GlossaryItem/glossary.xml');
265 }
266 $zipfile->close(); // this is optional, since send_file() closes it anyway
267
268 $ims_course_title = str_replace(array(' ', ':'), '_', $ims_course_title);
269 /**
270  * A problem here with the preg_replace below.
271  * Originally was designed to remove all werid symbols to avoid file corruptions.
272  * In UTF-8, all non-english chars are considered to be 'werid symbols'
273  * We can still replace it as is, or add fileid to the filename to avoid these problems
274  * Well then again people won't be able to tell what this file is about
275  * If we are going to take out the preg_replace, some OS might not be able to understand
276  * these characters and will have problems importing.
277  */
278 $ims_course_title = preg_replace("{[^a-zA-Z0-9._-]}","", trim($ims_course_title));
279 $zipfile->send_file($ims_course_title . '_imscc');
280
281 exit;
282 ?>