4347b002020e2088c870dffc8e72b0cdf5d65416
[acontent.git] / docs / home / editor / editor_tab_functions.inc.php
1 <?php
2 /************************************************************************/
3 /* AContent                                                             */
4 /************************************************************************/
5 /* Copyright (c) 2010                                                   */
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
13 if (!defined('TR_INCLUDE_PATH')) { exit; }
14
15 function in_array_cin($strItem, $arItems)
16 {
17    foreach ($arItems as $key => $strValue)
18    {
19        if (strtoupper($strItem) == strtoupper($strValue))
20        {
21                    return $key;
22        }
23    }
24    return false;
25
26
27
28 function get_tabs() {
29         //these are the _AT(x) variable names and their include file
30         /* tabs[tab_id] = array(tab_name, file_name,                accesskey) */
31         $tabs[0] = array('content',                     'edit.inc.php',          'n');
32         $tabs[1] = array('metadata',                    'properties.inc.php',    'p');
33         $tabs[2] = array('alternative_content', 'alternatives.inc.php',  'l');  
34         $tabs[3] = array('tests',               'tests.inc.php',         't');  
35         
36         return $tabs;
37 }
38
39
40 function output_tabs($current_tab, $changes) {
41         global $_base_path;
42         $tabs = get_tabs();
43         $num_tabs = count($tabs);
44 ?>
45         <table class="etabbed-table" border="0" cellpadding="0" cellspacing="0" width="95%">
46         <tr>            
47                 <?php 
48                 for ($i=0; $i < $num_tabs; $i++): 
49                         if ($current_tab == $i):?>
50                                 <td class="editor_tab_selected">
51                                         <?php if ($changes[$i]): ?>
52                                                 <img src="<?php echo $_base_path; ?>images/changes_bullet.gif" alt="<?php echo _AT('usaved_changes_made'); ?>" height="12" width="15" />
53                                         <?php endif; ?>
54                                         <?php echo _AT($tabs[$i][0]); ?>
55                                 </td>
56                                 <td class="tab-spacer">&nbsp;</td>
57                         <?php else: ?>
58                                 <td class="editor_tab">
59                                         <?php if ($changes[$i]): ?>
60                                                 <img src="<?php echo $_base_path; ?>images/changes_bullet.gif" alt="<?php echo _AT('usaved_changes_made'); ?>" height="12" width="15" />
61                                         <?php endif; ?>
62
63                                         <?php echo '<input type="submit" name="button_'.$i.'" value="'._AT($tabs[$i][0]).'" title="'._AT($tabs[$i][0]).' - alt '.$tabs[$i][2].'" class="editor_buttontab" accesskey="'.$tabs[$i][2].'" onmouseover="this.style.cursor=\'pointer\';" '.$clickEvent.' />'; ?>
64                                 </td>
65                                 <td class="tab-spacer">&nbsp;</td>
66                         <?php endif; ?>
67                 <?php endfor; ?>
68                 <td >&nbsp;</td>
69         </tr>
70         </table>
71 <?php }
72 /**
73  * Strips all tags and encodes special characters in the URL
74  * Returns false if the URL is invalid
75  * 
76  * @param string $url
77  * @return mixed - returns a stripped and encoded URL or false if URL is invalid
78  */
79 function isValidURL($url) {
80     if (substr($url,0,4) === 'http') {
81         return filter_var(filter_var($url, FILTER_SANITIZE_STRING), FILTER_VALIDATE_URL);
82     }
83     return false;
84 }
85
86 // save all changes to the DB
87 function save_changes($redir, $current_tab) {
88         global $contentManager, $addslashes, $msg, $_course_id, $_content_id;
89         
90         $_POST['pid']   = intval($_POST['pid']);
91         $_POST['_cid']  = intval($_POST['_cid']);
92         
93         $_POST['alternatives'] = intval($_POST['alternatives']);
94         
95         $_POST['title'] = trim($_POST['title']);
96         $_POST['head']  = trim($_POST['head']);
97         $_POST['use_customized_head']   = isset($_POST['use_customized_head'])?$_POST['use_customized_head']:0;
98         $_POST['body_text']     = trim($_POST['body_text']);
99         $_POST['weblink_text'] = trim($_POST['weblink_text']);
100         $_POST['formatting'] = intval($_POST['formatting']);
101         $_POST['keywords']      = trim($_POST['keywords']);
102         $_POST['test_message'] = trim($_POST['test_message']);
103
104         //if weblink is selected, use it
105         if ($_POST['formatting']==CONTENT_TYPE_WEBLINK) {
106             $url = $_POST['weblink_text'];
107             $validated_url = isValidURL($url);
108         if (!validated_url || $validated_url !== $url) {
109                $msg->addError(array('INVALID_INPUT', _AT('weblink')));
110             } else {
111                     $_POST['body_text'] = $url;
112                     $content_type_pref = CONTENT_TYPE_WEBLINK;
113             }
114         } else {
115                 $content_type_pref = CONTENT_TYPE_CONTENT;
116         }
117
118         /*if (!($release_date = generate_release_date())) {
119                 $msg->addError('BAD_DATE');
120         }*/
121
122 //      if ($_POST['title'] == '') {
123 //              $msg->addError(array('EMPTY_FIELDS', _AT('title')));
124 //      }
125                 
126 //      if (!$msg->containsErrors()) {
127 //              $_POST['title']                 = $addslashes($_POST['title']);
128 //              $_POST['body_text']             = $addslashes($_POST['body_text']);
129 //              $_POST['head']                  = $addslashes($_POST['head']);
130 //              $_POST['keywords']              = $addslashes($_POST['keywords']);
131 //              $_POST['test_message']  = $addslashes($_POST['test_message']);          
132
133                 // add or edit content
134                 if ($_POST['_cid']) {
135                         /* editing an existing page */
136                         $err = $contentManager->editContent($_POST['_cid'], $_POST['title'], $_POST['body_text'], 
137                                                             $_POST['keywords'], $_POST['formatting'], 
138                                                             $_POST['head'], $_POST['use_customized_head'], 
139                                                             $_POST['test_message']);
140                         $cid = $_POST['_cid'];
141                 } else {
142                         /* insert new */
143                         $cid = $contentManager->addContent($_course_id,
144                                                                                                   $_POST['pid'],
145                                                                                                   $_POST['ordering'],
146                                                                                                   $_POST['title'],
147                                                                                                   $_POST['body_text'],
148                                                                                                   $_POST['keywords'],
149                                                                                                   $_POST['related'],
150                                                                                                   $_POST['formatting'],
151                                                                                                   $_POST['head'],
152                                                                                                   $_POST['use_customized_head'],
153                                                                                                   $_POST['test_message'],
154                                                                                                   $content_type_pref);
155                         $_POST['_cid']    = $cid;
156                         $_REQUEST['_cid'] = $cid;
157                 }
158                 if ($cid == 0) return;
159 //      }
160
161         /* insert glossary terms */
162         /*
163         if (is_array($_POST['glossary_defs']) && ($num_terms = count($_POST['glossary_defs']))) {
164                 global $glossary, $glossary_ids, $msg;
165
166                 foreach($_POST['glossary_defs'] as $w => $d) {
167                         $old_w = $w;
168                         $key = in_array_cin($w, $glossary_ids);
169                         $w = urldecode($w);
170                         $d = $addslashes($d);
171
172                         if (($key !== false) && (($glossary[$old_w] != $d) || isset($_POST['related_term'][$old_w])) ) {
173                                 $w = addslashes($w);
174                                 $related_id = intval($_POST['related_term'][$old_w]);
175                                 $sql = "UPDATE ".TABLE_PREFIX."glossary SET definition='$d', related_word_id=$related_id WHERE word_id=$key AND course_id=$_SESSION[course_id]";
176                                 $result = mysql_query($sql, $db);
177                                 $glossary[$old_w] = $d;
178                         } else if ($key === false && ($d != '')) {
179                                 $w = addslashes($w);
180                                 $related_id = intval($_POST['related_term'][$old_w]);
181                                 $sql = "INSERT INTO ".TABLE_PREFIX."glossary VALUES (NULL, $_SESSION[course_id], '$w', '$d', $related_id)";
182
183                                 $result = mysql_query($sql, $db);
184                                 $glossary[$old_w] = $d;
185                         }
186                 }
187         }*/
188         if (isset($_GET['tab'])) {
189                 $current_tab = intval($_GET['tab']);
190         }
191         if (isset($_POST['current_tab'])) {
192                 $current_tab = intval($_POST['current_tab']);
193         }
194
195         // adapted content: save primary content type
196         if (isset($_POST['use_post_for_alt']))
197         {
198                 include_once(TR_INCLUDE_PATH.'classes/DAO/PrimaryResourcesTypesDAO.class.php');
199                 $primaryResourcesTypesDAO = new PrimaryResourcesTypesDAO();
200                 
201                 // 1. delete old primary content type
202                 $sql = "DELETE FROM ".TABLE_PREFIX."primary_resources_types
203                          WHERE primary_resource_id in 
204                                (SELECT DISTINCT primary_resource_id 
205                                   FROM ".TABLE_PREFIX."primary_resources
206                                  WHERE content_id=".$cid."
207                                    AND language_code='".$_SESSION['lang']."')";
208                 $primaryResourcesTypesDAO->execute($sql);
209                 
210                 // 2. insert the new primary content type
211                 $sql = "SELECT pr.primary_resource_id, rt.type_id
212                           FROM ".TABLE_PREFIX."primary_resources pr, ".
213                                  TABLE_PREFIX."resource_types rt
214                          WHERE pr.content_id = ".$cid."
215                            AND pr.language_code = '".$_SESSION['lang']."'";
216                 $all_types_rows = $primaryResourcesTypesDAO->execute($sql);
217                 
218                 if (is_array($all_types_rows)) {
219                         foreach ($all_types_rows as $type) {
220                                 if (isset($_POST['alt_'.$type['primary_resource_id'].'_'.$type['type_id']]))
221                                 {
222                                         $primaryResourcesTypesDAO->Create($type['primary_resource_id'], $type['type_id']);
223 //                                      $sql = "INSERT INTO ".TABLE_PREFIX."primary_resources_types (primary_resource_id, type_id)
224 //                                              VALUES (".$type['primary_resource_id'].", ".$type['type_id'].")";
225 //                                      $result = mysql_query($sql, $db);
226                                 }
227                         }
228                 }
229         }
230         
231         include_once(TR_INCLUDE_PATH.'classes/DAO/ContentTestsAssocDAO.class.php');
232         $contentTestsAssocDAO = new ContentTestsAssocDAO();
233         $test_rows = $contentTestsAssocDAO->getByContent($_POST['_cid']);
234 //      $sql = 'SELECT * FROM '.TABLE_PREFIX."content_tests_assoc WHERE content_id=$_POST[cid]";
235 //      $result = mysql_query($sql, $db);
236         $db_test_array = array();
237         if (is_array($test_rows)) {
238                 foreach ($test_rows as $row) {
239                         $db_test_array[] = $row['test_id'];
240                 }
241         }
242
243         if (is_array($_POST['tid']) && sizeof($_POST['tid']) > 0){
244                 $toBeDeleted = array_diff($db_test_array, $_POST['tid']);
245                 $toBeAdded = array_diff($_POST['tid'], $db_test_array);
246                 //Delete entries
247                 if (!empty($toBeDeleted)){
248                         $tids = implode(",", $toBeDeleted);
249                         $sql = 'DELETE FROM '. TABLE_PREFIX . "content_tests_assoc WHERE content_id=$_POST[cid] AND test_id IN ($tids)";
250                         $contentTestsAssocDAO->execute($sql);
251                 }
252         
253                 //Add entries
254                 if (!empty($toBeAdded)){
255                         foreach ($toBeAdded as $i => $tid){
256                                 $tid = intval($tid);
257 //                              $sql = 'INSERT INTO '. TABLE_PREFIX . "content_tests_assoc SET content_id=$_POST[cid], test_id=$tid";
258 //                              $result = mysql_query($sql, $db);
259                                 if ($contentTestsAssocDAO->Create($_POST['_cid'], $tid) === false){
260                                         $msg->addError('DB_NOT_UPDATED');
261                                 }
262                         }
263                 }
264         } else {
265                 //All tests has been removed.
266                 $contentTestsAssocDAO->DeleteByContentID($_POST['_cid']);
267 //              $sql = 'DELETE FROM '. TABLE_PREFIX . "content_tests_assoc WHERE content_id=$_POST[cid]";
268 //              $result = mysql_query($sql, $db);
269         }
270         //End Add test
271
272         //TODO*******************BOLOGNA****************REMOVE ME**************/
273 /*
274         if(isset($_SESSION['associated_forum']) && !$msg->containsErrors()){
275                 if($_SESSION['associated_forum']=='none'){
276                         $sql = "DELETE FROM ".TABLE_PREFIX."content_forums_assoc WHERE content_id='$_POST[cid]'";
277                         mysql_query($sql,$db);
278                 } else {
279                         $sql = "DELETE FROM ".TABLE_PREFIX."content_forums_assoc WHERE content_id='$_POST[cid]'";
280                         mysql_query($sql,$db);
281                         $associated_forum = $_SESSION['associated_forum'];
282                         for($i=0; $i<count($associated_forum); $i++){
283                                 $sql="INSERT INTO ".TABLE_PREFIX."content_forums_assoc SET content_id='$_POST[cid]',forum_id='$associated_forum[$i]'";
284                                 mysql_query($sql,$db);
285                         }
286                 }
287                 unset($_SESSION['associated_forum']);
288         }
289 */
290         if (!$msg->containsErrors() && $redir) {
291                 $_SESSION['save_n_close'] = $_POST['save_n_close'];
292                 
293                 $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
294                 header('Location: '.basename($_SERVER['PHP_SELF']).'?_cid='.$cid.SEP.'close='.$addslashes($_POST['save_n_close']).SEP.'tab='.$addslashes($_POST['current_tab']).SEP.'displayhead='.$addslashes($_POST['displayhead']).SEP.'alternatives='.$addslashes($_POST['alternatives']));
295                 exit;
296         } else {
297                 return;
298         }
299 }
300 /*
301 function generate_release_date($now = false) {
302         if ($now) {
303                 $day  = date('d');
304                 $month= date('m');
305                 $year = date('Y');
306                 $hour = date('H');
307                 $min  = 0;
308         } else {
309                 $day    = intval($_POST['day']);
310                 $month  = intval($_POST['month']);
311                 $year   = intval($_POST['year']);
312                 $hour   = intval($_POST['hour']);
313                 $min    = intval($_POST['min']);
314         }
315
316         if (!checkdate($month, $day, $year)) {
317                 return false;
318         }
319
320         if (strlen($month) == 1){
321                 $month = "0$month";
322         }
323         if (strlen($day) == 1){
324                 $day = "0$day";
325         }
326         if (strlen($hour) == 1){
327                 $hour = "0$hour";
328         }
329         if (strlen($min) == 1){
330                 $min = "0$min";
331         }
332         $release_date = "$year-$month-$day $hour:$min:00";
333         
334         return $release_date;
335 }
336 */
337 function check_for_changes($row, $row_alternatives) {
338         global $contentManager, $cid, $glossary, $glossary_ids_related, $addslashes;
339
340         $changes = array();
341
342         if ($row && strcmp(trim($addslashes($_POST['title'])), addslashes($row['title']))) {
343                 $changes[0] = true;
344         } else if (!$row && $_POST['title']) {
345                 $changes[0] = true;
346         }
347
348         if ($row && strcmp($addslashes(trim($_POST['head'])), trim(addslashes($row['head'])))) {
349                 $changes[0] = true;
350         } else if (!$row && $_POST['head']) {
351                 $changes[0] = true;
352         }
353
354         if ($row && strcmp($addslashes(trim($_POST['body_text'])), trim(addslashes($row['text'])))) {
355                 $changes[0] = true;
356         } else if (!$row && $_POST['body_text']) {
357                 $changes[0] = true;
358         }
359         
360     if ($row && strcmp($addslashes(trim($_POST['weblink_text'])), trim(addslashes($row['text'])))) {
361         $changes[0] = true;
362     } else if (!$row && $_POST['weblink_text']) {
363         $changes[0] = true;
364     }
365
366         /* use customized head: */
367         if ($row && isset($_POST['use_customized_head']) && ($_POST['use_customized_head'] != $row['use_customized_head'])) {
368                 $changes[0] = true;
369         }
370
371         /* formatting: */
372         if ($row && strcmp(trim($_POST['formatting']), $row['formatting'])) {
373                 $changes[0] = true;
374         } else if (!$row && $_POST['formatting']) {
375                 $changes[0] = true;
376         }
377
378         /* release date: */
379 //      if ($row && strcmp(substr(generate_release_date(), 0, -2), substr($row['release_date'], 0, -2))) {
380 //              /* the substr was added because sometimes the release_date in the db has the seconds field set, which we dont use */
381 //              /* so it would show a difference, even though it should actually be the same, so we ignore the seconds with the -2 */
382 //              /* the seconds gets added if the course was created during the installation process. */
383 //              $changes[1] = true;
384 //      } else if (!$row && strcmp(generate_release_date(), generate_release_date(true))) {
385 //              $changes[1] = true;
386 //      }
387
388         /* related content: */
389 //      $row_related = $contentManager->getRelatedContent($cid);
390 //
391 //      if (is_array($_POST['related']) && is_array($row_related)) {
392 //              $sum = array_sum(array_diff($_POST['related'], $row_related));
393 //              $sum += array_sum(array_diff($row_related, $_POST['related']));
394 //              if ($sum > 0) {
395 //                      $changes[1] = true;
396 //              }
397 //      } else if (!is_array($_POST['related']) && !empty($row_related)) {
398 //              $changes[1] = true;
399 //      }
400
401         /* keywords */
402         if ($row && strcmp(trim($_POST['keywords']), $row['keywords'])) {
403                 $changes[1] = true;
404         }  else if (!$row && $_POST['keywords']) {
405                 $changes[1] = true;
406         }
407
408
409         /* glossary */
410 //      if (is_array($_POST['glossary_defs'])) {
411 //              global $glossary_ids;
412 //              foreach ($_POST['glossary_defs'] as $w => $d) {
413 //
414 //                      $key = in_array_cin($w, $glossary_ids);
415 //                      if ($key === false) {
416 //                              /* new term */
417 //                              $changes[2] = true;
418 //                              break;
419 //                      } else if ($cid && ($d &&($d != $glossary[$glossary_ids[$key]]))) {
420 //                              /* changed term */
421 //                              $changes[2] = true;
422 //                              break;
423 //                      }
424 //              }
425 //
426 //              if (is_array($_POST['related_term'])) {
427 //                      foreach($_POST['related_term'] as $term => $r_id) {
428 //                              if ($glossary_ids_related[$term] != $r_id) {
429 //                                      $changes[2] = true;
430 //                                      break;
431 //                              }
432 //                      }
433 //              }
434 //      }
435
436         /* adapted content */
437         if (isset($_POST['use_post_for_alt']))
438         {
439                 foreach ($_POST as $alt_id => $alt_value) {
440                         if (substr($alt_id, 0 ,4) == 'alt_' && $alt_value != $row_alternatives[$alt_id]){
441                                 $changes[2] = true;
442                                 break;
443                         }
444                 }
445         }
446         
447         /* test & survey */     
448         if ($row && isset($_POST['test_message']) && $_POST['test_message'] != $row['test_message']){
449                 $changes[3] = true;
450         }
451         
452         $content_tests = $contentManager->getContentTestsAssoc($cid);
453         
454         if (isset($_POST['visited_tests'])) {
455                 if (!is_array($content_tests) && is_array($_POST['tid'])) {
456                         $changes[3] = true;
457                 }
458                 if (is_array($content_tests)) {
459                         for ($i = 0; $i < count($content_tests); $i++) {
460                                 if ($content_tests[$i]['test_id'] <> $_POST['tid'][$i]) {
461                                         $changes[3] = true;
462                                         break;
463                                 }
464                         }
465                 }
466         }
467
468         return $changes;
469 }
470
471 function paste_from_file() {
472         global $msg;
473         
474         include_once(TR_INCLUDE_PATH.'../home/classes/ContentUtility.class.php');
475         if ($_FILES['uploadedfile_paste']['name'] == '')        {
476                 $msg->addError('FILE_NOT_SELECTED');
477                 return;
478         }
479         if ($_FILES['uploadedfile_paste']['name']
480                 && (($_FILES['uploadedfile_paste']['type'] == 'text/plain')
481                         || ($_FILES['uploadedfile_paste']['type'] == 'text/html')) )
482                 {
483
484                 $path_parts = pathinfo($_FILES['uploadedfile_paste']['name']);
485                 $ext = strtolower($path_parts['extension']);
486
487                 if (in_array($ext, array('html', 'htm'))) {
488                         $_POST['body_text'] = file_get_contents($_FILES['uploadedfile_paste']['tmp_name']);
489
490                         /* get the <title></title> of this page                         */
491
492                         $start_pos      = strpos(strtolower($_POST['body_text']), '<title>');
493                         $end_pos        = strpos(strtolower($_POST['body_text']), '</title>');
494
495                         if (($start_pos !== false) && ($end_pos !== false)) {
496                                 $start_pos += strlen('<title>');
497                                 $_POST['title'] = trim(substr($_POST['body_text'], $start_pos, $end_pos-$start_pos));
498                         }
499                         unset($start_pos);
500                         unset($end_pos);
501
502                         $_POST['head'] = ContentUtility::getHtmlHeadByTag($_POST['body_text'], array("link", "style", "script")); 
503                         if (strlen(trim($_POST['head'])) > 0)   
504                                 $_POST['use_customized_head'] = 1;
505                         else
506                                 $_POST['use_customized_head'] = 0;
507                         
508                         $_POST['body_text'] = ContentUtility::getHtmlBody($_POST['body_text']); 
509
510                         $msg->addFeedback('FILE_PASTED');
511                 } else if ($ext == 'txt') {
512                         $_POST['body_text'] = file_get_contents($_FILES['uploadedfile_paste']['tmp_name']);
513                         //LAW
514 //                      debug($_POST);
515                         $msg->addFeedback('FILE_PASTED');
516
517                 }
518         } else {
519                 $msg->addError('BAD_FILE_TYPE');
520         }
521
522         return;
523 }
524
525 //for accessibility checker
526 function write_temp_file() {
527         global $_POST, $msg;
528
529         if (defined('TR_FORCE_GET_FILE') && TR_FORCE_GET_FILE) {
530                 $content_base = 'get.php/';
531         } else {
532                 $content_base = 'content/' . $_SESSION['course_id'] . '/';
533         }
534
535         if ($_POST['content_path']) {
536                 $content_base .= $_POST['content_path'] . '/';
537         }
538
539         $file_name = $_POST['_cid'].'.html';
540
541         if ($handle = fopen(TR_CONTENT_DIR . $file_name, 'wb+')) {
542 //              $temp_content = '<h2>'.TR_print(stripslashes($_POST['title']), 'content.title').'</h2>';
543 //
544 //              if ($_POST['body_text'] != '') {
545 //                      $temp_content .= format_content(stripslashes($_POST['body_text']), $_POST['formatting'], $_POST['glossary_defs']);
546 //              }
547 //              $temp_title = $_POST['title'];
548 //
549 //              $html_template = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
550 //                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
551 //              <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
552 //              <head>
553 //                      <base href="{BASE_HREF}" />
554 //                      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
555 //                      <title>{TITLE}</title>
556 //                      <meta name="Generator" content="ATutor accessibility checker file - can be deleted">
557 //              </head>
558 //              <body>
559 //              {CONTENT}
560 //              </body>
561 //              </html>';
562 //
563 //              $page_html = str_replace(       array('{BASE_HREF}', '{TITLE}', '{CONTENT}'),
564 //                                                                      array($content_base, $temp_title, $temp_content),
565 //                                                                      $html_template);
566                 
567                 if (!@fwrite($handle, stripslashes($_POST['body_text']))) {
568                         $msg->addError('FILE_NOT_SAVED');       
569            }
570         } else {
571                 $msg->addError('FILE_NOT_SAVED');
572         }
573         $msg->printErrors();
574 }
575 ?>