move code up one directory
[atutor.git] / mods / _core / properties / lib / course.inc.php
1 <?php
2 /************************************************************************/
3 /* ATutor                                                                                                                               */
4 /************************************************************************/
5 /* Copyright (c) 2002-2010                                              */
6 /* Inclusive Design Institute                                           */
7 /* http://atutor.ca                                                     */
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 if (!defined('AT_INCLUDE_PATH')) { exit; }
14
15 /**
16  * To resize course_icon images
17  * @param       uploaded image source path 
18  * @param       uploaded image path to be saved as
19  * @param       uploaded image's height
20  * @param       uploaded image width
21  * @param       save file with this height
22  * @param       save file with this width
23  * @param       file extension type
24  * @return      true if successful, false otherwise
25  */
26 function resize_image($src, $dest, $src_h, $src_w, $dest_h, $dest_w, $type) {
27         $thumbnail_img = imagecreatetruecolor($dest_w, $dest_h);
28         if ($type == 'gif') {
29                 $source = imagecreatefromgif($src);
30         } else if ($type == 'jpg') {
31                 $source = imagecreatefromjpeg($src);
32         } else {
33                 $source = imagecreatefrompng($src);
34         }
35         
36         $result = imagecopyresampled($thumbnail_img, $source, 0, 0, 0, 0, $dest_w, $dest_h, $src_w, $src_h);
37
38         if ($type == 'gif') {
39                 $result &= imagegif($thumbnail_img, $dest);
40         } else if ($type == 'jpg') {
41                 $result &= imagejpeg($thumbnail_img, $dest, 75);
42         } else {
43                 $result &= imagepng($thumbnail_img, $dest, 7);
44         }
45         return $result;
46 }
47
48 function add_update_course($_POST, $isadmin = FALSE) {
49         require_once(AT_INCLUDE_PATH.'../mods/_core/file_manager/filemanager.inc.php');
50
51         global $addslashes;
52         global $db;
53         global $system_courses;
54         global $MaxCourseSize;
55         global $msg;
56         global $_config;
57         global $_config_defaults;
58         global $stripslashes;
59
60         $Backup = new Backup($db);
61         $missing_fields = array();
62
63         if ($_POST['title'] == '') {
64                 $missing_fields[] = _AT('title');
65         } 
66         if (!$_POST['instructor']) {
67                 $missing_fields[] = _AT('instructor');
68         }
69
70         if ($missing_fields) {
71                 $missing_fields = implode(', ', $missing_fields);
72                 $msg->addError(array('EMPTY_FIELDS', $missing_fields));
73         }
74
75         $_POST['access']                  = $addslashes($_POST['access']);
76         $_POST['title']                   = $addslashes($_POST['title']);
77         $_POST['description']     = $addslashes($_POST['description']);
78         $_POST['hide']                    = $addslashes($_POST['hide']);
79         $_POST['pri_lang']                = $addslashes($_POST['pri_lang']);
80         $_POST['created_date']    = $addslashes($_POST['created_date']);
81         $_POST['copyright']               = $addslashes($_POST['copyright']);
82         $_POST['icon']                    = $addslashes($_POST['icon']);
83         $_POST['banner']                  = $addslashes($_POST['banner']);
84         $_POST['course_dir_name'] = $addslashes($_POST['course_dir_name']);
85
86         $_POST['course']        = intval($_POST['course']);
87         $_POST['notify']        = intval($_POST['notify']);
88         $_POST['hide']          = intval($_POST['hide']);
89         $_POST['instructor']= intval($_POST['instructor']);
90         $_POST['category_parent']       = intval($_POST['category_parent']);
91         $_POST['rss']       = intval($_POST['rss']);
92
93         // Course directory name (aka course slug)
94         if ($_POST['course_dir_name'] != ''){
95                 //validate the course_dir_name, allow only alphanumeric, dash, underscore.
96                 if (preg_match('/^[\w][\w\d\-\_]+$/', $_POST['course_dir_name'])==0){
97                         $msg->addError('COURSE_DIR_NAME_INVALID');
98                 }
99
100                 //check if the course_dir_name is already being used
101                 $sql = 'SELECT COUNT(course_id) as cnt FROM '.TABLE_PREFIX."courses WHERE course_id!=$_POST[course] AND course_dir_name='$_POST[course_dir_name]'";
102                 $result = mysql_query($sql);
103                 $num_of_dir = mysql_fetch_assoc($result);
104                 if (intval($num_of_dir['cnt']) > 0){
105                         $msg->addError('COURSE_DIR_NAME_IN_USE');
106                 }               
107         }
108
109         // Custom icon
110         if ($_FILES['customicon']['name'] != ''){
111                 // Use custom icon instead if it exists
112                 $_POST['icon']    = $addslashes($_FILES['customicon']['name']);
113         } 
114         if ($_FILES['customicon']['error'] == UPLOAD_ERR_FORM_SIZE){
115                 // Check if filesize is too large for a POST
116                 $msg->addError(array('FILE_MAX_SIZE', $_config['prof_pic_max_file_size'] . ' ' . _AT('bytes')));
117         }
118         if ($_POST['release_date']) {
119                 $day_release    = intval($_POST['day_release']);
120                 $month_release  = intval($_POST['month_release']);
121                 $year_release   = intval($_POST['year_release']);
122                 $hour_release   = intval($_POST['hour_release']);
123                 $min_release    = intval($_POST['min_release']);
124
125                 if (!checkdate($month_release, $day_release, $year_release)) { //or date is in the past
126                         $msg->addError('RELEASE_DATE_INVALID');
127                 }
128
129                 if (strlen($month_release) == 1){
130                         $month_release = "0$month_release";
131                 }
132                 if (strlen($day_release) == 1){
133                         $day_release = "0$day_release";
134                 }
135                 if (strlen($hour_release) == 1){
136                         $hour_release = "0$hour_release";
137                 }
138                 if (strlen($min_release) == 1){
139                         $min_release = "0$min_release";
140                 }
141                 $release_date = "$year_release-$month_release-$day_release $hour_release:$min_release:00";
142         } else {
143                 $release_date = "0000-00-00 00:00:00";
144         }
145
146         if ($_POST['end_date']) {
147                 $day_end        = intval($_POST['day_end']);
148                 $month_end      = intval($_POST['month_end']);
149                 $year_end       = intval($_POST['year_end']);
150                 $hour_end       = intval($_POST['hour_end']);
151                 $min_end        = intval($_POST['min_end']);
152
153                 if (!checkdate($month_end, $day_end, $year_end)) { //or date is in the past
154                         $msg->addError('END_DATE_INVALID');
155                 }
156
157                 if (strlen($month_end) == 1){
158                         $month_end = "0$month_end";
159                 }
160                 if (strlen($day_end) == 1){
161                         $day_end = "0$day_end";
162                 }
163                 if (strlen($hour_end) == 1){
164                         $hour_end = "0$hour_end";
165                 }
166                 if (strlen($min_end) == 1){
167                         $min_end = "0$min_end";
168                 }
169                 $end_date = "$year_end-$month_end-$day_end $hour_end:$min_end:00";
170         } else {
171                 $end_date = "0000-00-00 00:00:00";
172         }
173
174         $initial_content_info = explode('_', $_POST['initial_content'], 2);
175         //admin
176         $course_quotas = '';
177         if ($isadmin) {
178                 $instructor             = $_POST['instructor'];
179                 $quota                  = intval($_POST['quota']);
180                 $quota_entered  = intval($_POST['quota_entered']);
181                 $filesize               = intval($_POST['filesize']);
182                 $filesize_entered= intval($_POST['filesize_entered']);
183
184                 //if they checked 'other', set quota=entered value, if it is empty or negative, set to default (-2)
185                 if ($quota == '2') {
186                         if ($quota_entered=='' || empty($quota_entered) || $quota_entered<0 ) {
187                                 $quota = AT_COURSESIZE_DEFAULT;                         
188                         } else {
189                                 $quota = floatval($quota_entered);
190                                 $quota = megabytes_to_bytes($quota);
191                         }
192                 }
193
194                 //if they checked 'other', set filesize=entered value, if it is empty or negative, set to default 
195                 if ($filesize=='2') {
196                         if ($filesize_entered=='' || empty($filesize_entered) || $filesize_entered<0 ) {
197                                 $filesize = AT_FILESIZE_DEFAULT;
198                                 $msg->addFeedback('COURSE_DEFAULT_FSIZE');
199                         } else {
200                                 $filesize = floatval($filesize_entered);
201                                 $filesize = megabytes_to_bytes($filesize);
202                         }
203                 }
204
205                 $course_quotas  =  "max_quota='$quota', max_file_size='$filesize',";
206
207         } else {
208                 $instructor = $_SESSION['member_id'];
209                 if (!$_POST['course'])  {
210                         $course_quotas    =  "max_quota=".AT_COURSESIZE_DEFAULT.", max_file_size=".AT_FILESIZE_DEFAULT.",";
211                         $row = $Backup->getRow($initial_content_info[0], $initial_content_info[1]);
212
213                         if ((count($initial_content_info) == 2) 
214                                 && ($system_courses[$initial_content_info[1]]['member_id'] == $_SESSION['member_id'])) {
215                                 
216                                         if ($MaxCourseSize < $row['contents']['file_manager']) {
217                                                 $msg->addError('RESTORE_TOO_BIG');      
218                                         }
219                         } else {
220                                 $initial_content_info = intval($_POST['initial_content']);
221                         }
222
223                 } else {
224                         unset($initial_content_info);
225                         $course_quotas  =  "max_quota='{$system_courses[$_POST[course]][max_quota]}', max_file_size='{$system_courses[$_POST[course]][max_file_size]}',";
226                 }
227         }
228
229         if ($msg->containsErrors()) {
230                 return FALSE;
231         }
232
233         //display defaults
234         if (!$_POST['course']) {
235                 $menu_defaults = ",home_links='$_config[home_defaults]', main_links='$_config[main_defaults]', side_menu='$_config[side_defaults]'";
236         } else {
237                 $menu_defaults = ',home_links=\''.$system_courses[$_POST['course']]['home_links'].'\', main_links=\''.$system_courses[$_POST['course']]['main_links'].'\', side_menu=\''.$system_courses[$_POST['course']]['side_menu'].'\'';
238         }
239
240         $sql    = "REPLACE INTO ".TABLE_PREFIX."courses SET course_id=$_POST[course], member_id='$_POST[instructor]', access='$_POST[access]', title='$_POST[title]', description='$_POST[description]', course_dir_name='$_POST[course_dir_name]', cat_id='$_POST[category_parent]', content_packaging='$_POST[content_packaging]', notify=$_POST[notify], hide=$_POST[hide], $course_quotas primary_language='$_POST[pri_lang]', created_date='$_POST[created_date]', rss=$_POST[rss], copyright='$_POST[copyright]', icon='$_POST[icon]', banner='$_POST[banner]', release_date='$release_date', end_date='$end_date' $menu_defaults";
241
242         $result = mysql_query($sql, $db);
243         if (!$result) {
244                 echo mysql_error($db);
245                 echo 'DB Error';
246                 exit;
247         }
248         $_SESSION['is_admin'] = 1;
249         $new_course_id = $_SESSION['course_id'] = mysql_insert_id($db);
250         if ($isadmin) {
251                 write_to_log(AT_ADMIN_LOG_REPLACE, 'courses', mysql_affected_rows($db), $sql);
252         }
253
254         if ($isadmin) {
255                 //get current instructor and unenroll from course if different from POST instructor     
256                 $old_instructor = $system_courses[$_POST['course']]['member_id'];
257                 
258                 if ($old_instructor != $_POST['instructor']) {
259                         //remove old from course enrollment
260                         $sql = "DELETE FROM ".TABLE_PREFIX."course_enrollment WHERE course_id=".$_POST['course']." AND member_id=".$old_instructor;
261                         $result = mysql_query($sql, $db);
262                         write_to_log(AT_ADMIN_LOG_DELETE, 'course_enrollment', mysql_affected_rows($db), $sql);
263                 } 
264         }
265
266         //enroll new instructor
267         $sql = "INSERT INTO ".TABLE_PREFIX."course_enrollment VALUES ($_POST[instructor], $new_course_id, 'y', 0, '"._AT('instructor')."', 0)";
268         $result = mysql_query($sql, $db);
269         if ($isadmin) {
270                 write_to_log(AT_ADMIN_LOG_REPLACE, 'course_enrollment', mysql_affected_rows($db), $sql);
271         }
272
273         // create the course content directory
274         $path = AT_CONTENT_DIR . $new_course_id . '/';
275         @mkdir($path, 0700);
276         @copy(AT_CONTENT_DIR . 'index.html', AT_CONTENT_DIR . $new_course_id . '/index.html');
277
278         // create the course backup directory
279         $path = AT_BACKUP_DIR . $new_course_id . '/';
280         @mkdir($path, 0700);
281         @copy(AT_CONTENT_DIR . 'index.html', AT_BACKUP_DIR . $new_course_id . '/index.html');
282
283         /* insert some default content: */
284
285         if (!$_POST['course_id'] && ($_POST['initial_content'] == '1')) {
286                 $contentManager = new ContentManager($db, $new_course_id);
287                 $contentManager->initContent( );
288
289                 $cid = $contentManager->addContent($new_course_id, 0, 1,_AT('welcome_to_atutor'),
290                                                                                         addslashes(_AT('this_is_content')),
291                                                                                         '', '', 1, date('Y-m-d H:00:00'));
292
293                 $announcement = _AT('default_announcement');
294                 
295                 $sql    = "INSERT INTO ".TABLE_PREFIX."news VALUES (NULL, $new_course_id, $instructor, NOW(), 1, '"._AT('welcome_to_atutor')."', '$announcement')";
296                 $result = mysql_query($sql,$db);
297                 
298                 if ($isadmin) {
299                         write_to_log(AT_ADMIN_LOG_INSERT, 'news', mysql_affected_rows($db), $sql);
300                 }
301
302                 /**
303                  * removed - #3098
304                 // create forum for Welcome Course
305                 $sql    = "INSERT INTO ".TABLE_PREFIX."forums VALUES (NULL, '"._AT('forum_general_discussion')."', '', 0, 0, NOW())";
306                 $result = mysql_query($sql,$db);
307
308                 if ($isadmin) {
309                         write_to_log(AT_ADMIN_LOG_INSERT, 'forums', mysql_affected_rows($db), $sql);
310                 }
311
312                 $sql = "INSERT INTO ".TABLE_PREFIX."forums_courses VALUES (LAST_INSERT_ID(), $new_course_id)";
313                 $result = mysql_query($sql,$db);
314
315                 if ($isadmin) {
316                         write_to_log(AT_ADMIN_LOG_INSERT, 'forums_courses', mysql_affected_rows($db), $sql);
317                 }
318                 ***/
319
320         } else if (!$_POST['course'] && (count($initial_content_info) == 2)){
321
322                 $Backup->setCourseID($new_course_id);
323                 $Backup->restore($material = TRUE, 'append', $initial_content_info[0], $initial_content_info[1]);
324         }
325  
326         // custom icon, have to be after directory is created
327 //      $_FILES['customicon'] = $_POST['customicon'];   //copy to $_FILES.
328         if($_FILES['customicon']['tmp_name'] != ''){
329         $_POST['comments'] = trim($_POST['comments']);
330
331         $owner_id = $_SESSION['course_id'];
332         $owner_type = "1";
333         if ($_FILES['customicon']['error'] == UPLOAD_ERR_INI_SIZE) {
334             $msg->addError(array('FILE_TOO_BIG', get_human_size(megabytes_to_bytes(substr(ini_get('upload_max_filesize'), 0, -1)))));
335         } else if (!isset($_FILES['customicon']['name']) || ($_FILES['customicon']['error'] == UPLOAD_ERR_NO_FILE) || ($_FILES['customicon']['size'] == 0)) {
336             $msg->addError('FILE_NOT_SELECTED');
337
338         } else if ($_FILES['customicon']['error'] || !is_uploaded_file($_FILES['customicon']['tmp_name'])) {
339             $msg->addError('FILE_NOT_SAVED');
340         }
341         
342         if (!$msg->containsErrors()) {
343             $_POST['description'] = $addslashes(trim($_POST['description']));
344             $_FILES['customicon']['name'] = addslashes($_FILES['customicon']['name']);
345
346             if ($_POST['comments']) {
347                 $num_comments = 1;
348             } else {
349                 $num_comments = 0;
350             }
351             
352             $path = AT_CONTENT_DIR.$owner_id."/custom_icons/";
353                 
354             if (!is_dir($path)) {
355                 @mkdir($path);
356             }
357                         
358                         // if we can upload custom course icon, it means GD is enabled, no need to check extension again.
359                         $gd_info = gd_info();
360                         $supported_images = array();
361                         if ($gd_info['GIF Create Support']) {
362                                 $supported_images[] = 'gif';
363                         }
364                         if ($gd_info['JPG Support'] || $gd_info['JPEG Support']) {
365                                 $supported_images[] = 'jpg';
366                         }
367                         if ($gd_info['PNG Support']) {
368                                 $supported_images[] = 'png';
369                         }
370
371                         // check if this is a supported file type
372                         $filename   = $stripslashes($_FILES['customicon']['name']);
373                         $path_parts = pathinfo($filename);
374                         $extension  = strtolower($path_parts['extension']);
375                         $image_attributes = getimagesize($_FILES['customicon']['tmp_name']);
376
377                         if ($extension == 'jpeg') {
378                                 $extension = 'jpg';
379                         }
380
381                         // resize the original but don't backup a copy.
382                         $width  = $image_attributes[0];
383                         $height = $image_attributes[1];
384                         $original_img   = $_FILES['customicon']['tmp_name'];
385                         $thumbnail_img  = $path . $_FILES['customicon']['name'];
386
387                         if ($width > $height && $width>79) {
388                                 $thumbnail_height = intval(79 * $height / $width);
389                                 $thumbnail_width  = 79;
390                                 if (!resize_image($original_img, $thumbnail_img, $height, $width, $thumbnail_height, $thumbnail_width, $extension)){
391                                         $msg->addError('FILE_NOT_SAVED');
392                                 }
393                         } else if ($width <= $height && $height > 79) {
394                                 $thumbnail_height= 100;
395                                 $thumbnail_width = intval(100 * $width / $height);
396                                 if (!resize_image($original_img, $thumbnail_img, $height, $width, $thumbnail_height, $thumbnail_width, $extension)){
397                                         $msg->addError('FILE_NOT_SAVED');
398                                 }
399                         } else {
400                                 // no resizing, just copy the image.
401                                 // it's too small to resize.
402                                 copy($original_img, $thumbnail_img);
403                         }
404
405         } else {
406             $msg->addError('FILE_NOT_SAVED');
407             
408         }
409         //header('Location: index.php'.$owner_arg_prefix.'folder='.$parent_folder_id);
410         //exit;
411     }
412     //----------------------------------------
413
414         /* delete the RSS feeds just in case: */
415         if (file_exists(AT_CONTENT_DIR . 'feeds/' . $new_course_id . '/RSS1.0.xml')) {
416                 @unlink(AT_CONTENT_DIR . 'feeds/' . $_POST['course'] . '/RSS1.0.xml');
417         }
418         if (file_exists(AT_CONTENT_DIR . 'feeds/' . $new_course_id . '/RSS2.0.xml')) {
419                 @unlink(AT_CONTENT_DIR . 'feeds/' . $new_course_id . '/RSS2.0.xml');
420         }
421
422         if ($isadmin) {
423                 $_SESSION['course_id'] = -1;
424         }
425
426         $_SESSION['course_title'] = $stripslashes($_POST['title']);
427         return $new_course_id;
428 }
429
430 ?>