Пример #1
0
 /**
  * notify by email the user of the reception of a message
  *
  * @param array of int: $userDataList user identificatin list
  * @param MessageToSend $message message envoy�
  * @param int $messageId identification of the message
  * 
  */
 public function notify($userDataList, $message, $messageId)
 {
     if (!get_conf('mailNotification', TRUE)) {
         return;
     }
     // sender name and email
     if ($message->getSender() == 0) {
         $userData = array('mail' => get_conf('no_reply_mail') ? get_conf('no_reply_mail') : get_conf('administrator_email'), 'firstName' => get_lang('Message from %platformName', array('%platformName' => get_conf('siteName'))), 'lastName' => '');
     } else {
         $userData = claro_get_current_user_data();
     }
     //************************************ IS MANAGER
     $stringManager = false;
     $courseManagers = claro_get_course_manager_id($message->getCourseCode());
     $nbrOfManagers = count($courseManagers);
     for ($countManager = 0; $countManager < $nbrOfManagers; $countManager++) {
         if ($message->getSender() == $courseManagers[$countManager]) {
             $courseData = claro_get_course_data($message->getCourseCode());
             $stringManager = get_block('Course manager of %course%(%courseCode%)', array('%course%' => $courseData['name'], '%courseCode%' => $courseData['officialCode']));
         }
     }
     //---------------------- email subject
     $emailSubject = '[' . get_conf('siteName');
     if (!is_null($message->getCourseCode())) {
         $courseData = claro_get_course_data($message->getCourseCode());
         if ($courseData) {
             $emailSubject .= ' - ' . $courseData['officialCode'];
         }
     }
     $emailSubject .= '] ' . $message->getSubject();
     //------------------------------subject
     /* $altBody = get_lang('If you can\'t read this message go to: ') . rtrim( get_path('rootWeb'), '/' ) . '/claroline/messaging/readmessage.php?messageId=' . $messageId . '&type=received' . "\n\n"
        . '-- '
        . claro_get_current_user_data('lastName') . " " . claro_get_current_user_data('firstName') . "\n"
        . $stringManager
        . "\n\n" . get_conf('siteName') ." <" . get_conf('rootWeb') . '>' . "\n"
        . '   ' . get_lang('Administrator') . ' : ' . get_conf('administrator_name') . ' <' . get_conf('administrator_email') . '>' . "\n"
        ; */
     //-------------------------BODY
     $msgContent = claro_parse_user_text($message->getMessage());
     $urlAppend = get_path('url');
     if (!empty($urlAppend)) {
         $msgContent = preg_replace('!href="' . get_path('url') . '!', 'href="' . rtrim(get_path('rootWeb'), '/') . '/', $msgContent);
         $msgContent = preg_replace('!\\>' . get_path('url') . '!', '>' . get_path('rootWeb'), $msgContent);
     } else {
         $msgContent = preg_replace('!href="/!', 'href="' . rtrim(get_path('rootWeb'), '/') . '/', $msgContent);
     }
     $emailBody = "<html><head></head><body>" . $msgContent . '<br /><br />' . '-- <br />' . get_lang('%firstName %lastName', array('%firstName' => $userData['firstName'], '%lastName' => $userData['lastName'])) . "<br />" . $stringManager . '<br /><br /><a href="' . get_conf('rootWeb') . '">' . get_conf('siteName') . '</a><br />' . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . get_lang('Administrator') . ': <a href="mailto:' . get_conf('administrator_email') . '">' . get_conf('administrator_name') . '</a><br />' . '</body></html>';
     //******************************** END BODY
     //******************************************
     if (empty($userData['mail']) || !is_well_formed_email_address($userData['mail'])) {
         // do not send email for a user with no mail address
         pushClaroMessage('Mail Notification Failed : User has no email or an invalid one : ' . var_export($userData, true) . '!');
         return claro_failure::set_failure(get_lang("Mail Notification Failed : You don't have any email address defined in your user profile or the defined email address is not valid."));
     }
     self::emailNotification($userDataList, $emailBody, $emailSubject, $userData['mail'], get_lang('%firstName %lastName', array('%firstName' => $userData['firstName'], '%lastName' => $userData['lastName'])));
 }
Пример #2
0
 /**
  * check if data are valide
  *
  * @author Sebastien Piraux <*****@*****.**>
  * @return boolean
  */
 public function validate()
 {
     // title is a mandatory element
     $title = strip_tags($this->title);
     if (empty($title)) {
         claro_failure::set_failure('exercise_no_title');
         return false;
     } else {
         // dates : check if start date is lower than end date else we will have a paradox
         if (!is_null($this->endDate) && $this->endDate <= $this->startDate) {
             claro_failure::set_failure('exercise_incorrect_dates');
             return false;
         }
     }
     return true;
     // no errors, form is valide
 }
Пример #3
0
/**
 * Returns data for the announcement  of the given id of the given or current course.
 *
 * @param integer   $announcement_id id the requested announcement
 * @param string    $course_id       sysCode of the course (leaveblank for current course)
 * @return array(id, title, content, visibility, rank) of the announcement
 * @since 1.7
 */
function announcement_get_item($announcement_id, $course_id = null)
{
    $tbl = claro_sql_get_course_tbl(claro_get_course_db_name_glued($course_id));
    $sql = "SELECT id,\n                   title,\n                   contenu      AS content,\n                   visibleFrom,\n                   visibleUntil,\n                   visibility,\n                   ordre        AS rank\n            FROM  `" . $tbl['announcement'] . "`\n            WHERE id = " . (int) $announcement_id;
    $announcement = claro_sql_query_get_single_row($sql);
    if ($announcement) {
        return $announcement;
    } else {
        return claro_failure::set_failure('ANNOUNCEMENT_UNKNOW');
    }
}
Пример #4
0
/**
 * unzip safly a zipfile
 *
 * @author Hugues Peeters <*****@*****.**>
 *
 * @param string $fileName file name of zip
 * @param string $filePath file path of zip
 * @param string $extractPath
 * @param integer $maxFilledSpace (byte) count  of byte size aivailable
 * @param boolean $allowPHP whether True the file can't contain php or phtml files
 * @return true
 * @throws claro_failure on error
 */
function treat_secure_file_unzip($fileName, $filePath, $extractPath, $maxFilledSpace, $allowPHP = false)
{
    $zipFile = new pclZip($fileName);
    // Check the zip content (real size and file extension)
    $zipContentArray = $zipFile->listContent();
    if (!is_array($zipContentArray)) {
        return false;
    }
    foreach ($zipContentArray as $thisContent) {
        if (!$allowPHP) {
            if (preg_match('~.(php.?|phtml)$~i', $thisContent['filename'])) {
                return claro_failure::set_failure(get_lang('The zip file can not contain .PHP files'));
            }
        }
        if (!isset($realFileSize)) {
            $realFileSize = 0;
        }
        $realFileSize += $thisContent['size'];
    }
    if (!enough_size($realFileSize, $extractPath, $maxFilledSpace)) {
        return claro_failure::set_failure(get_lang('The upload has failed. There is not enough space in your directory'));
    }
    $extractedFileNameList = $zipFile->extract(PCLZIP_OPT_PATH, $extractPath . $filePath, PCLZIP_OPT_SET_CHMOD, CLARO_FILE_PERMISSIONS);
    if (is_array($extractedFileNameList)) {
        return $extractedFileNameList;
    } else {
        return false;
    }
}
Пример #5
0
/**
 * edit a bloc for information category
 *
 * @param  integer $def_id,
 * @param  integer $user_id,
 * @param  string  $user_ip, DEFAULT $REMOTE_ADDR
 * @param  string  $content ; if empty call delete the bloc
 * @return boolean true if succeed, else bolean false
 */
function claro_user_info_edit_cat_content($def_id, $user_id, $content = "", $user_ip = "", $course_id = NULL)
{
    $tbl_cdb_names = claro_sql_get_course_tbl(claro_get_course_db_name_glued($course_id));
    $tbl_userinfo_content = $tbl_cdb_names['userinfo_content'];
    if (empty($user_ip)) {
        global $REMOTE_ADDR;
        $user_ip = $REMOTE_ADDR;
    }
    if (0 == (int) $user_id || 0 == (int) $def_id) {
        return claro_failure::set_failure('id_nul');
    }
    $content = trim($content);
    if ('' == trim($content)) {
        return claro_user_info_cleanout_cat_content($user_id, $def_id);
    }
    $sql = "UPDATE `" . $tbl_userinfo_content . "` SET\n            `content`    = '" . claro_sql_escape($content) . "',\n            `ed_ip`        = '" . $user_ip . "',\n            `ed_date`    = now()\n            WHERE def_id = " . (int) $def_id . "\n              AND user_id = " . (int) $user_id;
    claro_sql_query($sql);
    return true;
}
Пример #6
0
/**
 * Return course list which have an unexisting category as parent
 *
 * @author Christophe Gesché <*****@*****.**>
 * @since 1.8
 *
 * @return array('Course code'=>string, 'Unknow faculty'=>string)
 */
function checkCourseOwnance()
{
    $tbl_mdb_names = claro_sql_get_main_tbl();
    $sql = "SELECT c.code    AS `Course code`,\n                   c.faculte AS `Unknow faculty`\n        FROM  `" . $tbl_mdb_names['course'] . "`       AS c\n        LEFT JOIN  `" . $tbl_mdb_names['category'] . "` AS f\n        ON c.FACULTE = f.code\n        WHERE f.id IS null ";
    if (false !== ($res = claro_sql_query_fetch_all($sql))) {
        return $res;
    } else {
        return claro_failure::set_failure('QUERY_ERROR_' . __LINE__);
    }
}
Пример #7
0
/**
 * search files or directory whose name fit a pattern
 *
 * @param string $searchPattern - Perl compatible regex to search on file name
 * @param string $baseDirPath - directory path where to start the search
 * @param string $fileType (optional) - filter allowing to restrict search
 *        on files or directories (allowed value are 'ALL', 'FILE', 'DIR').
 * @param array $excludedPathList (optional) - list of files or directories
 *        that have to be excluded from the search
 * @return array path list of the files fitting the search pattern
 */
function claro_search_file($searchPattern, $baseDirPath, $recursive = false, $fileType = 'ALL', $excludedPathList = array())
{
    $searchResultList = array();
    //$baseDirPath unexisting is  a devel error or a data incoherence,
    if (!file_exists($baseDirPath)) {
        // TODO would push an error but return empty array instead of false.
        return claro_failure::set_failure('BASE_DIR_DONT_EXIST');
    }
    $dirPt = opendir($baseDirPath);
    //can't be false as if (! file_exists($baseDirPath))  have make a good control
    //if ( ! $dirPt) return false;
    while ($fileName = readdir($dirPt)) {
        $filePath = $baseDirPath . '/' . $fileName;
        if ($fileName == '.' || $fileName == '..' || in_array('/' . ltrim($filePath, '/'), $excludedPathList)) {
            continue;
        } else {
            if (is_dir($filePath)) {
                $dirList[] = $filePath;
            }
            if ($fileType == 'DIR' && is_file($filePath)) {
                continue;
            }
            if ($fileType == 'FILE' && is_dir($filePath)) {
                continue;
            }
            if (preg_match($searchPattern, $fileName)) {
                $searchResultList[] = $filePath;
            }
        }
    }
    closedir($dirPt);
    if ($recursive && isset($dirList) && count($dirList) > 0) {
        foreach ($dirList as $thisDir) {
            $searchResultList = array_merge($searchResultList, claro_search_file($searchPattern, $thisDir, $recursive, $fileType, $excludedPathList));
        }
    }
    return $searchResultList;
}
 function announcement_get_item($announcement_id, $course_id = NULL)
 {
     $tbl = claro_sql_get_course_tbl(claro_get_course_db_name_glued($course_id));
     $sql = "SELECT                id,\n\t\t\t\t\t\t\t\t\t  title,\n\t\t\t\t\t   contenu     AS content,\n\t\t\t\t\t\t   temps   AS `time`,\n\t\t\t\t\t\t\t\t\t  visibility,\n\t\t\t\t\t   ordre       AS rank\n\t\t\t\tFROM  `" . $tbl['announcement'] . "`\n\t\t\t\tWHERE id=" . (int) $announcement_id;
     $announcement = claro_sql_query_get_single_row($sql);
     if ($announcement) {
         return $announcement;
     } else {
         return claro_failure::set_failure('ANNOUNCEMENT_UNKNOW');
     }
 }
Пример #9
0
/**
 * Change change rank of a category
 *
 * @param integer $currCatId id  of category
 * @param string $direction (UP|DOWN)
 * @return boolean true wheater success
 */
function move_category_rank($currCatId, $direction)
{
    if (strtoupper($direction) == 'UP') {
        $operator = ' < ';
        $orderDirection = ' DESC ';
    } elseif (strtoupper($direction) == 'DOWN') {
        $operator = ' > ';
        $orderDirection = ' ASC ';
    } else {
        return claro_failure::set_failure('WRONG DIRECTION');
    }
    $tbl_cdb_names = claro_sql_get_course_tbl();
    $tbl_forum_categories = $tbl_cdb_names['bb_categories'];
    $categorySettingList = get_category_settings($currCatId);
    $currCatRank = $categorySettingList['cat_order'];
    $tbl_cdb_names = claro_sql_get_course_tbl();
    $tbl_forum_categories = $tbl_cdb_names['bb_categories'];
    $sql = 'SELECT cat_id AS id, cat_order AS rank
            FROM `' . $tbl_forum_categories . '`
            WHERE cat_order ' . $operator . ' ' . (int) $currCatRank . '
            ORDER BY cat_order ' . $orderDirection . ' LIMIT 1';
    $adjacentCategory = claro_sql_query_get_single_row($sql);
    if (is_array($adjacentCategory)) {
        // SWAP BOTH RANK
        $sql = 'UPDATE `' . $tbl_forum_categories . '`
                SET cat_order = ' . (int) $adjacentCategory['rank'] . '
                WHERE cat_id = ' . (int) $currCatId;
        if (claro_sql_query($sql) == false) {
            return false;
        }
        $sql = 'UPDATE `' . $tbl_forum_categories . '`
                SET cat_order = ' . (int) $currCatRank . '
                WHERE cat_id = ' . (int) $adjacentCategory['id'];
        if (claro_sql_query($sql) == false) {
            return false;
        }
    } else {
        return false;
    }
    return true;
}
Пример #10
0
function restore_course_repository($courseId, $courseRepository)
{
    global $urlAppend;
    if (is_writable($courseRepository)) {
        umask(0);
        /**
            create directory for new tools of claroline 1.5
        */
        if (!is_dir($courseRepository)) {
            mkdir($courseRepository, CLARO_FILE_PERMISSIONS);
        }
        if (!is_dir($courseRepository . '/chat')) {
            mkdir($courseRepository . '/chat', CLARO_FILE_PERMISSIONS);
        }
        if (!is_dir($courseRepository . '/modules')) {
            mkdir($courseRepository . '/modules', CLARO_FILE_PERMISSIONS);
        }
        if (!is_dir($courseRepository . '/scormPackages')) {
            mkdir($courseRepository . '/scormPackages', CLARO_FILE_PERMISSIONS);
        }
        // build index.php of course
        $fd = fopen($courseRepository . '/index.php', 'w');
        if (!$fd) {
            return claro_failure::set_failure('CANT_CREATE_COURSE_INDEX');
        }
        $string = '<?php ' . "\n" . 'header (\'Location: ' . $urlAppend . '/claroline/course/index.php?cid=' . claro_htmlspecialchars($courseId) . '\') ;' . "\n" . '?' . '>' . "\n";
        if (!fwrite($fd, $string)) {
            return false;
        }
        if (!fclose($fd)) {
            return false;
        }
        $fd = fopen($courseRepository . '/group/index.php', 'w');
        if (!$fd) {
            return false;
        }
        $string = '<?php session_start(); ?' . '>';
        if (!fwrite($fd, $string)) {
            return false;
        }
        return true;
    } else {
        printf('repository %s not writable', $courseRepository);
        return 0;
    }
}
Пример #11
0
/**
 * Recursive function to get the full categories path of a specified categorie.
 *
 * @param table of all the categories, 2 dimension tables, first dimension for cat codes, second for names,
 *  parent's cat code.
 * @param $catcode   string the categorie we want to have its full path from root categorie
 * @param $separator string
 * @return void
 */
function get_full_path($categories, $catcode = NULL, $separator = ' > ')
{
    //Find parent code
    $parent = null;
    foreach ($categories as $currentCat) {
        if ($currentCat['code'] == $catcode) {
            $parent = $currentCat['parent'];
            $childTreePos = $currentCat['treePos'];
            // for protection anti loop
        }
    }
    // RECURSION : find parent categorie in table
    if ($parent == null) {
        return $catcode;
    }
    foreach ($categories as $currentCat) {
        if ($currentCat['code'] == $parent) {
            if ($currentCat['treePos'] >= $childTreePos) {
                return claro_failure::set_failure('loop_in_structure');
            }
            if ($parent == $catcode) {
                return claro_failure::set_failure('loop_in_structure');
            }
            return get_full_path($categories, $parent, $separator) . $separator . $catcode;
        }
    }
}
Пример #12
0
 public function importAttachment($importedFilePath)
 {
     // copy file in a tmp directory known by object,
     // attached file will be copied to its final destination when saving question
     $dir = $this->tmpQuestionDirSys;
     $filename = basename($importedFilePath);
     if (!is_dir($dir)) {
         // create it
         if (!claro_mkdir($dir, CLARO_FILE_PERMISSIONS)) {
             claro_failure::set_failure('cannot_create_tmp_dir');
             return false;
         }
     }
     if (claro_move_file($importedFilePath, $dir . $filename)) {
         $this->attachment = $filename;
         return true;
     } else {
         return false;
     }
 }
Пример #13
0
/**
 * Get unique keys of a course.
 *
 * @param  string $course_id (optionnal)  If not set, it use the current course
 *         will be taken.
 * @return array list of unique keys (sys, db & path) of a course
 * @author Christophe Gesche <*****@*****.**>
 * @since 1.7
 */
function claro_get_group_data($context, $force = false)
{
    if (is_array($context) && array_key_exists(CLARO_CONTEXT_COURSE, $context)) {
        $cid = $context[CLARO_CONTEXT_COURSE];
    }
    if (is_array($context) && array_key_exists(CLARO_CONTEXT_GROUP, $context)) {
        $gid = $context[CLARO_CONTEXT_GROUP];
    }
    $groupDataList = null;
    static $cachedGroupDataList = null;
    /*
        if ( ! $force)
        {
            if ( $cachedGroupDataList && $groupId == $cachedGroupDataList['sysCode'] )
            {
                $groupDataList = $cachedGroupDataList;
            }
            elseif ( ( is_null($groupId) && $GLOBALS['_gid']) )
            {
                $groupDataList = $GLOBALS['_group'];
            }
        }
    */
    if (!$groupDataList) {
        $tbl_c_names = claro_sql_get_course_tbl(claro_get_course_db_name_glued($cid));
        $sql = "SELECT g.id               AS id          ,\n                       g.name             AS name        ,\n                       g.description      AS description ,\n                       g.tutor            AS tutorId     ,\n                       f.forum_id         AS forumId     ,\n                       g.secretDirectory  AS directory   ,\n                       g.maxStudent       AS maxMember\n\n                FROM `" . $tbl_c_names['group_team'] . "`      g\n                LEFT JOIN `" . $tbl_c_names['bb_forums'] . "`   f\n\n                   ON    g.id = f.group_id\n                WHERE    `id` = '" . (int) $gid . "'";
        $groupDataList = claro_sql_query_get_single_row($sql);
        if (!$groupDataList) {
            return claro_failure::set_failure('group_not_found');
        }
        $cachedGroupDataList = $groupDataList;
        // cache for the next time ...
    }
    return $groupDataList;
}
Пример #14
0
/**
 * Check if the password chosen by the user is not too much easy to find
 *
 * @author Hugues Peeters <*****@*****.**>
 *
 * @param string requested password
 * @param array list of other values of the form we wnt to check the password
 * @return boolean true if not too much easy to find
 *
 */
function is_password_secure_enough($requestedPassword, $forbiddenValueList)
{
    foreach ($forbiddenValueList as $thisValue) {
        if (strtoupper($requestedPassword) == strtoupper($thisValue)) {
            return claro_failure::set_failure('ERROR_CODE_too_easy');
        }
        if (!empty($requestedPassword) && !empty($thisValue) && (false !== stristr($requestedPassword, $thisValue) || false !== stristr($thisValue, $requestedPassword))) {
            return claro_failure::set_failure('ERROR_CODE_too_easy');
        }
        if (function_exists('soundex') && soundex($requestedPassword) == soundex($thisValue)) {
            return claro_failure::set_failure('ERROR_CODE_too_easy');
        }
    }
    return true;
}
Пример #15
0
/**
 * return data for the event  of the given id of the given or current course
 *
 * @param integer $event_id id the requested event
 * @param string  $courseCode sysCode of the course (leaveblank for current course)
 * @author Christophe Gesche <*****@*****.**>
 * @return array(`id`, `title`, `content`, `dayAncient`, `hourAncient`, `lastingAncient`) of the event
 * @since  1.7
 */
function agenda_get_item($event_id, $courseCode = null)
{
    $tbl_c_names = claro_sql_get_course_tbl(claro_get_course_db_name_glued($courseCode));
    $tbl_calendar_event = $tbl_c_names['calendar_event'];
    $sql = "SELECT `id`,\n                   `titre`      AS `title`,\n                   `contenu`    AS `content`,\n                   `day`        AS `dayAncient`,\n                   `hour`       AS `hourAncient`,\n                   `lasting`    AS `lastingAncient`,\n                   `speakers`     AS `speakers`,\n                   `location`   AS `location`\n            FROM `" . $tbl_calendar_event . "`\n            WHERE `id` = " . (int) $event_id;
    $event = claro_sql_query_get_single_row($sql);
    if ($event) {
        return $event;
    } else {
        return claro_failure::set_failure('EVENT_ENTRY_UNKNOW');
    }
}
Пример #16
0
/**
 * Execute course related SQL files by replacing __CL__COURSE__ place holder
 * with given course code, then executing the file
 * @param   string file path to the sql file
 * @param   string courseId course sys code
 * @return  boolean
 * @author  Frederic Minne <*****@*****.**>
 * @throws  SQL_FILE_NOT_FOUND, SQL_QUERY_FAILED
 */
function execute_sql_file_in_course($file, $courseId)
{
    if (file_exists($file)) {
        $sql = file_get_contents($file);
        if (!empty($courseId)) {
            $currentCourseDbNameGlu = claro_get_course_db_name_glued($courseId);
            $sql = str_replace('__CL_COURSE__', $currentCourseDbNameGlu, $sql);
        }
        if (!claro_sql_multi_query($sql)) {
            return claro_failure::set_failure('SQL_QUERY_FAILED');
        } else {
            return true;
        }
    } else {
        return claro_failure::set_failure('SQL_FILE_NOT_FOUND');
    }
}
Пример #17
0
/**
 * Read a file from the file system and echo it
 *
 * Workaround for the readfile bug in PHP 5.0.4 and with host where
 * PHP readfile is deactivated
 *
 * @param   string $path file path
 * @param   boolean $retbytes return file length (default true)
 * @return  int file length if $retbytes
 *          boolean true on success if not $retbytes
 *          boolean false on failure
 *          set claro_failure on failure
 * @deprecated since Claroline 1.9 and PHP 5.1
 */
function claro_readfile($path, $retbytes = true)
{
    if (!file_exists($path)) {
        return claro_failure::set_failure('FILE_NOT_FOUND');
    }
    $chunksize = 1 * (1024 * 1024);
    // how many bytes per chunk
    $buffer = '';
    $cnt = 0;
    $handle = fopen($path, 'rb');
    if (!$handle) {
        return claro_failure::set_failure('CANNOT_OPEN_FILE');
    }
    while (!feof($handle)) {
        $buffer = fread($handle, $chunksize);
        if ($buffer === false) {
            return claro_failure::set_failure('CANNOT_READ_FILE');
        }
        echo $buffer;
        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }
    $status = fclose($handle);
    if ($retbytes && $status) {
        return $cnt;
    } else {
        return $status;
    }
}
Пример #18
0
/**
 *  Helper function to read, validate and complete module information from
 *  a manifest file
 */
function readModuleManifest($modulePath)
{
    $manifestPath = $modulePath . '/manifest.xml';
    if (!file_exists($manifestPath)) {
        return claro_failure::set_failure(get_lang('Manifest missing : %filename', array('%filename' => $manifestPath)));
    } else {
        $parser = new ModuleManifestParser();
        $moduleInfo = $parser->parse($manifestPath);
        if (!checkModuleInfo($moduleInfo)) {
            return false;
        } else {
            return $moduleInfo;
        }
    }
}
Пример #19
0
/**
 * build the rss file and place it in directory
 *
 * @param array $context context of claroline
 * @param string $calType : ics,xcs,rdf
 * @return string ical file path
 */
function buildICal($context, $calType = 'ics')
{
    if (is_array($context) && count($context) > 0) {
        $iCalRepositorySys = get_path('rootSys') . get_conf('iCalRepositoryCache', 'tmp/cache/iCal/');
        if (!file_exists($iCalRepositorySys)) {
            require_once dirname(__FILE__) . '/fileManage.lib.php';
            claro_mkdir($iCalRepositorySys, CLARO_FILE_PERMISSIONS, true);
            if (!file_exists($iCalRepositorySys)) {
                claro_failure::set_failure('CANT_CREATE_ICAL_DIR');
            }
        }
        $iCal = (object) new iCal('', 0, $iCalRepositorySys);
        // (ProgrammID, Method (1 = Publish | 0 = Request), Download Directory)
        $toolLabelList = ical_get_tool_compatible_list();
        foreach ($toolLabelList as $toolLabel) {
            if (is_tool_activated_in_course(get_tool_id_from_module_label($toolLabel), $context[CLARO_CONTEXT_COURSE])) {
                if (!is_module_installed_in_course($toolLabel, $context[CLARO_CONTEXT_COURSE])) {
                    install_module_in_course($toolLabel, $context[CLARO_CONTEXT_COURSE]);
                }
                $icalToolLibPath = get_module_path($toolLabel) . '/connector/ical.write.cnr.php';
                $icalToolFuncName = $toolLabel . '_write_ical';
                if (file_exists($icalToolLibPath)) {
                    require_once $icalToolLibPath;
                    if (function_exists($icalToolFuncName)) {
                        $iCal = call_user_func($icalToolFuncName, $iCal, $context);
                    }
                }
            }
        }
        $iCalFilePath = $iCalRepositorySys;
        if (array_key_exists(CLARO_CONTEXT_COURSE, $context)) {
            $iCalFilePath .= $context[CLARO_CONTEXT_COURSE] . '.';
        }
        if (array_key_exists(CLARO_CONTEXT_GROUP, $context)) {
            $iCalFilePath .= 'g' . $context[CLARO_CONTEXT_GROUP] . '.';
        }
        if ('ics' == $calType || get_conf('iCalGenStandard', true)) {
            $stdICalFilePath = $iCalFilePath . 'ics';
            if (false !== ($fpICal = @fopen($stdICalFilePath, 'w'))) {
                fwrite($fpICal, $iCal->getOutput('ics'));
                fclose($fpICal);
            }
        }
        if ('xcs' == $calType || get_conf('iCalGenXml', true)) {
            $xmlICalFilePath = $iCalFilePath . 'xml';
            if (false !== ($fpICal = @fopen($xmlICalFilePath, 'w'))) {
                fwrite($fpICal, $iCal->getOutput('xcs'));
                fclose($fpICal);
            }
        }
        if ('rdf' == $calType || get_conf('iCalGenRdf', false)) {
            $rdfICalFilePath = $iCalFilePath . 'rdf';
            if (false !== ($fpICal = @fopen($rdfICalFilePath, 'w'))) {
                fwrite($fpICal, $iCal->getOutput('rdf'));
                fclose($fpICal);
            }
        }
        switch ($calType) {
            case 'xcs':
                return $xmlICalFilePath;
                break;
            case 'rdf':
                return $rdfICalFilePath;
                break;
            default:
                return $stdICalFilePath;
                break;
        }
    }
    return false;
}
Пример #20
0
 /**
  * check if data are valide
  *
  * @author Laurence Dumortier <*****@*****.**>
  * @return boolean
  */
 public function validate()
 {
     // title is a mandatory element
     $title = strip_tags($this->title);
     if (empty($title)) {
         claro_failure::set_failure('category_no_title');
         return false;
     }
     if ($this->titleAlreadyExists()) {
         claro_failure::set_failure('category_already_exists');
         return false;
     }
     return true;
     // no errors, form is valide
 }
Пример #21
0
/**
 * Execute SQL files at course creation
 */
function execute_sql_at_course_creation($sqlPath, $courseDbName)
{
    if (file_exists($sqlPath)) {
        $sql = file_get_contents($sqlPath);
        $currentCourseDbNameGlu = get_conf('courseTablePrefix') . $courseDbName . get_conf('dbGlu');
        $sql = str_replace('__CL_COURSE__', $currentCourseDbNameGlu, $sql);
        if (!claro_sql_multi_query($sql)) {
            return claro_failure::set_failure('SQL_QUERY_FAILED');
        } else {
            return true;
        }
    } else {
        return claro_failure::set_failure('SQL_FILE_NOT_FOUND');
    }
}
Пример #22
0
/**
 * Add common info about a module in main module registry.
 * In Claroline this  info is split in two type of info
 * into two tables :
 * * module  for really use info,
 * * module_info for descriptive info
 *
 * @param array $module_info.
 * @return int moduleId in the registry.
 */
function register_module_core($module_info)
{
    $tbl = claro_sql_get_tbl(array('module', 'module_info', 'tool', 'module_contexts'));
    $tbl_name = claro_sql_get_main_tbl();
    $missingElement = array_diff(array('LABEL', 'NAME', 'TYPE'), array_keys($module_info));
    if (count($missingElement) > 0) {
        return claro_failure::set_failure(get_lang('Missing elements in module Manifest : %MissingElements', array('%MissingElements' => implode(',', $missingElement))));
    }
    if (isset($module_info['ENTRY'])) {
        $script_url = $module_info['ENTRY'];
    } else {
        $script_url = 'entry.php';
    }
    $sql = "INSERT INTO `" . $tbl['module'] . "`\n            SET label      = '" . claro_sql_escape($module_info['LABEL']) . "',\n                name       = '" . claro_sql_escape($module_info['NAME']) . "',\n                type       = '" . claro_sql_escape($module_info['TYPE']) . "',\n                script_url = '" . claro_sql_escape($script_url) . "'\n                ";
    $moduleId = claro_sql_query_insert_id($sql);
    $sql = "INSERT INTO `" . $tbl['module_info'] . "`\n            SET module_id      = " . (int) $moduleId . ",\n                version        = '" . claro_sql_escape($module_info['VERSION']) . "',\n                author         = '" . claro_sql_escape($module_info['AUTHOR']['NAME']) . "',\n                author_email   = '" . claro_sql_escape($module_info['AUTHOR']['EMAIL']) . "',\n                author_website = '" . claro_sql_escape($module_info['AUTHOR']['WEB']) . "',\n                website        = '" . claro_sql_escape($module_info['WEB']) . "',\n                description    = '" . claro_sql_escape($module_info['DESCRIPTION']) . "',\n                license        = '" . claro_sql_escape($module_info['LICENSE']) . "'";
    claro_sql_query($sql);
    foreach ($module_info['CONTEXTS'] as $context) {
        $sql = "INSERT INTO `{$tbl['module_contexts']}`\n" . "SET\n" . "  `module_id` = " . (int) $moduleId . ",\n" . "  `context` = '" . claro_sql_escape($context) . "'";
        claro_sql_query($sql);
    }
    return $moduleId;
}
Пример #23
0
function claro_is_module_allowed()
{
    if (!array_key_exists('tlabelReq', $GLOBALS)) {
        return claro_failure::set_failure('MISSING TOOL LABEL');
    }
    $moduleLabel = $GLOBALS['tlabelReq'];
    $moduleData = get_module_data($moduleLabel);
    if ($moduleData['type'] == 'tool') {
        $contextList = get_module_context_list($moduleLabel);
        // pushClaroMessage(var_export(iterator_to_array($contextList), true),'kernel');
        if (!claro_is_in_a_course() && in_array('platform', iterator_to_array($contextList))) {
            return get_module_data($moduleLabel, 'activation') == 'activated';
        }
        // if a course tool, use claro_is_tool_allowed
        return claro_is_tool_allowed();
    } else {
        // if an applet "tool", return true if activated
        // and let module manage it's access by itself
        return $moduleData['activation'] == 'activated';
    }
}
Пример #24
0
 /**
  * check if data are valide
  *
  * @author Sebastien Piraux <*****@*****.**>
  * @return boolean
  */
 public function validate()
 {
     // title is a mandatory element
     $title = trim(strip_tags($this->title));
     if (empty($title)) {
         claro_failure::set_failure('assignment_no_title');
         return false;
     } else {
         // check if title already exists
         if ($this->id == -1) {
             // insert
             $sql = "SELECT `title`\n                        FROM `" . $this->tblAssignment . "`\n                        WHERE `title` = '" . claro_sql_escape($this->title) . "'";
         } else {
             // update
             $sql = "SELECT `title`\n                        FROM `" . $this->tblAssignment . "`\n                        WHERE `title` = '" . claro_sql_escape($this->title) . "'\n                        AND `id` != " . (int) $this->id;
         }
         $query = claro_sql_query($sql);
         if (mysql_num_rows($query) != 0) {
             claro_failure::set_failure('assignment_title_already_exists');
             return false;
         }
     }
     // dates : check if start date is lower than end date else we will have a paradox
     if ($this->endDate <= $this->startDate) {
         claro_failure::set_failure('assignment_incorrect_dates');
         return false;
     }
     return true;
     // no errors, form is valide
 }
Пример #25
0
/**
 * This function empties all classes,
 * remove link between classes and users
 * delete related users from related courses
 */
function empty_all_class()
{
    $tbl = claro_sql_get_main_tbl();
    $sql = "\n        SELECT id FROM `" . $tbl['class'] . "`";
    $searchResultList = claro_sql_query_fetch_all($sql);
    foreach ($searchResultList as $thisClass) {
        $classId = $thisClass['id'];
        // find all the students enrolled in that class
        $sql2 = "\n            SELECT user_id from `" . $tbl['rel_class_user'] . "`\n            WHERE class_id = '" . claro_sql_escape($classId) . "'";
        $thisClassUser = claro_sql_query_fetch_all($sql2);
        // Find all the courses to whom the class is enrolled
        $sql2 = "\n            SELECT courseId\n            FROM `" . $tbl['rel_course_class'] . "`\n            WHERE classId = '" . claro_sql_escape($classId) . "'";
        $searchResultList2 = claro_sql_query_fetch_all($sql2);
        foreach ($searchResultList2 as $thisCourse) {
            $courseCode = $thisCourse['courseId'];
            foreach ($thisClassUser as $thisUser) {
                $user_id = $thisUser['user_id'];
                if (!user_remove_from_course($user_id, $courseCode, false, false, $classId)) {
                    return claro_failure::set_failure('PROBLEM_WITH_COURSE_UNSUSCRIBTION ' . $user_id . ' ' . $courseCode);
                    //TODO : ameliorer la detection d'erreur
                }
            }
        }
        class_remove_all_users($classId);
    }
    return true;
}
Пример #26
0
/**
 * function delete_groups($groupIdList = 'ALL')
 * deletes groups and their datas.
 *
 * @param  mixed   $groupIdList - group(s) to delete. It can be a single id
 *                                (int) or a list of id (array). If no id is
 *                                given all the course group are deleted
 *
 * @return integer : number of groups deleted.
 * @throws claro_failure
 */
function delete_groups($groupIdList = 'ALL')
{
    global $eventNotifier;
    $tbl_c_names = claro_sql_get_course_tbl();
    $tbl_groups = $tbl_c_names['group_team'];
    $tbl_groupsUsers = $tbl_c_names['group_rel_team_user'];
    $tbl_courseCalendar = $tbl_c_names['calendar_event'];
    require_once get_module_path('CLWIKI') . '/lib/lib.createwiki.php';
    require_once dirname(__FILE__) . '/forum.lib.php';
    if (is_tool_activated_in_course(get_tool_id_from_module_label('CLWIKI'), claro_get_current_course_id()) && is_tool_activated_in_groups(claro_get_current_course_id(), 'CLWIKI')) {
        delete_group_wikis($groupIdList);
    }
    if (is_tool_activated_in_course(get_tool_id_from_module_label('CLFRM'), claro_get_current_course_id()) && is_tool_activated_in_groups(claro_get_current_course_id(), 'CLFRM')) {
        delete_group_forums($groupIdList);
    }
    /**
     * Check the data and notify eventmanager of the deletion
     */
    if (strtoupper($groupIdList) == 'ALL') {
        $sql_condition = '';
    } elseif (is_array($groupIdList)) {
        foreach ($groupIdList as $thisGroupId) {
            if (!is_int($thisGroupId)) {
                return false;
            }
        }
        $sql_condition = 'WHERE id IN (' . implode(' , ', $groupIdList) . ')';
    } else {
        if (settype($groupIdList, 'integer')) {
            $sql_condition = '  WHERE id = ' . (int) $groupIdList;
            $eventNotifier->notifyCourseEvent('group_deleted', claro_get_current_course_id(), claro_get_current_tool_id(), '0', $groupIdList, '0');
        } else {
            // TODO : perhaps a trigger erro is better
            return claro_failure::set_failure('CANT_SET_ID_GROUP_AS_INTEGER ' . __LINE__);
        }
    }
    /*
     * Search the groups data necessary to delete them
     */
    $sql_searchGroup = "SELECT `id` AS `id`,\n                               `secretDirectory` AS `directory`\n                        FROM `" . $tbl_groups . "`" . $sql_condition;
    $groupList = claro_sql_query_fetch_all_cols($sql_searchGroup);
    //notify event manager about the deletion for each group
    foreach ($groupList['id'] as $thisGroupId) {
        $eventNotifier->notifyCourseEvent('group_deleted', claro_get_current_course_id(), claro_get_current_tool_id(), '0', $thisGroupId, '0');
    }
    if (count($groupList['id']) > 0) {
        /*
         * Remove users, group(s) and group forum(s) from the course tables
         */
        $sql_deleteGroup = "DELETE FROM `" . $tbl_groups . "`\n                                   WHERE id IN (" . implode(' , ', $groupList['id']) . ")\n                                    # " . __FUNCTION__ . "\n                                    # " . __FILE__ . "\n                                    # " . __LINE__;
        $sql_cleanOutGroupUsers = "DELETE FROM `" . $tbl_groupsUsers . "`\n                                   WHERE team IN (" . implode(' , ', $groupList['id']) . ")\n                                    # " . __FUNCTION__ . "\n                                    # " . __FILE__ . "\n                                    # " . __LINE__;
        $sql_cleanOutGroupEvent = "DELETE FROM `" . $tbl_courseCalendar . "`\n                                    WHERE group_id IN (" . implode(' , ', $groupList['id']) . ")\n                                    # " . __FUNCTION__ . "\n                                    # " . __FILE__ . "\n                                    # " . __LINE__;
        // Deleting group record in table
        $deletedGroupNumber = claro_sql_query_affected_rows($sql_deleteGroup);
        // Delete all members of deleted group(s)
        claro_sql_query($sql_cleanOutGroupUsers);
        // Delete all calendar events for deleted group(s)
        claro_sql_query($sql_cleanOutGroupEvent);
        /**
         * Archive and delete the group files
         */
        // define repository for deleted element
        $groupGarbage = $GLOBALS['garbageRepositorySys'] . '/' . $GLOBALS['currentCourseRepository'] . '/group/';
        if (!file_exists($groupGarbage)) {
            claro_mkdir($groupGarbage, CLARO_FILE_PERMISSIONS, true);
        }
        foreach ($groupList['directory'] as $thisDirectory) {
            if (file_exists($GLOBALS['coursesRepositorySys'] . $GLOBALS['currentCourseRepository'] . '/group/' . $thisDirectory)) {
                rename($GLOBALS['coursesRepositorySys'] . $GLOBALS['currentCourseRepository'] . '/group/' . $thisDirectory, $groupGarbage . $thisDirectory);
            }
        }
        return $deletedGroupNumber;
    } else {
        return FALSE;
    }
}
Пример #27
0
/**
 * Send e-mail using Main settings
 */
function claro_mail($subject, $message, $to, $toName, $from, $fromName)
{
    $mail = new ClaroPHPMailer();
    if (empty($from)) {
        $from = get_conf('administrator_email');
        if (empty($fromName)) {
            $fromName = get_conf('administrator_name');
        }
    }
    $mail->Subject = $subject;
    $mail->Body = $message;
    $mail->From = $from;
    $mail->FromName = $fromName;
    $mail->Sender = $from;
    $mail->AddAddress($to, $toName);
    if ($mail->Send()) {
        return true;
    } else {
        return claro_failure::set_failure($mail->getError());
    }
}
Пример #28
0
function repairTree()
{
    $tbl_mdb_names = claro_sql_get_main_tbl();
    $tbl_category = $tbl_mdb_names['category'];
    //  get  list of all node
    $sql = " SELECT code, code_P, treePos, name, nb_childs\n               FROM `" . $tbl_category . "`\n               ORDER BY `treePos`";
    $catList = claro_sql_query_fetch_all($sql);
    $newTreePos = 1;
    $listSize = count($catList);
    // foreach node check code_parent,  treepos and nbchilds
    foreach ($catList as $cat) {
        $newCatList[$cat['code']] = $cat;
        $parentCatData = get_cat_data(get_cat_id_from_code($cat['code_P']));
        if ($cat['treePos'] < $parentCatData['treePos']) {
            $newCatList[$cat['code']]['newCode_P'] = ' root ';
            $newCatList[$cat['code']]['newTreePos'] = $listSize--;
        } else {
            if (!is_null($cat['code_P']) && !get_cat_id_from_code($cat['code_P'])) {
                $newCatList[$cat['code']]['newCode_P'] = ' root ';
                $newCatList[$cat['code']]['newTreePos'] = $listSize--;
            } else {
                $newCatList[$cat['code']]['newTreePos'] = $newTreePos++;
                $newCatList[$cat['code']]['newNb_childs'] = countChild($cat['code']);
            }
        }
    }
    reset($newCatList);
    $node_moved = false;
    // rescan node list  and  update data if difference was detected.
    foreach ($newCatList as $cat) {
        if (isset($cat['newCode_P']) && $cat['code_P'] != $cat['newCode_P']) {
            $sql = "UPDATE  `" . $tbl_category . "` " . ($cat['newCode_P'] == ' root ' ? "   SET code_P = null " : "   SET code_P = " . (int) $cat['newCode_P']) . " WHERE code = '" . claro_sql_escape($cat['code']) . "'";
            $node_moved = true;
            // repair ownance but brok countchild
            claro_sql_query($sql);
        }
        if (isset($cat['newNb_childs']) && $cat['nb_childs'] != $cat['newNb_childs']) {
            $sql = "UPDATE  `" . $tbl_category . "` " . "   SET nb_childs = " . (int) $cat['newNb_childs'] . " WHERE code = '" . claro_sql_escape($cat['code']) . "'";
            claro_sql_query($sql);
        }
        if ($cat['treePos'] != $cat['newTreePos']) {
            $sql = "UPDATE  `" . $tbl_category . "` " . "   SET treePos = " . (int) $cat['newTreePos'] . " WHERE code = '" . claro_sql_escape($cat['code']) . "'";
            claro_sql_query($sql);
        }
    }
    if ($node_moved) {
        return claro_failure::set_failure('node_moved');
    } else {
        return true;
    }
}
Пример #29
0
<?php

// $Id: course_install.php 9706 2007-12-12 13:30:11Z mlaurent $
// vim: expandtab sw=4 ts=4 sts=4:
if (count(get_included_files()) == 1) {
    die('The file ' . basename(__FILE__) . ' cannot be accessed directly, use include instead');
}
$moduleWorkingDirectory = get_path('coursesRepositorySys') . $courseDirectory . '/chat';
if (!claro_mkdir($moduleWorkingDirectory, CLARO_FILE_PERMISSIONS, true)) {
    return claro_failure::set_failure(get_lang('Unable to create folder %folder', array('%folder' => $moduleWorkingDirectory)));
}
Пример #30
0
 /**
  * Validate data from current object.  Error handling with
  * a backlog object.
  *
  * @return bool     success
  */
 public function validate()
 {
     //TODO don't get how this function actually works
     $success = true;
     // Configuration array, define here which field can be left empty or not
     //TODO make it more accurate using function get_conf('human_label_needed');
     $fieldRequiredStateList['name'] = true;
     $fieldRequiredStateList['code'] = true;
     $fieldRequiredStateList['idParent'] = true;
     $fieldRequiredStateList['rank'] = false;
     $fieldRequiredStateList['visible'] = true;
     $fieldRequiredStateList['canHaveCoursesChild'] = true;
     // Validate category name
     if (is_null($this->name) && $fieldRequiredStateList['name']) {
         claro_failure::set_failure('category_missing_field_name');
         $this->backlog->failure(get_lang('Category name is required'));
         $success = false;
     }
     // Validate category code
     if (is_null($this->code) && $fieldRequiredStateList['code']) {
         claro_failure::set_failure('category_missing_field_code');
         $this->backlog->failure(get_lang('Category code needed'));
         $success = false;
     }
     // Check if the code is unique
     if (!$this->checkUniqueCode()) {
         claro_failure::set_failure('category_duplicate_code');
         $this->backlog->failure(get_lang('This category already exists'));
         $success = false;
     }
     // Validate parent identifier
     if (is_null($this->idParent) && $fieldRequiredStateList['idParent']) {
         claro_failure::set_failure('category_missing_field_idParent');
         $this->backlog->failure(get_lang('Category parent needed'));
         $success = false;
     }
     // Category can't be its own parent
     if ($this->idParent == $this->id) {
         claro_failure::set_failure('category_self_linked');
         $this->backlog->failure(get_lang('Category can\'t be its own parent'));
         $success = false;
     }
     // Category can't be linked to one of its own children
     if ($this->checkIsChild($this->idParent)) {
         claro_failure::set_failure('category_child_linked');
         $this->backlog->failure(get_lang('Category can\'t be linked to one of its own children'));
         $success = false;
     }
     // Check authorisation to possess courses
     if (is_null($this->visible) && $fieldRequiredStateList['visible']) {
         claro_failure::set_failure('category_missing_field_visible');
         $this->backlog->failure(get_lang('Visibility of the category must be set'));
         $success = false;
     }
     // Check authorisation to possess courses
     if (is_null($this->canHaveCoursesChild) && $fieldRequiredStateList['canHaveCoursesChild']) {
         claro_failure::set_failure('category_missing_field_canHaveCoursesChild');
         $this->backlog->failure(get_lang('Category must be authorized or not to have courses children'));
         $success = false;
     }
     return $success;
 }