/**
  * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormOrganization
  * object from database records or from the DOM element given as parameter
  * @param	string	Type of construction needed ('db' or 'manifest', default = 'manifest')
  * @param	mixed	Depending on the type given, DB id for the lp_item or reference to the DOM element
  */
 public function __construct($type = 'manifest', &$element, $scorm_charset = 'UTF-8')
 {
     if (isset($element)) {
         // Parsing using PHP5 DOMXML methods.
         switch ($type) {
             case 'db':
                 // TODO: Implement this way of metadata object creation.
                 return false;
             case 'manifest':
                 // Do the same as the default.
             // Do the same as the default.
             default:
                 //if ($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function.
                 $children = $element->childNodes;
                 foreach ($children as $child) {
                     switch ($child->nodeType) {
                         case XML_ELEMENT_NODE:
                             switch ($child->tagName) {
                                 case 'item':
                                     $oItem = new scormItem('manifest', $child);
                                     if ($oItem->identifier != '') {
                                         $this->items[$oItem->identifier] = $oItem;
                                     }
                                     break;
                                 case 'metadata':
                                     $this->metadata = new scormMetadata('manifest', $child);
                                     break;
                                 case 'title':
                                     $tmp_children = $child->childNodes;
                                     if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
                                         $this->title = api_utf8_decode(api_html_entity_decode($child->firstChild->nodeValue, ENT_QUOTES, 'UTF-8'));
                                     }
                                     break;
                             }
                             break;
                         case XML_TEXT_NODE:
                             break;
                     }
                 }
                 if ($element->hasAttributes()) {
                     $attributes = $element->attributes;
                     //$keep_href = '';
                     foreach ($attributes as $attrib) {
                         switch ($attrib->name) {
                             case 'identifier':
                                 $this->identifier = $attrib->value;
                                 break;
                             case 'structure':
                                 $this->structure = $attrib->value;
                                 break;
                         }
                     }
                 }
                 return true;
         }
         // End parsing using PHP5 DOMXML methods.
     }
     return false;
 }
Example #2
0
 /**
  * Returns the title of a html document.
  * @param string $string                The contents of the input document.
  * @param string $input_encoding        The encoding of the input document. If the value is not set, it is detected.
  * @param string $$output_encoding      The encoding of the retrieved title. If the value is not set, the system encoding is assumend.
  * @return string                       The retrieved title, html-entities and extra-whitespace between the words are cleaned.
  */
 static function api_get_title_html(&$string, $output_encoding = null, $input_encoding = null)
 {
     if (@preg_match('/<head.+<title[^>]*>(.*)<\\/title>/msi', $string, $matches)) {
         if (empty($output_encoding)) {
             $output_encoding = api_get_system_encoding();
         }
         if (empty($input_encoding)) {
             $input_encoding = self::api_detect_encoding_html($string);
         }
         return trim(@preg_replace('/\\s+/', ' ', api_html_entity_decode(api_convert_encoding($matches[1], $output_encoding, $input_encoding), ENT_QUOTES, $output_encoding)));
     }
     return '';
 }
    /**
     * Gets html pages and compose them into a learning path
     * @param	array	The files that will compose the generated learning path. Unused so far.
     * @return	boolean	False if file does not exit. Nothing otherwise.
     */
    function make_lp($files = array()) {

        global $_course;
        // We get a content where ||page_break|| indicates where the page is broken.
        if (!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')) { return false; }
        $content = file_get_contents($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');

        unlink($this->base_work_dir.'/'.$this->file_path);
        unlink($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');

        // The file is utf8 encoded and it seems to make problems with special quotes.
        // Then we htmlentities that, we replace these quotes and html_entity_decode that in good charset.
        $charset = api_get_system_encoding();
        $content = api_htmlentities($content, ENT_COMPAT, $this->original_charset);
        $content = str_replace('&rsquo;', '\'', $content);
        $content = api_convert_encoding($content, $charset, $this->original_charset);
        $content = str_replace($this->original_charset, $charset, $content);
        $content = api_html_entity_decode($content, ENT_COMPAT, $charset);

        // Set the path to pictures to absolute (so that it can be modified in fckeditor).
        $content = preg_replace("|src=\"([^\"]*)|i", "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1", $content);

        list($header, $body) = explode('<BODY', $content);

        $body = '<BODY'.$body;

        // Remove font-family styles.
        $header = preg_replace("|font\-family[^;]*;|i", '', $header);

        // Chamilo styles.
        $my_style = api_get_setting('stylesheets');
        if (empty($my_style)) { $my_style = 'chamilo'; }
        $style_to_import = "<style type=\"text/css\">\r\n";
        $style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n";        
        $style_to_import .= "</style>\r\n";
        $header = preg_replace("|</head>|i", "\r\n$style_to_import\r\n\\0", $header);

        // Line break before and after picture.
        $header = str_replace('p {', 'p {clear:both;', $header);

        $header = str_replace('absolute', 'relative', $header);

        switch ($this->split_steps) {
            case 'per_page': $this -> dealPerPage($header, $body); break;
            case 'per_chapter': $this -> dealPerChapter($header, $body); break;
        }
    }
 /**
  * Exports the complete report as a CSV file
  * @param	string		Document path inside the document tool
  * @param	integer		Optional user ID
  * @param	boolean		Whether to include user fields or not
  * @return	boolean		False on error
  */
 public function exportCompleteReportCSV($dato)
 {
     $filename = 'gradebook_results_' . gmdate('YmdGis') . '.csv';
     if (!empty($user_id)) {
         $filename = 'gradebook_results_user_' . $user_id . '_' . gmdate('YmdGis') . '.csv';
     }
     $data = '';
     //build the results
     //titles
     foreach ($dato[0] as $header_col) {
         if (!empty($header_col)) {
             $data .= str_replace("\r\n", '  ', api_html_entity_decode(strip_tags($header_col))) . ';';
         }
     }
     $data .= "\r\n";
     $cant_students = count($dato[1]);
     //print_r($data);		exit();
     for ($i = 0; $i < $cant_students; $i++) {
         $column = 0;
         foreach ($dato[1][$i] as $col_name) {
             $data .= str_replace("\r\n", '  ', api_html_entity_decode(strip_tags($col_name))) . ';';
         }
         $data .= "\r\n";
     }
     //output the results
     $len = strlen($data);
     header('Content-type: application/octet-stream');
     header('Content-Type: application/force-download');
     header('Content-length: ' . $len);
     if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
         header('Content-Disposition: filename= ' . $filename);
     } else {
         header('Content-Disposition: attachment; filename= ' . $filename);
     }
     if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
         header('Pragma: ');
         header('Cache-Control: ');
         header('Cache-Control: public');
         // IE cannot download from sessions without a cache
     }
     header('Content-Description: ' . $filename);
     header('Content-transfer-encoding: binary');
     echo $data;
     return true;
 }
/**
 * This is a php-implementation of a function that is similar to mb_convert_encoding() from mbstring extension.
 * The function converts a given string from one to another character encoding.
 * @param string $string					The string being converted.
 * @param string $to_encoding				The encoding that $string is being converted to.
 * @param string $from_encoding				The encoding that $string is being converted from.
 * @return string							Returns the converted string.
 */
function _api_convert_encoding(&$string, $to_encoding, $from_encoding)
{
    $str = (string) $string;
    static $character_map = array();
    static $utf8_compatible = array('UTF-8', 'US-ASCII');
    if (empty($str)) {
        return $str;
    }
    $to_encoding = api_refine_encoding_id($to_encoding);
    $from_encoding = api_refine_encoding_id($from_encoding);
    if (api_equal_encodings($to_encoding, $from_encoding)) {
        return $str;
    }
    if ($to_encoding == 'HTML-ENTITIES') {
        return api_htmlentities($str, ENT_QUOTES, $from_encoding);
    }
    if ($from_encoding == 'HTML-ENTITIES') {
        return api_html_entity_decode($str, ENT_QUOTES, $to_encoding);
    }
    $to = _api_get_character_map_name($to_encoding);
    $from = _api_get_character_map_name($from_encoding);
    if (empty($to) || empty($from) || $to == $from || in_array($to, $utf8_compatible) && in_array($from, $utf8_compatible)) {
        return $str;
    }
    if (!isset($character_map[$to])) {
        $character_map[$to] =& _api_parse_character_map($to);
    }
    if ($character_map[$to] === false) {
        return $str;
    }
    if (!isset($character_map[$from])) {
        $character_map[$from] =& _api_parse_character_map($from);
    }
    if ($character_map[$from] === false) {
        return $str;
    }
    if ($from != 'UTF-8') {
        $len = api_byte_count($str);
        $codepoints = array();
        for ($i = 0; $i < $len; $i++) {
            $ord = ord($str[$i]);
            if ($ord > 127) {
                if (isset($character_map[$from]['local'][$ord])) {
                    $codepoints[] = $character_map[$from]['local'][$ord];
                } else {
                    $codepoints[] = 0xfffd;
                    // U+FFFD REPLACEMENT CHARACTER is the general substitute character in the Unicode Standard.
                }
            } else {
                $codepoints[] = $ord;
            }
        }
    } else {
        $codepoints = _api_utf8_to_unicode($str);
    }
    if ($to != 'UTF-8') {
        foreach ($codepoints as $i => &$codepoint) {
            if ($codepoint > 127) {
                if (isset($character_map[$to]['unicode'][$codepoint])) {
                    $codepoint = chr($character_map[$to]['unicode'][$codepoint]);
                } else {
                    $codepoint = '?';
                    // Unknown character.
                }
            } else {
                $codepoint = chr($codepoint);
            }
        }
        $str = implode($codepoints);
    } else {
        $str = _api_utf8_from_unicode($codepoints);
    }
    return $str;
}
 /**
  * @param $in_title
  * @return string
  */
 public static function get_formated_title_variable($in_title)
 {
     return api_html_entity_decode($in_title);
 }
Example #7
0
 /**
  * Return the HTML form to display an item (generally a section/module item)
  * @param    string    Item type (module/dokeos_module)
  * @param    string    Title (optional, only when creating)
  * @param    string    Action ('add'/'edit')
  * @param    integer    lp_item ID
  * @param    mixed    Extra info
  * @return    string     HTML form
  */
 public function display_item_form($item_type, $title = '', $action = 'add_item', $id = 0, $extra_info = 'new')
 {
     $course_id = api_get_course_int_id();
     $_course = api_get_course_info();
     global $charset;
     $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
     if ($id != 0 && is_array($extra_info)) {
         $item_title = $extra_info['title'];
         $item_description = $extra_info['description'];
         $item_path = api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/scorm/' . $this->path . '/' . stripslashes($extra_info['path']);
         $item_path_fck = '/scorm/' . $this->path . '/' . stripslashes($extra_info['path']);
     } else {
         $item_title = '';
         $item_description = '';
         $item_path_fck = '';
     }
     if ($id != 0 && is_array($extra_info)) {
         $parent = $extra_info['parent_item_id'];
     } else {
         $parent = 0;
     }
     $id = intval($id);
     $sql = "SELECT * FROM " . $tbl_lp_item . "\n                WHERE c_id = " . $course_id . " AND lp_id = " . $this->lp_id . " AND id != {$id}";
     if ($item_type == 'module') {
         $sql .= " AND parent_item_id = 0";
     }
     $result = Database::query($sql);
     $arrLP = array();
     while ($row = Database::fetch_array($result)) {
         $arrLP[] = array('id' => $row['id'], 'item_type' => $row['item_type'], 'title' => $row['title'], 'path' => $row['path'], 'description' => $row['description'], 'parent_item_id' => $row['parent_item_id'], 'previous_item_id' => $row['previous_item_id'], 'next_item_id' => $row['next_item_id'], 'max_score' => $row['max_score'], 'min_score' => $row['min_score'], 'mastery_score' => $row['mastery_score'], 'prerequisite' => $row['prerequisite'], 'display_order' => $row['display_order']);
     }
     $this->tree_array($arrLP);
     $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
     unset($this->arrMenu);
     $gradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : null;
     $url = api_get_self() . '?' . api_get_cidreq() . '&gradeboook=' . $gradebook . '&action=' . $action . '&type=' . $item_type . '&lp_id=' . $this->lp_id;
     $form = new FormValidator('form', 'POST', $url);
     $defaults['title'] = api_html_entity_decode($item_title, ENT_QUOTES, $charset);
     $defaults['description'] = $item_description;
     $form->addElement('header', $title);
     //$arrHide = array($id);
     $arrHide[0]['value'] = Security::remove_XSS($this->name);
     $arrHide[0]['padding'] = 3;
     $charset = api_get_system_encoding();
     if ($item_type != 'module' && $item_type != 'dokeos_module') {
         for ($i = 0; $i < count($arrLP); $i++) {
             if ($action != 'add') {
                 if (($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide) && !in_array($arrLP[$i]['parent_item_id'], $arrHide)) {
                     $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
                     $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10;
                     if ($parent == $arrLP[$i]['id']) {
                         $s_selected_parent = $arrHide[$arrLP[$i]['id']];
                     }
                 }
             } else {
                 if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') {
                     $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
                     $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10;
                     if ($parent == $arrLP[$i]['id']) {
                         $s_selected_parent = $arrHide[$arrLP[$i]['id']];
                     }
                 }
             }
         }
         if ($action != 'move') {
             $form->addElement('text', 'title', get_lang('Title'), 'id="idTitle" class="learnpath_chapter_form" size="40%"');
             $form->applyFilter('title', 'html_filter');
             $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
             //$form->addElement('textarea', 'description', get_lang('Description').' :', 'id="idDescription"');
         } else {
             $form->addElement('hidden', 'title');
         }
         $parent_select = $form->addElement('select', 'parent', get_lang('Parent'), '', 'class="learnpath_chapter_form" style="width:37%;" id="idParent" onchange="javascript: load_cbo(this.value);"');
         foreach ($arrHide as $key => $value) {
             $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"');
         }
         if (!empty($s_selected_parent)) {
             $parent_select->setSelected($s_selected_parent);
         }
     }
     if (is_array($arrLP)) {
         reset($arrLP);
     }
     $arrHide = array();
     // POSITION
     for ($i = 0; $i < count($arrLP); $i++) {
         if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
             //this is the same!
             if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
                 $s_selected_position = $arrLP[$i]['id'];
             } elseif ($action == 'add') {
                 $s_selected_position = $arrLP[$i]['id'];
             }
             $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After') . ' "' . $arrLP[$i]['title'] . '"';
         }
     }
     $position = $form->addElement('select', 'previous', get_lang('Position'), '', 'id="previous" class="learnpath_chapter_form" style="width:37%;"');
     $padding = isset($value['padding']) ? $value['padding'] : 0;
     $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:' . $padding . 'px;"');
     foreach ($arrHide as $key => $value) {
         $position->addOption($value['value'] . '"', $key, 'style="padding-left:' . $padding . 'px;"');
     }
     if (!empty($s_selected_position)) {
         $position->setSelected($s_selected_position);
     }
     if (is_array($arrLP)) {
         reset($arrLP);
     }
     $form->addElement('style_submit_button', 'submit_button', get_lang('SaveSection'), 'class="save"');
     if ($item_type == 'module' || $item_type == 'dokeos_module') {
         $form->addElement('hidden', 'parent', '0');
     }
     //fix in order to use the tab
     if ($item_type == 'chapter') {
         $form->addElement('hidden', 'type', 'chapter');
     }
     $extension = null;
     if (!empty($item_path)) {
         $extension = pathinfo($item_path, PATHINFO_EXTENSION);
     }
     //assets can't be modified
     //$item_type == 'asset' ||
     if ($item_type == 'sco' && ($extension == 'html' || $extension == 'htm')) {
         if ($item_type == 'sco') {
             $form->addElement('html', '<script type="text/javascript">alert("' . get_lang('WarningWhenEditingScorm') . '")</script>');
         }
         $renderer = $form->defaultRenderer();
         $renderer->setElementTemplate('<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}', 'content_lp');
         $relative_prefix = '';
         $editor_config = array('ToolbarSet' => 'LearningPathDocuments', 'Width' => '100%', 'Height' => '500', 'FullPage' => true, 'CreateDocumentDir' => $relative_prefix, 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH) . api_get_course_path() . '/scorm/', 'BaseHref' => api_get_path(WEB_COURSE_PATH) . api_get_course_path() . $item_path_fck);
         $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
         $content_path = api_get_path(SYS_COURSE_PATH) . api_get_course_path() . $item_path_fck;
         //$defaults['content_lp'] = file_get_contents($item_path);
         $defaults['content_lp'] = file_get_contents($content_path);
     }
     $form->addElement('hidden', 'type', 'dokeos_' . $item_type);
     $form->addElement('hidden', 'post_time', time());
     $form->setDefaults($defaults);
     return $form->return_form();
 }
Example #8
0
$lib_path = api_get_path(LIBRARY_PATH);
require_once $lib_path . 'blog.lib.php';
require_once $lib_path . 'fckeditor/fckeditor.php';
$blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
$nameTools = get_lang('Blogs');
$DaysShort = api_get_week_days_short();
$DaysLong = api_get_week_days_long();
$MonthsLong = api_get_months_long();
$current_page = $_GET['action'];
/*
	PROCESSING
*/
$safe_post_title = Security::remove_XSS($_POST['post_title']);
$safe_post_file_comment = Security::remove_XSS($_POST['post_file_comment']);
$safe_post_full_text = Security::remove_XSS(stripslashes(api_html_entity_decode($_POST['post_full_text'])), COURSEMANAGERLOWSECURITY);
$safe_comment_text = Security::remove_XSS(stripslashes(api_html_entity_decode($_POST['comment_text'])), COURSEMANAGERLOWSECURITY);
$safe_comment_title = Security::remove_XSS($_POST['comment_title']);
$safe_task_name = Security::remove_XSS($_POST['task_name']);
$safe_task_description = Security::remove_XSS($_POST['task_description']);
if (!empty($_POST['new_post_submit']) and !empty($_POST['post_title'])) {
    Blog::create_post($safe_post_title, $safe_post_full_text, $safe_post_file_comment, $blog_id);
    $return_message = array('type' => 'confirmation', 'message' => get_lang('BlogAdded'));
}
if (!empty($_POST['edit_post_submit'])) {
    $safe_post_title = Security::remove_XSS($_POST['post_title']);
    Blog::edit_post($_POST['post_id'], $safe_post_title, $safe_post_full_text, $blog_id);
    $return_message = array('type' => 'confirmation', 'message' => get_lang('BlogEdited'));
}
if (!empty($_POST['new_comment_submit'])) {
    Blog::create_comment($safe_comment_title, $safe_comment_text, $safe_post_file_comment, $blog_id, (int) $_GET['post_id'], $_POST['comment_parent_id']);
    $return_message = array('type' => 'confirmation', 'message' => get_lang('CommentAdded'));
Example #9
0
 }
 if (!empty($total_time)) {
     $any_result = true;
 }
 // Quiz in lp
 $score = Tracking::get_avg_student_score($student_id, $course_code, array($lp_id), $sessionId);
 // Latest exercise results in a LP
 $score_latest = Tracking::get_avg_student_score($student_id, $course_code, array($lp_id), $sessionId, false, true);
 if ($i % 2 == 0) {
     $css_class = "row_even";
 } else {
     $css_class = "row_odd";
 }
 $i++;
 // csv export content
 $csv_content[] = array(api_html_entity_decode(stripslashes($lp_name), ENT_QUOTES, $charset), api_time_to_hms($total_time), $score . '%', $score_latest . '%', $progress . '%', $start_time);
 echo '<tr class="' . $css_class . '">';
 echo Display::tag('td', stripslashes($lp_name));
 echo Display::tag('td', api_time_to_hms($total_time));
 if (!is_null($score)) {
     if (is_numeric($score)) {
         $score = $score . '%';
     }
 }
 echo Display::tag('td', $score);
 if (!is_null($score_latest)) {
     if (is_numeric($score_latest)) {
         $score_latest = $score_latest . '%';
     }
 }
 echo Display::tag('td', $score_latest);
Example #10
0
/**
 * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully)
 * Sender name and email can be specified, if not specified
 * name and email of the platform admin are used
 *
 * @author Bert Vanderkimpen ICT&O UGent
 * @author Yannick Warnier <*****@*****.**>
 *
 * @param string    name of recipient
 * @param string    email of recipient
 * @param string    email subject
 * @param string    email body
 * @param string    sender name
 * @param string    sender e-mail
 * @param array     extra headers in form $headers = array($name => $value) to allow parsing
 * @param array     data file (path and filename)
 * @param array     data to attach a file (optional)
 * @param bool      True for attaching a embedded file inside content html (optional)
 * @return          returns true if mail was sent
 * @see             class.phpmailer.php
 */
function api_mail_html($recipient_name, $recipient_email, $subject, $message, $senderName = '', $senderEmail = '', $extra_headers = array(), $data_file = array(), $embedded_image = false, $additionalParameters = array())
{
    global $platform_email;
    $mail = new PHPMailer();
    $mail->Mailer = $platform_email['SMTP_MAILER'];
    $mail->Host = $platform_email['SMTP_HOST'];
    $mail->Port = $platform_email['SMTP_PORT'];
    $mail->CharSet = $platform_email['SMTP_CHARSET'];
    // Stay far below SMTP protocol 980 chars limit.
    $mail->WordWrap = 200;
    if ($platform_email['SMTP_AUTH']) {
        $mail->SMTPAuth = 1;
        $mail->Username = $platform_email['SMTP_USER'];
        $mail->Password = $platform_email['SMTP_PASS'];
    }
    // 5 = low, 1 = high
    $mail->Priority = 3;
    $mail->SMTPKeepAlive = true;
    // Default values
    $notification = new Notification();
    $defaultEmail = $notification->getDefaultPlatformSenderEmail();
    $defaultName = $notification->getDefaultPlatformSenderName();
    // Error to admin.
    $mail->AddCustomHeader('Errors-To: ' . $defaultEmail);
    // If the parameter is set don't use the admin.
    $senderName = !empty($senderName) ? $senderName : $defaultEmail;
    $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultName;
    // Reply to first
    if (isset($extra_headers['reply_to'])) {
        $mail->AddReplyTo($extra_headers['reply_to']['mail'], $extra_headers['reply_to']['name']);
        $mail->Sender = $extra_headers['reply_to']['mail'];
        unset($extra_headers['reply_to']);
    }
    $mail->SetFrom($senderEmail, $senderName);
    $mail->Subject = $subject;
    $mail->AltBody = strip_tags(str_replace('<br />', "\n", api_html_entity_decode($message)));
    // Send embedded image.
    if ($embedded_image) {
        // Get all images html inside content.
        preg_match_all("/<img\\s+.*?src=[\"\\']?([^\"\\' >]*)[\"\\']?[^>]*>/i", $message, $m);
        // Prepare new tag images.
        $new_images_html = array();
        $i = 1;
        if (!empty($m[1])) {
            foreach ($m[1] as $image_path) {
                $real_path = realpath($image_path);
                $filename = basename($image_path);
                $image_cid = $filename . '_' . $i;
                $encoding = 'base64';
                $image_type = mime_content_type($real_path);
                $mail->AddEmbeddedImage($real_path, $image_cid, $filename, $encoding, $image_type);
                $new_images_html[] = '<img src="cid:' . $image_cid . '" />';
                $i++;
            }
        }
        // Replace origin image for new embedded image html.
        $x = 0;
        if (!empty($m[0])) {
            foreach ($m[0] as $orig_img) {
                $message = str_replace($orig_img, $new_images_html[$x], $message);
                $x++;
            }
        }
    }
    $message = str_replace(array("\n\r", "\n", "\r"), '<br />', $message);
    $mail->Body = '<html><head></head><body>' . $message . '</body></html>';
    // Attachment ...
    if (!empty($data_file)) {
        $mail->AddAttachment($data_file['path'], $data_file['filename']);
    }
    // Only valid addresses are accepted.
    if (is_array($recipient_email)) {
        foreach ($recipient_email as $dest) {
            if (api_valid_email($dest)) {
                $mail->AddAddress($dest, $recipient_name);
            }
        }
    } else {
        if (api_valid_email($recipient_email)) {
            $mail->AddAddress($recipient_email, $recipient_name);
        } else {
            return 0;
        }
    }
    if (is_array($extra_headers) && count($extra_headers) > 0) {
        foreach ($extra_headers as $key => $value) {
            switch (strtolower($key)) {
                case 'encoding':
                case 'content-transfer-encoding':
                    $mail->Encoding = $value;
                    break;
                case 'charset':
                    $mail->Charset = $value;
                    break;
                case 'contenttype':
                case 'content-type':
                    $mail->ContentType = $value;
                    break;
                default:
                    $mail->AddCustomHeader($key . ':' . $value);
                    break;
            }
        }
    } else {
        if (!empty($extra_headers)) {
            $mail->AddCustomHeader($extra_headers);
        }
    }
    // WordWrap the html body (phpMailer only fixes AltBody) FS#2988
    $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap);
    // Send the mail message.
    if (!$mail->Send()) {
        error_log('ERROR: mail not sent to ' . $recipient_name . ' (' . $recipient_email . ') because of ' . $mail->ErrorInfo . '<br />');
        return 0;
    }
    $plugin = new AppPlugin();
    $installedPluginsList = $plugin->getInstalledPluginListObject();
    foreach ($installedPluginsList as $installedPlugin) {
        if ($installedPlugin->isMailPlugin and array_key_exists("smsType", $additionalParameters)) {
            $clockworksmsObject = new Clockworksms();
            $clockworksmsObject->send($additionalParameters);
        }
    }
    // Clear all the addresses.
    $mail->ClearAddresses();
    return 1;
}
Example #11
0
$table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
$table_user 					= Database :: get_main_table(TABLE_MAIN_USER);

$course_id = api_get_course_int_id();

// Getting the survey information
$survey_data = survey_manager::get_survey($_GET['survey_id']);
if (empty($survey_data)) {
	Display :: display_header(get_lang('ToolSurvey'));
	Display :: display_error_message(get_lang('InvallidSurvey'), false);
	Display :: display_footer();
	exit;
}

$urlname = api_substr(api_html_entity_decode($survey_data['title'], ENT_QUOTES), 0, 40);
if (api_strlen(strip_tags($survey_data['title'])) > 40) {
	$urlname .= '...';
}

if ($survey_data['survey_type'] == 1) {
	$sql = 'SELECT id FROM '.Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP).'
	        WHERE
                c_id = '.$course_id.' AND
                survey_id = '.(int)$_GET['survey_id'].' LIMIT 1';
	$rs = Database::query($sql);
	if (Database::num_rows($rs)===0) {
		header('Location: '.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.(int)$_GET['survey_id'].'&message='.'YouNeedToCreateGroups');
		exit;
	}
}
/**
 * This function displays the form that is used to add a post. This can be a new thread or a reply.
 * @param array $current_forum
 * @param array $forum_setting
 * @param string $action is the parameter that determines if we are
 *  1. newthread: adding a new thread (both empty) => No I-frame
 *  2. replythread: Replying to a thread ($action = replythread) => I-frame with the complete thread (if enabled)
 *  3. replymessage: Replying to a message ($action =replymessage) => I-frame with the complete thread (if enabled) (I first thought to put and I-frame with the message only)
 *  4. quote: Quoting a message ($action= quotemessage) => I-frame with the complete thread (if enabled). The message will be in the reply. (I first thought not to put an I-frame here)
 * @return void HMTL
 * @author Patrick Cool <*****@*****.**>, Ghent University
 * @version february 2006, dokeos 1.8
 */
function show_add_post_form($current_forum, $forum_setting, $action = '', $id = '', $form_values = '')
{
    $_user = api_get_user_info();
    $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
    // Initialize the object.
    $myThread = isset($_GET['thread']) ? $_GET['thread'] : '';
    $my_forum = isset($_GET['forum']) ? $_GET['forum'] : '';
    $my_post = isset($_GET['post']) ? $_GET['post'] : '';
    $my_gradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : '';
    $form = new FormValidator('thread', 'post', api_get_self() . '?' . http_build_query(['forum' => intval($my_forum), 'gradebook' => $my_gradebook, 'thread' => intval($myThread), 'post' => intval($my_post), 'action' => $action]) . '&' . api_get_cidreq());
    $form->setConstants(array('forum' => '5'));
    // Setting the form elements.
    $form->addElement('hidden', 'forum_id', intval($my_forum));
    $form->addElement('hidden', 'thread_id', intval($myThread));
    $form->addElement('hidden', 'gradebook', $my_gradebook);
    // If anonymous posts are allowed we also display a form to allow the user to put his name or username in.
    if ($current_forum['allow_anonymous'] == 1 && !isset($_user['user_id'])) {
        $form->addElement('text', 'poster_name', get_lang('Name'));
        $form->applyFilter('poster_name', 'html_filter');
    }
    $form->addElement('text', 'post_title', get_lang('Title'));
    $form->addHtmlEditor('post_text', get_lang('Text'), true, null, api_is_allowed_to_edit(null, true) ? array('ToolbarSet' => 'Forum', 'Width' => '100%', 'Height' => '300') : array('ToolbarSet' => 'ForumStudent', 'Width' => '100%', 'Height' => '300', 'UserStatus' => 'student'));
    $form->addRule('post_text', get_lang('ThisFieldIsRequired'), 'required');
    $iframe = null;
    $myThread = Security::remove_XSS($myThread);
    if ($forum_setting['show_thread_iframe_on_reply'] && $action != 'newthread' && !empty($myThread)) {
        $iframe = "<iframe style=\"border: 1px solid black\" src=\"iframe_thread.php?" . api_get_cidreq() . "&forum=" . Security::remove_XSS($my_forum) . "&thread=" . $myThread . "#" . Security::remove_XSS($my_post) . "\" width=\"100%\"></iframe>";
    }
    if (!empty($iframe)) {
        $form->addElement('label', get_lang('Thread'), $iframe);
    }
    $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters'));
    $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
    if ((api_is_course_admin() || api_is_course_coach() || api_is_course_tutor()) && !$myThread) {
        // Thread qualify
        if (Gradebook::is_active()) {
            //Loading gradebook select
            GradebookUtils::load_gradebook_select_in_tool($form);
            $form->addElement('checkbox', 'thread_qualify_gradebook', '', get_lang('QualifyThreadGradebook'), 'onclick="javascript:if(this.checked==true){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"');
        } else {
            $form->addElement('hidden', 'thread_qualify_gradebook', false);
        }
        $form->addElement('html', '<div id="options_field" style="display:none">');
        $form->addElement('text', 'numeric_calification', get_lang('QualificationNumeric'));
        $form->applyFilter('numeric_calification', 'html_filter');
        $form->addElement('text', 'calification_notebook_title', get_lang('TitleColumnGradebook'));
        $form->applyFilter('calification_notebook_title', 'html_filter');
        $form->addElement('text', 'weight_calification', get_lang('QualifyWeight'), array('value' => '0.00', 'onfocus' => "javascript: this.select();"));
        $form->applyFilter('weight_calification', 'html_filter');
        $group = array();
        $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('Yes'), 1);
        $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('No'), 0);
        $form->addGroup($group, '', [get_lang('ForumThreadPeerScoring'), get_lang('ForumThreadPeerScoringComment')], ' ');
        $form->addElement('html', '</div>');
    }
    if ($forum_setting['allow_post_notification'] && isset($_user['user_id'])) {
        $form->addElement('checkbox', 'post_notification', '', get_lang('NotifyByEmail') . ' (' . $_user['mail'] . ')');
    }
    if ($forum_setting['allow_sticky'] && api_is_allowed_to_edit(null, true) && $action == 'newthread') {
        $form->addElement('checkbox', 'thread_sticky', '', get_lang('StickyPost'));
    }
    if ($current_forum['allow_attachments'] == '1' || api_is_allowed_to_edit(null, true)) {
        $values = $form->exportValues();
    }
    $form->addElement('html', '</div>');
    if (in_array($action, ['quote', 'replymessage'])) {
        $form->addFile('user_upload[]', get_lang('Attachment'));
        $form->addButton('add_attachment', get_lang('AddAttachment'), 'paperclip', 'default', 'default', null, ['id' => 'reply-add-attachment']);
    } else {
        $form->addFile('user_upload', get_lang('Attachment'));
    }
    // Setting the class and text of the form title and submit button.
    if ($action == 'quote') {
        $form->addButtonCreate(get_lang('QuoteMessage'), 'SubmitPost');
    } elseif ($action == 'replythread') {
        $form->addButtonCreate(get_lang('ReplyToThread'), 'SubmitPost');
    } elseif ($action == 'replymessage') {
        $form->addButtonCreate(get_lang('ReplyToMessage'), 'SubmitPost');
    } else {
        $form->addButtonCreate(get_lang('CreateThread'), 'SubmitPost');
    }
    if (!empty($form_values)) {
        $defaults['post_title'] = prepare4display($form_values['post_title']);
        $defaults['post_text'] = prepare4display($form_values['post_text']);
        $defaults['post_notification'] = strval(intval($form_values['post_notification']));
        $defaults['thread_sticky'] = strval(intval($form_values['thread_sticky']));
        $defaults['thread_peer_qualify'] = intval($form_values['thread_peer_qualify']);
    } else {
        $defaults['thread_peer_qualify'] = 0;
    }
    // If we are quoting a message we have to retrieve the information of the post we are quoting so that
    // we can add this as default to the textarea.
    if (($action == 'quote' || $action == 'replymessage') && isset($my_post)) {
        // We also need to put the parent_id of the post in a hidden form when
        // we are quoting or replying to a message (<> reply to a thread !!!)
        $form->addElement('hidden', 'post_parent_id', intval($my_post));
        // If we are replying or are quoting then we display a default title.
        $values = get_post_information($my_post);
        $defaults['post_title'] = get_lang('ReplyShort') . api_html_entity_decode($values['post_title'], ENT_QUOTES);
        // When we are quoting a message then we have to put that message into the wysiwyg editor.
        // Note: The style has to be hardcoded here because using class="quote" didn't work.
        if ($action == 'quote') {
            $defaults['post_text'] = '<div>&nbsp;</div><div style="margin: 5px;"><div style="font-size: 90%; font-style: italic;">' . get_lang('Quoting') . ' ' . api_get_person_name($values['firstname'], $values['lastname']) . ':</div><div style="color: #006600; font-size: 90%;  font-style: italic; background-color: #FAFAFA; border: #D1D7DC 1px solid; padding: 3px;">' . prepare4display($values['post_text']) . '</div></div><div>&nbsp;</div><div>&nbsp;</div>';
        }
    }
    $form->setDefaults(isset($defaults) ? $defaults : null);
    // The course admin can make a thread sticky (=appears with special icon and always on top).
    $form->addRule('post_title', get_lang('ThisFieldIsRequired'), 'required');
    if ($current_forum['allow_anonymous'] == 1 && !isset($_user['user_id'])) {
        $form->addRule('poster_name', get_lang('ThisFieldIsRequired'), 'required');
    }
    // Validation or display
    if ($form->validate()) {
        $check = Security::check_token('post');
        if ($check) {
            $values = $form->exportValues();
            if (isset($values['thread_qualify_gradebook']) && $values['thread_qualify_gradebook'] == '1' && empty($values['weight_calification'])) {
                Display::display_error_message(get_lang('YouMustAssignWeightOfQualification') . '&nbsp;<a href="javascript:window.history.go(-1);">' . get_lang('Back') . '</a>', false);
                return false;
            }
            Security::clear_token();
            return $values;
        }
    } else {
        $token = Security::get_token();
        $form->addElement('hidden', 'sec_token');
        $form->setConstants(array('sec_token' => $token));
        // Delete from $_SESSION forum attachment from other posts
        // and keep only attachments for new post
        clearAttachedFiles(FORUM_NEW_POST);
        // Get forum attachment ajax table to add it to form
        $attachmentAjaxTable = getAttachmentsAjaxTable(0, $current_forum['forum_id']);
        $ajaxHtml = $attachmentAjaxTable;
        $form->addElement('html', $ajaxHtml);
        $form->display();
    }
}
 /**
  * Exports the complete report as an XLS file
  * @return	boolean		False on error
  */
 public function exportCompleteReportXLS($document_path = '', $user_id = null, $export_user_fields = false, $export_filter = 0, $exercise_id = 0, $hotpotato_name = null)
 {
     global $charset;
     $this->getExercisesReporting($document_path, $user_id, $export_filter, $exercise_id, $hotpotato_name);
     $filename = 'exercise_results_' . date('YmdGis') . '.xls';
     if (!empty($user_id)) {
         $filename = 'exercise_results_user_' . $user_id . '_' . date('YmdGis') . '.xls';
     }
     $workbook = new Spreadsheet_Excel_Writer();
     $workbook->setTempDir(api_get_path(SYS_ARCHIVE_PATH));
     $workbook->setVersion(8);
     // BIFF8
     $workbook->send($filename);
     $worksheet =& $workbook->addWorksheet('Report ' . date('YmdGis'));
     $worksheet->setInputEncoding(api_get_system_encoding());
     $line = 0;
     $column = 0;
     //skip the first column (row titles)
     // check if exists column 'user'
     $with_column_user = false;
     foreach ($this->results as $result) {
         if (!empty($result['last_name']) && !empty($result['first_name'])) {
             $with_column_user = true;
             break;
         }
     }
     if ($with_column_user) {
         $worksheet->write($line, $column, get_lang('Email'));
         $column++;
         if (api_is_western_name_order()) {
             $worksheet->write($line, $column, get_lang('FirstName'));
             $column++;
             $worksheet->write($line, $column, get_lang('LastName'));
             $column++;
         } else {
             $worksheet->write($line, $column, get_lang('LastName'));
             $column++;
             $worksheet->write($line, $column, get_lang('FirstName'));
             $column++;
         }
     }
     if ($export_user_fields) {
         //show user fields section with a big th colspan that spans over all fields
         $extra_user_fields = UserManager::get_extra_fields(0, 1000, 5, 'ASC', false, 1);
         //show the fields names for user fields
         foreach ($extra_user_fields as $field) {
             $worksheet->write($line, $column, api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES, $charset));
             $column++;
         }
     }
     $worksheet->write($line, $column, get_lang('Title'));
     $column++;
     $worksheet->write($line, $column, get_lang('StartDate'));
     $column++;
     $worksheet->write($line, $column, get_lang('EndDate'));
     $column++;
     $worksheet->write($line, $column, get_lang('Duration') . ' (' . get_lang('MinMinutes') . ')');
     $column++;
     $worksheet->write($line, $column, get_lang('Score'));
     $column++;
     $worksheet->write($line, $column, get_lang('Total'));
     $column++;
     $worksheet->write($line, $column, get_lang('Status'));
     $line++;
     foreach ($this->results as $row) {
         $column = 0;
         if ($with_column_user) {
             $worksheet->write($line, $column, api_html_entity_decode(strip_tags($row['email']), ENT_QUOTES, $charset));
             $column++;
             if (api_is_western_name_order()) {
                 $worksheet->write($line, $column, api_html_entity_decode(strip_tags($row['first_name']), ENT_QUOTES, $charset));
                 $column++;
                 $worksheet->write($line, $column, api_html_entity_decode(strip_tags($row['last_name']), ENT_QUOTES, $charset));
                 $column++;
             } else {
                 $worksheet->write($line, $column, api_html_entity_decode(strip_tags($row['last_name']), ENT_QUOTES, $charset));
                 $column++;
                 $worksheet->write($line, $column, api_html_entity_decode(strip_tags($row['first_name']), ENT_QUOTES, $charset));
                 $column++;
             }
         }
         if ($export_user_fields) {
             //show user fields data, if any, for this user
             $user_fields_values = UserManager::get_extra_user_data($row['user_id'], false, false, false, true);
             foreach ($user_fields_values as $value) {
                 $worksheet->write($line, $column, api_html_entity_decode(strip_tags($value), ENT_QUOTES, $charset));
                 $column++;
             }
         }
         $worksheet->write($line, $column, api_html_entity_decode(strip_tags($row['title']), ENT_QUOTES, $charset));
         $column++;
         $worksheet->write($line, $column, $row['start_date']);
         $column++;
         $worksheet->write($line, $column, $row['end_date']);
         $column++;
         $worksheet->write($line, $column, $row['duration']);
         $column++;
         $worksheet->write($line, $column, $row['result']);
         $column++;
         $worksheet->write($line, $column, $row['max']);
         $column++;
         $worksheet->write($line, $column, $row['status']);
         $line++;
     }
     $workbook->close();
     return true;
 }
Example #14
0
    }
    /*
     * Export to a CSV file
     * force the browser to save the file instead of opening it
     */
    $len = strlen($title_line . $line);
    header('Content-type: application/octet-stream');
    //header('Content-Type: application/force-download');
    header('Content-length: ' . $len);
    $filename = html_entity_decode(str_replace(":", "", str_replace(" ", "_", $title[0] . '_' . $title[1] . '.csv')));
    $filename = api_replace_dangerous_char($filename);
    if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
        header('Content-Disposition: filename= ' . $filename);
    } else {
        header('Content-Disposition: attachment; filename= ' . $filename);
    }
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
        header('Pragma: ');
        header('Cache-Control: ');
        header('Cache-Control: public');
        // IE cannot download from sessions without a cache
    }
    header('Content-Description: ' . $filename);
    header('Content-transfer-encoding: binary');
    echo api_html_entity_decode($title_line, ENT_QUOTES, $charset);
    echo api_html_entity_decode($line, ENT_QUOTES, $charset);
    exit;
} else {
    // not allowed
    api_not_allowed();
}
Example #15
0
/**
 * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully)
 * Sender name and email can be specified, if not specified
 * name and email of the platform admin are used
 *
 * @author Bert Vanderkimpen ICT&O UGent
 * @author Yannick Warnier <*****@*****.**>
 *
 * @param string    name of recipient
 * @param string    email of recipient
 * @param string    email subject
 * @param string    email body
 * @param string    sender name
 * @param string    sender e-mail
 * @param array     extra headers in form $headers = array($name => $value) to allow parsing
 * @param array     data file (path and filename)
 * @param array     data to attach a file (optional)
 * @param bool      True for attaching a embedded file inside content html (optional)
 * @return          returns true if mail was sent
 * @see             class.phpmailer.php
 */
function api_mail_html($recipient_name, $recipient_email, $subject, $message, $senderName = '', $senderEmail = '', $extra_headers = array(), $data_file = array(), $embedded_image = false, $additionalParameters = array())
{
    // Default values
    $notification = new Notification();
    $defaultEmail = $notification->getDefaultPlatformSenderEmail();
    $defaultName = $notification->getDefaultPlatformSenderName();
    // If the parameter is set don't use the admin.
    $senderName = !empty($senderName) ? $senderName : $defaultName;
    $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultEmail;
    $link = isset($additionalParameters['link']) ? $additionalParameters['link'] : '';
    $swiftMessage = \Swift_Message::newInstance()->setSubject($subject)->setFrom($senderEmail, $senderName)->setTo($recipient_email, $recipient_name)->setBody(Container::getTemplating()->render('ChamiloCoreBundle:default/mail:mail.html.twig', array('content' => $message, 'link' => $link)), 'text/html');
    if (!empty($additionalParameters)) {
        $plugin = new AppPlugin();
        $smsPlugin = $plugin->getSMSPluginLibrary();
        if ($smsPlugin) {
            $smsPlugin->send($additionalParameters);
        }
    }
    Container::getMailer()->send($swiftMessage);
    return 1;
    global $platform_email;
    $mail = new PHPMailer();
    $mail->Mailer = $platform_email['SMTP_MAILER'];
    $mail->Host = $platform_email['SMTP_HOST'];
    $mail->Port = $platform_email['SMTP_PORT'];
    $mail->CharSet = $platform_email['SMTP_CHARSET'];
    // Stay far below SMTP protocol 980 chars limit.
    $mail->WordWrap = 200;
    if ($platform_email['SMTP_AUTH']) {
        $mail->SMTPAuth = 1;
        $mail->Username = $platform_email['SMTP_USER'];
        $mail->Password = $platform_email['SMTP_PASS'];
    }
    // 5 = low, 1 = high
    $mail->Priority = 3;
    $mail->SMTPKeepAlive = true;
    // Default values
    $notification = new Notification();
    $defaultEmail = $notification->getDefaultPlatformSenderEmail();
    $defaultName = $notification->getDefaultPlatformSenderName();
    // Error to admin.
    $mail->AddCustomHeader('Errors-To: ' . $defaultEmail);
    // If the parameter is set don't use the admin.
    $senderName = !empty($senderName) ? $senderName : $defaultName;
    $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultEmail;
    // Reply to first
    if (isset($extra_headers['reply_to'])) {
        $mail->AddReplyTo($extra_headers['reply_to']['mail'], $extra_headers['reply_to']['name']);
        $mail->Sender = $extra_headers['reply_to']['mail'];
        unset($extra_headers['reply_to']);
    }
    //If the SMTP configuration only accept one sender
    if ($platform_email['SMTP_UNIQUE_SENDER']) {
        $senderName = $platform_email['SMTP_FROM_NAME'];
        $senderEmail = $platform_email['SMTP_FROM_EMAIL'];
    }
    $mail->SetFrom($senderEmail, $senderName);
    $mail->Subject = $subject;
    $mail->AltBody = strip_tags(str_replace('<br />', "\n", api_html_entity_decode($message)));
    // Send embedded image.
    if ($embedded_image) {
        // Get all images html inside content.
        preg_match_all("/<img\\s+.*?src=[\"\\']?([^\"\\' >]*)[\"\\']?[^>]*>/i", $message, $m);
        // Prepare new tag images.
        $new_images_html = array();
        $i = 1;
        if (!empty($m[1])) {
            foreach ($m[1] as $image_path) {
                $real_path = realpath($image_path);
                $filename = basename($image_path);
                $image_cid = $filename . '_' . $i;
                $encoding = 'base64';
                $image_type = mime_content_type($real_path);
                $mail->AddEmbeddedImage($real_path, $image_cid, $filename, $encoding, $image_type);
                $new_images_html[] = '<img src="cid:' . $image_cid . '" />';
                $i++;
            }
        }
        // Replace origin image for new embedded image html.
        $x = 0;
        if (!empty($m[0])) {
            foreach ($m[0] as $orig_img) {
                $message = str_replace($orig_img, $new_images_html[$x], $message);
                $x++;
            }
        }
    }
    $message = str_replace(array("\n\r", "\n", "\r"), '<br />', $message);
    $mailView = new Template(null, false, false, false, false, false, false);
    $mailView->assign('content', $message);
    $link = $additionalParameters['link'];
    $mailView->assign('link', $link);
    $layout = $mailView->get_template('mail/mail.tpl');
    $mail->Body = $mailView->fetch($layout);
    // Attachment ...
    if (!empty($data_file)) {
        $mail->AddAttachment($data_file['path'], $data_file['filename']);
    }
    // Only valid addresses are accepted.
    if (is_array($recipient_email)) {
        foreach ($recipient_email as $dest) {
            if (api_valid_email($dest)) {
                $mail->AddAddress($dest, $recipient_name);
            }
        }
    } else {
        if (api_valid_email($recipient_email)) {
            $mail->AddAddress($recipient_email, $recipient_name);
        } else {
            return 0;
        }
    }
    if (is_array($extra_headers) && count($extra_headers) > 0) {
        foreach ($extra_headers as $key => $value) {
            switch (strtolower($key)) {
                case 'encoding':
                case 'content-transfer-encoding':
                    $mail->Encoding = $value;
                    break;
                case 'charset':
                    $mail->Charset = $value;
                    break;
                case 'contenttype':
                case 'content-type':
                    $mail->ContentType = $value;
                    break;
                default:
                    $mail->AddCustomHeader($key . ':' . $value);
                    break;
            }
        }
    } else {
        if (!empty($extra_headers)) {
            $mail->AddCustomHeader($extra_headers);
        }
    }
    // WordWrap the html body (phpMailer only fixes AltBody) FS#2988
    $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap);
    // Send the mail message.
    if (!$mail->Send()) {
        error_log('ERROR: mail not sent to ' . $recipient_name . ' (' . $recipient_email . ') because of ' . $mail->ErrorInfo . '<br />');
        return 0;
    }
    if (!empty($additionalParameters)) {
        $plugin = new AppPlugin();
        $smsPlugin = $plugin->getSMSPluginLibrary();
        if ($smsPlugin) {
            $smsPlugin->send($additionalParameters);
        }
    }
    // Clear all the addresses.
    $mail->ClearAddresses();
    return 1;
}
    }
    $perId[$eid_id] = ($pi = $perId[$eid_id]) ? $pi + 1 : 1;
}
if (isset($sdi)) {
    $mdo = new mdobject($_course, $sdi);
    echo '<br />', htmlspecialchars($mdo->mdo_path, ENT_QUOTES, $charset), ', SD-id ', $sdi, ': ', $perId[$sdi] ? $perId[$sdi] : '0', ' ', $mdtmain[$sdi] ? '- <span class="lbs" onClick="' . "makeWindow('index.php?eid=" . EID_TYPE . '.' . $sdi . "', '', '')\">" . get_lang('MainMD') . '</span>' : '', "\n";
}
if (count($perId)) {
    foreach ($perId as $id => $number) {
        $mdo = new mdobject($_course, $id);
        if (!($pth = $mdo->mdo_path)) {
            $pth = $mdtmain[$id];
            // fetch something simple without parsing
            if ($ttopen = strpos($pth, '<title>')) {
                if ($ttclose = strpos($pth, '</title>', $ttopen)) {
                    $pth = ' ' . api_html_entity_decode(substr($pth, $ttopen + 7, $ttclose - $ttopen - 7), ENT_QUOTES, $charset);
                } else {
                    $pth = ' ' . substr($pth, $ttopen + 7, 30);
                }
            } else {
                $pth = ' ' . substr($pth, 0, 30);
            }
        }
        $pathId[$pth] = $id;
    }
    echo '<br><br><table>', "\n";
    ksort($pathId);
    $wwl = strlen($workWith);
    foreach ($pathId as $pth => $id) {
        if ($wwl == 0 || $wwl < strlen($pth) && substr($pth, 0, $wwl) == $workWith) {
            $tmfdt = file_exists($tfmff = $baseWorkDir . $pth . '/' . MFFNAME . $sdisub . MFFDEXT) ? date('Y/m/d H:i:s', filemtime($tfmff)) : '-';
Example #17
0
 /**
  * Returns a list of answers
  * @author Yannick Warnier <*****@*****.**>
  * @return array	List of answers where each answer is an array
  * of (id, answer, comment, grade) and grade=weighting
  */
 public function getAnswersList($decode = false)
 {
     $list = array();
     for ($i = 1; $i <= $this->nbrAnswers; $i++) {
         if (!empty($this->answer[$i])) {
             //Avoid problems when parsing elements with accents
             if ($decode) {
                 $this->answer[$i] = api_html_entity_decode($this->answer[$i], ENT_QUOTES, api_get_system_encoding());
                 $this->comment[$i] = api_html_entity_decode($this->comment[$i], ENT_QUOTES, api_get_system_encoding());
             }
             $list[] = array('id' => $i, 'answer' => $this->answer[$i], 'comment' => $this->comment[$i], 'grade' => $this->weighting[$i], 'hotspot_coord' => $this->hotspot_coordinates[$i], 'hotspot_type' => $this->hotspot_type[$i], 'correct' => $this->correct[$i], 'destination' => $this->destination[$i]);
         }
     }
     return $list;
 }
Example #18
0
 /**
  * Get data for courses list in sortable with pagination
  * @return array
  */
 public static function get_course_data($from, $number_of_items, $column, $direction)
 {
     global $courses, $csv_content, $charset, $session_id;
     // definition database tables
     $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
     $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
     $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $course_data = array();
     $courses_code = array_keys($courses);
     foreach ($courses_code as &$code) {
         $code = "'{$code}'";
     }
     // get all courses with limit
     $sql = "SELECT course.code as col1, course.title as col2\n                FROM {$tbl_course} course\n                WHERE course.code IN (" . implode(',', $courses_code) . ")";
     if (!in_array($direction, array('ASC', 'DESC'))) {
         $direction = 'ASC';
     }
     $column = intval($column);
     $from = intval($from);
     $number_of_items = intval($number_of_items);
     $sql .= " ORDER BY col{$column} {$direction} ";
     $sql .= " LIMIT {$from},{$number_of_items}";
     $res = Database::query($sql);
     while ($row_course = Database::fetch_row($res)) {
         $course_code = $row_course[0];
         $courseInfo = api_get_course_info($course_code);
         $courseId = $courseInfo['real_id'];
         $avg_assignments_in_course = $avg_messages_in_course = $nb_students_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = $avg_score_in_exercise = 0;
         // students directly subscribed to the course
         if (empty($session_id)) {
             $sql = "SELECT user_id\n                        FROM {$tbl_course_user} as course_rel_user\n                        WHERE\n                            course_rel_user.status='5' AND\n                            course_rel_user.c_id = '{$courseId}'";
         } else {
             $sql = "SELECT user_id FROM {$tbl_session_course_user} srcu\n                        WHERE\n                            c_id = '{$courseId}' AND\n                            session_id = '{$session_id}' AND\n                            status<>2";
         }
         $rs = Database::query($sql);
         $users = array();
         while ($row = Database::fetch_array($rs)) {
             $users[] = $row['user_id'];
         }
         if (count($users) > 0) {
             $nb_students_in_course = count($users);
             $avg_assignments_in_course = Tracking::count_student_assignments($users, $course_code, $session_id);
             $avg_messages_in_course = Tracking::count_student_messages($users, $course_code, $session_id);
             $avg_progress_in_course = Tracking::get_avg_student_progress($users, $course_code, array(), $session_id);
             $avg_score_in_course = Tracking::get_avg_student_score($users, $course_code, array(), $session_id);
             $avg_score_in_exercise = Tracking::get_avg_student_exercise_score($users, $course_code, 0, $session_id);
             $avg_time_spent_in_course = Tracking::get_time_spent_on_the_course($users, $courseInfo['real_id'], $session_id);
             $avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2);
             if (is_numeric($avg_score_in_course)) {
                 $avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2);
             }
             $avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
         } else {
             $avg_time_spent_in_course = null;
             $avg_progress_in_course = null;
             $avg_score_in_course = null;
             $avg_score_in_exercise = null;
             $avg_messages_in_course = null;
             $avg_assignments_in_course = null;
         }
         $table_row = array();
         $table_row[] = $row_course[1];
         $table_row[] = $nb_students_in_course;
         $table_row[] = $avg_time_spent_in_course;
         $table_row[] = is_null($avg_progress_in_course) ? '' : $avg_progress_in_course . '%';
         $table_row[] = is_null($avg_score_in_course) ? '' : $avg_score_in_course . '%';
         $table_row[] = is_null($avg_score_in_exercise) ? '' : $avg_score_in_exercise . '%';
         $table_row[] = $avg_messages_in_course;
         $table_row[] = $avg_assignments_in_course;
         //set the "from" value to know if I access the Reporting by the chamilo tab or the course link
         $table_row[] = '<center><a href="../../tracking/courseLog.php?cidReq=' . $course_code . '&from=myspace&id_session=' . $session_id . '">
                          <img src="' . api_get_path(WEB_IMG_PATH) . 'icons/22/2rightarrow.png" border="0" /></a>
                         </center>';
         $csv_content[] = array(api_html_entity_decode($row_course[1], ENT_QUOTES, $charset), $nb_students_in_course, $avg_time_spent_in_course, is_null($avg_progress_in_course) ? null : $avg_progress_in_course . '%', is_null($avg_score_in_course) ? null : is_numeric($avg_score_in_course) ? $avg_score_in_course . '%' : $avg_score_in_course, is_null($avg_score_in_exercise) ? null : $avg_score_in_exercise . '%', $avg_messages_in_course, $avg_assignments_in_course);
         $course_data[] = $table_row;
     }
     return $course_data;
 }
Example #19
0
 /**
  * @param int $user_id
  * @param array $courseInfo
  * @param int $session_id
  * @param string $origin
  * @param bool $export_csv
  * @param int $lp_id
  * @param int $lp_item_id
  * @param int $extendId
  * @param int $extendAttemptId
  * @param string $extendedAttempt
  * @param string $extendedAll
  * @param string $type classic or simple
  * @param boolean $allowExtend Optional. Allow or not extend te results
  * @return null|string
  */
 public static function getLpStats($user_id, $courseInfo, $session_id, $origin, $export_csv, $lp_id, $lp_item_id = null, $extendId = null, $extendAttemptId = null, $extendedAttempt = null, $extendedAll = null, $type = 'classic', $allowExtend = true)
 {
     if (empty($courseInfo) || empty($lp_id)) {
         return null;
     }
     $lp_id = intval($lp_id);
     $lp_item_id = intval($lp_item_id);
     $user_id = intval($user_id);
     $session_id = intval($session_id);
     $origin = Security::remove_XSS($origin);
     $list = learnpath::get_flat_ordered_items_list($lp_id, 0, $courseInfo['real_id']);
     $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
     $course_id = $courseInfo['real_id'];
     $courseCode = $courseInfo['code'];
     $session_condition = api_get_session_condition($session_id);
     // Extend all button
     $output = null;
     $extend_all = 0;
     if ($origin == 'tracking') {
         $url_suffix = '&session_id=' . $session_id . '&course=' . $courseCode . '&student_id=' . $user_id . '&lp_id=' . $lp_id . '&origin=' . $origin;
     } else {
         $url_suffix = '&lp_id=' . $lp_id;
     }
     if (!empty($extendedAll)) {
         $extend_all_link = Display::url(Display::return_icon('view_less_stats.gif', get_lang('HideAllAttempts')), api_get_self() . '?action=stats' . $url_suffix);
         $extend_all = 1;
     } else {
         $extend_all_link = Display::url(Display::return_icon('view_more_stats.gif', get_lang('ShowAllAttempts')), api_get_self() . '?action=stats&extend_all=1' . $url_suffix);
     }
     if ($origin != 'tracking') {
         $output .= '<div class="section-status">';
         $output .= Display::page_header(get_lang('ScormMystatus'));
         $output .= '</div>';
     }
     $actionColumn = null;
     if ($type == 'classic') {
         $actionColumn = ' <th>' . get_lang('Actions') . '</th>';
     }
     $output .= '<div class="table-responsive">';
     $output .= '<table class="table tracking">
         <thead>
         <tr class="table-header">
             <th width="16">' . ($allowExtend == true ? $extend_all_link : '&nbsp;') . '</th>
             <th colspan="4">
                 ' . get_lang('ScormLessonTitle') . '
             </th>
             <th colspan="2">
                 ' . get_lang('ScormStatus') . '
             </th>
             <th colspan="2">
                 ' . get_lang('ScormScore') . '
             </th>
             <th colspan="2">
                 ' . get_lang('ScormTime') . '
             </th>
             ' . $actionColumn . '
             </tr>
         </thead>
         <tbody>
     ';
     // Going through the items using the $items[] array instead of the database order ensures
     // we get them in the same order as in the imsmanifest file, which is rather random when using
     // the database table.
     $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
     $TBL_LP_ITEM_VIEW = Database::get_course_table(TABLE_LP_ITEM_VIEW);
     $TBL_LP_VIEW = Database::get_course_table(TABLE_LP_VIEW);
     $tbl_quiz_questions = Database::get_course_table(TABLE_QUIZ_QUESTION);
     $TBL_QUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
     $tbl_stats_exercices = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
     $tbl_stats_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $sql = "SELECT max(view_count)\n                FROM {$TBL_LP_VIEW}\n                WHERE\n                    c_id = {$course_id} AND\n                    lp_id = {$lp_id} AND\n                    user_id = {$user_id}\n                    {$session_condition}";
     $res = Database::query($sql);
     $view = '';
     if (Database::num_rows($res) > 0) {
         $myrow = Database::fetch_array($res);
         $view = $myrow[0];
     }
     $counter = 0;
     $total_time = 0;
     $h = get_lang('h');
     if (!empty($export_csv)) {
         $csv_content[] = array(get_lang('ScormLessonTitle'), get_lang('ScormStatus'), get_lang('ScormScore'), get_lang('ScormTime'));
     }
     $result_disabled_ext_all = true;
     $chapterTypes = learnpath::getChapterTypes();
     // Show lp items
     if (is_array($list) && count($list) > 0) {
         foreach ($list as $my_item_id) {
             $extend_this = 0;
             $order = 'DESC';
             if (!empty($extendId) && $extendId == $my_item_id || $extend_all) {
                 $extend_this = 1;
                 $order = 'ASC';
             }
             // Prepare statement to go through each attempt.
             $viewCondition = null;
             if (!empty($view)) {
                 $viewCondition = " AND v.view_count = {$view}  ";
             }
             $sql = "SELECT\n                    iv.status as mystatus,\n                    v.view_count as mycount,\n                    iv.score as myscore,\n                    iv.total_time as mytime,\n                    i.id as myid,\n                    i.lp_id as mylpid,\n                    iv.lp_view_id as mylpviewid,\n                    i.title as mytitle,\n                    i.max_score as mymaxscore,\n                    iv.max_score as myviewmaxscore,\n                    i.item_type as item_type,\n                    iv.view_count as iv_view_count,\n                    iv.id as iv_id,\n                    path\n                FROM {$TBL_LP_ITEM} as i\n                INNER JOIN {$TBL_LP_ITEM_VIEW} as iv\n                ON (i.id = iv.lp_item_id AND i.c_id = iv.c_id)\n                INNER JOIN {$TBL_LP_VIEW} as v\n                ON (iv.lp_view_id = v.id AND v.c_id = iv.c_id)\n                WHERE\n                    v.c_id = {$course_id} AND\n                    i.id = {$my_item_id} AND\n                    i.lp_id = {$lp_id}  AND\n                    v.user_id = {$user_id} AND\n                    v.session_id = {$session_id}\n                    {$viewCondition}\n                ORDER BY iv.view_count {$order} ";
             $result = Database::query($sql);
             $num = Database::num_rows($result);
             $time_for_total = 'NaN';
             // Extend all
             if (($extend_this || $extend_all) && $num > 0) {
                 $row = Database::fetch_array($result);
                 $result_disabled_ext_all = false;
                 if ($row['item_type'] == 'quiz') {
                     // Check results_disabled in quiz table.
                     $my_path = Database::escape_string($row['path']);
                     $sql = "SELECT results_disabled\n                                FROM {$TBL_QUIZ}\n                                WHERE\n                                    c_id = {$course_id} AND\n                                    id ='" . $my_path . "'";
                     $res_result_disabled = Database::query($sql);
                     $row_result_disabled = Database::fetch_row($res_result_disabled);
                     if (Database::num_rows($res_result_disabled) > 0 && (int) $row_result_disabled[0] === 1) {
                         $result_disabled_ext_all = true;
                     }
                 }
                 // If there are several attempts, and the link to extend has been clicked, show each attempt...
                 if ($counter % 2 == 0) {
                     $oddclass = 'row_odd';
                 } else {
                     $oddclass = 'row_even';
                 }
                 $extend_link = '';
                 if (!empty($inter_num)) {
                     $extend_link = Display::url(Display::return_icon('visible.gif', get_lang('HideAttemptView')), api_get_self() . '?action=stats&fold_id=' . $my_item_id . $url_suffix);
                 }
                 $title = $row['mytitle'];
                 if (empty($title)) {
                     $title = rl_get_resource_name($courseInfo['code'], $lp_id, $row['myid']);
                 }
                 if (in_array($row['item_type'], $chapterTypes)) {
                     $title = "<h4> {$title} </h4>";
                 }
                 $lesson_status = $row['mystatus'];
                 $title = Security::remove_XSS($title);
                 $counter++;
                 $action = null;
                 if ($type == 'classic') {
                     $action = '<td></td>';
                 }
                 if (in_array($row['item_type'], $chapterTypes)) {
                     $output .= '<tr class="' . $oddclass . '">
                             <td>' . $extend_link . '</td>
                             <td colspan="4">
                                ' . $title . '
                             </td>
                             <td colspan="2">' . learnpathItem::humanize_status($lesson_status, true, $type) . '</td>
                             <td colspan="2"></td>
                             <td colspan="2"></td>
                             ' . $action . '
                         </tr>';
                     continue;
                 } else {
                     $output .= '<tr class="' . $oddclass . '">
                             <td>' . $extend_link . '</td>
                             <td colspan="4">
                                ' . $title . '
                             </td>
                             <td colspan="2"></td>
                             <td colspan="2"></td>
                             <td colspan="2"></td>
                             ' . $action . '
                         </tr>';
                 }
                 $attemptCount = 1;
                 do {
                     // Check if there are interactions below.
                     $extend_attempt_link = '';
                     $extend_this_attempt = 0;
                     if ((learnpath::get_interactions_count_from_db($row['iv_id'], $course_id) > 0 || learnpath::get_objectives_count_from_db($row['iv_id'], $course_id) > 0) && !$extend_all) {
                         if ($extendAttemptId == $row['iv_id']) {
                             // The extend button for this attempt has been clicked.
                             $extend_this_attempt = 1;
                             $extend_attempt_link = Display::url(Display::return_icon('visible.gif', get_lang('HideAttemptView')), api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&fold_attempt_id=' . $row['iv_id'] . $url_suffix);
                         } else {
                             // Same case if fold_attempt_id is set, so not implemented explicitly.
                             // The extend button for this attempt has not been clicked.
                             $extend_attempt_link = Display::url(Display::return_icon('invisible.gif', get_lang('ExtendAttemptView')), api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix);
                         }
                     }
                     if ($counter % 2 == 0) {
                         $oddclass = 'row_odd';
                     } else {
                         $oddclass = 'row_even';
                     }
                     $lesson_status = $row['mystatus'];
                     $score = $row['myscore'];
                     $time_for_total = $row['mytime'];
                     $time = learnpathItem::getScormTimeFromParameter('js', $row['mytime']);
                     if ($score == 0) {
                         $maxscore = $row['mymaxscore'];
                     } else {
                         if ($row['item_type'] == 'sco') {
                             if (!empty($row['myviewmaxscore']) && $row['myviewmaxscore'] > 0) {
                                 $maxscore = $row['myviewmaxscore'];
                             } elseif ($row['myviewmaxscore'] === '') {
                                 $maxscore = 0;
                             } else {
                                 $maxscore = $row['mymaxscore'];
                             }
                         } else {
                             $maxscore = $row['mymaxscore'];
                         }
                     }
                     // Remove "NaN" if any (@todo: locate the source of these NaN)
                     $time = str_replace('NaN', '00' . $h . '00\'00"', $time);
                     if ($row['item_type'] != 'dokeos_chapter') {
                         if (!$is_allowed_to_edit && $result_disabled_ext_all) {
                             $view_score = Display::return_icon('invisible.gif', get_lang('ResultsHiddenByExerciseSetting'));
                         } else {
                             switch ($row['item_type']) {
                                 case 'sco':
                                     if ($maxscore == 0) {
                                         $view_score = $score;
                                     } else {
                                         $view_score = ExerciseLib::show_score($score, $maxscore, false);
                                     }
                                     break;
                                 case 'document':
                                     $view_score = $score == 0 ? '/' : ExerciseLib::show_score($score, $maxscore, false);
                                     break;
                                 default:
                                     $view_score = ExerciseLib::show_score($score, $maxscore, false);
                                     break;
                             }
                         }
                         $action = null;
                         if ($type == 'classic') {
                             $action = '<td></td>';
                         }
                         $output .= '<tr class="' . $oddclass . '">
                                 <td></td>
                                 <td>' . $extend_attempt_link . '</td>
                                 <td colspan="3">' . get_lang('Attempt') . ' ' . $attemptCount . '</td>
                                 <td colspan="2">' . learnpathItem::humanize_status($lesson_status, true, $type) . '</td>
                                 <td colspan="2">' . $view_score . '</td>
                                 <td colspan="2">' . $time . '</td>
                                 ' . $action . '
                             </tr>';
                         $attemptCount++;
                         if (!empty($export_csv)) {
                             $temp = array();
                             $temp[] = $title = Security::remove_XSS($title);
                             $temp[] = Security::remove_XSS(learnpathItem::humanize_status($lesson_status, false, $type));
                             if ($row['item_type'] == 'quiz') {
                                 if (!$is_allowed_to_edit && $result_disabled_ext_all) {
                                     $temp[] = '/';
                                 } else {
                                     $temp[] = $score == 0 ? '0/' . $maxscore : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1));
                                 }
                             } else {
                                 $temp[] = $score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1));
                             }
                             $temp[] = $time;
                             $csv_content[] = $temp;
                         }
                     }
                     $counter++;
                     $action = null;
                     if ($type == 'classic') {
                         $action = '<td></td>';
                     }
                     if ($extend_this_attempt || $extend_all) {
                         $list1 = learnpath::get_iv_interactions_array($row['iv_id']);
                         foreach ($list1 as $id => $interaction) {
                             if ($counter % 2 == 0) {
                                 $oddclass = 'row_odd';
                             } else {
                                 $oddclass = 'row_even';
                             }
                             $student_response = urldecode($interaction['student_response']);
                             $content_student_response = explode('__|', $student_response);
                             if (count($content_student_response) > 0) {
                                 if (count($content_student_response) >= 3) {
                                     // Pop the element off the end of array.
                                     array_pop($content_student_response);
                                 }
                                 $student_response = implode(',', $content_student_response);
                             }
                             $output .= '<tr class="' . $oddclass . '">
                                     <td></td>
                                     <td></td>
                                     <td></td>
                                     <td>' . $interaction['order_id'] . '</td>
                                     <td>' . $interaction['id'] . '</td>
                                     <td colspan="2">' . $interaction['type'] . '</td>
                                     <td>' . $student_response . '</td>
                                     <td>' . $interaction['result'] . '</td>
                                     <td>' . $interaction['latency'] . '</td>
                                     <td>' . $interaction['time'] . '</td>
                                     ' . $action . '
                                 </tr>';
                             $counter++;
                         }
                         $list2 = learnpath::get_iv_objectives_array($row['iv_id']);
                         foreach ($list2 as $id => $interaction) {
                             if ($counter % 2 == 0) {
                                 $oddclass = 'row_odd';
                             } else {
                                 $oddclass = 'row_even';
                             }
                             $output .= '<tr class="' . $oddclass . '">
                                     <td></td>
                                     <td></td>
                                     <td></td>
                                     <td>' . $interaction['order_id'] . '</td>
                                     <td colspan="2">' . $interaction['objective_id'] . '</td>
                                     <td colspan="2">' . $interaction['status'] . '</td>
                                     <td>' . $interaction['score_raw'] . '</td>
                                     <td>' . $interaction['score_max'] . '</td>
                                     <td>' . $interaction['score_min'] . '</td>
                                     ' . $action . '
                                  </tr>';
                             $counter++;
                         }
                     }
                 } while ($row = Database::fetch_array($result));
             } elseif ($num > 0) {
                 // Not extended.
                 $row = Database::fetch_array($result, 'ASSOC');
                 $my_id = $row['myid'];
                 $my_lp_id = $row['mylpid'];
                 $my_lp_view_id = $row['mylpviewid'];
                 $my_path = $row['path'];
                 $result_disabled_ext_all = false;
                 if ($row['item_type'] == 'quiz') {
                     // Check results_disabled in quiz table.
                     $my_path = Database::escape_string($my_path);
                     $sql = "SELECT results_disabled\n                                FROM {$TBL_QUIZ}\n                                WHERE c_id = {$course_id} AND id ='" . $my_path . "'";
                     $res_result_disabled = Database::query($sql);
                     $row_result_disabled = Database::fetch_row($res_result_disabled);
                     if (Database::num_rows($res_result_disabled) > 0 && (int) $row_result_disabled[0] === 1) {
                         $result_disabled_ext_all = true;
                     }
                 }
                 // Check if there are interactions below
                 $extend_this_attempt = 0;
                 $inter_num = learnpath::get_interactions_count_from_db($row['iv_id'], $course_id);
                 $objec_num = learnpath::get_objectives_count_from_db($row['iv_id'], $course_id);
                 $extend_attempt_link = '';
                 if ($inter_num > 0 || $objec_num > 0) {
                     if (!empty($extendAttemptId) && $extendAttemptId == $row['iv_id']) {
                         // The extend button for this attempt has been clicked.
                         $extend_this_attempt = 1;
                         $extend_attempt_link = Display::url(Display::return_icon('visible.gif', get_lang('HideAttemptView')), api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&fold_attempt_id=' . $row['iv_id'] . $url_suffix);
                     } else {
                         // Same case if fold_attempt_id is set, so not implemented explicitly.
                         // The extend button for this attempt has not been clicked.
                         $extend_attempt_link = Display::url(Display::return_icon('invisible.gif', get_lang('ExtendAttemptView')), api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix);
                     }
                 }
                 if ($counter % 2 == 0) {
                     $oddclass = 'row_odd';
                 } else {
                     $oddclass = 'row_even';
                 }
                 $extend_link = '';
                 if ($inter_num > 1) {
                     $extend_link = Display::url(Display::return_icon('invisible.gif', get_lang('ExtendAttemptView')), api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix);
                 }
                 $lesson_status = $row['mystatus'];
                 $score = $row['myscore'];
                 $subtotal_time = $row['mytime'];
                 while ($tmp_row = Database::fetch_array($result)) {
                     $subtotal_time += $tmp_row['mytime'];
                 }
                 $title = $row['mytitle'];
                 // Selecting the exe_id from stats attempts tables in order to look the max score value.
                 $sql = 'SELECT * FROM ' . $tbl_stats_exercices . '
                          WHERE
                             exe_exo_id="' . $row['path'] . '" AND
                             exe_user_id="' . $user_id . '" AND
                             orig_lp_id = "' . $lp_id . '" AND
                             orig_lp_item_id = "' . $row['myid'] . '" AND
                             c_id = ' . $course_id . ' AND
                             status <> "incomplete" AND
                             session_id = ' . $session_id . '
                          ORDER BY exe_date DESC
                          LIMIT 1';
                 $resultLastAttempt = Database::query($sql);
                 $num = Database::num_rows($resultLastAttempt);
                 $id_last_attempt = null;
                 if ($num > 0) {
                     while ($rowLA = Database::fetch_array($resultLastAttempt)) {
                         $id_last_attempt = $rowLA['exe_id'];
                     }
                 }
                 if ($score == 0) {
                     $maxscore = $row['mymaxscore'];
                 } else {
                     if ($row['item_type'] == 'sco') {
                         if (!empty($row['myviewmaxscore']) and $row['myviewmaxscore'] > 0) {
                             $maxscore = $row['myviewmaxscore'];
                         } elseif ($row['myviewmaxscore'] === '') {
                             $maxscore = 0;
                         } else {
                             $maxscore = $row['mymaxscore'];
                         }
                     } else {
                         if ($row['item_type'] == 'quiz') {
                             // Get score and total time from last attempt of a exercise en lp.
                             $sql = "SELECT score\n                                        FROM {$TBL_LP_ITEM_VIEW}\n                                        WHERE\n                                            c_id = {$course_id} AND\n                                            lp_item_id = '" . (int) $my_id . "' AND\n                                            lp_view_id = '" . (int) $my_lp_view_id . "'\n                                        ORDER BY view_count DESC limit 1";
                             $res_score = Database::query($sql);
                             $row_score = Database::fetch_array($res_score);
                             $sql = "SELECT SUM(total_time) as total_time\n                                        FROM {$TBL_LP_ITEM_VIEW}\n                                        WHERE\n                                            c_id = {$course_id} AND\n                                            lp_item_id = '" . (int) $my_id . "' AND\n                                            lp_view_id = '" . (int) $my_lp_view_id . "'";
                             $res_time = Database::query($sql);
                             $row_time = Database::fetch_array($res_time);
                             if (Database::num_rows($res_score) > 0 && Database::num_rows($res_time) > 0) {
                                 $score = (double) $row_score['score'];
                                 $subtotal_time = (int) $row_time['total_time'];
                             } else {
                                 $score = 0;
                                 $subtotal_time = 0;
                             }
                             // Selecting the max score from an attempt.
                             $sql = "SELECT SUM(t.ponderation) as maxscore\n                                        FROM (\n                                            SELECT DISTINCT\n                                                question_id, marks, ponderation\n                                            FROM {$tbl_stats_attempts} as at\n                                            INNER JOIN  {$tbl_quiz_questions} as q\n                                            ON (q.id = at.question_id AND q.c_id = {$course_id})\n                                            WHERE exe_id ='{$id_last_attempt}'\n                                        ) as t";
                             $result = Database::query($sql);
                             $row_max_score = Database::fetch_array($result);
                             $maxscore = $row_max_score['maxscore'];
                         } else {
                             $maxscore = $row['mymaxscore'];
                         }
                     }
                 }
                 $time_for_total = $subtotal_time;
                 $time = learnpathItem::getScormTimeFromParameter('js', $subtotal_time);
                 if (empty($title)) {
                     $title = rl_get_resource_name($courseInfo['code'], $lp_id, $row['myid']);
                 }
                 $action = null;
                 if ($type == 'classic') {
                     $action = '<td></td>';
                 }
                 if (in_array($row['item_type'], $chapterTypes)) {
                     $title = Security::remove_XSS($title);
                     $output .= '<tr class="' . $oddclass . '">
                             <td>' . $extend_link . '</td>
                             <td colspan="4">
                             <h4>' . $title . '</h4>
                             </td>
                             <td colspan="2">' . learnpathitem::humanize_status($lesson_status) . '</td>
                             <td colspan="2"></td>
                             <td colspan="2"></td>
                             ' . $action . '
                         </tr>';
                 } else {
                     $correct_test_link = '-';
                     if ($row['item_type'] == 'quiz') {
                         $my_url_suffix = '&course=' . $courseCode . '&student_id=' . $user_id . '&lp_id=' . intval($row['mylpid']) . '&origin=' . $origin;
                         $sql = 'SELECT * FROM ' . $tbl_stats_exercices . '
                                  WHERE
                                     exe_exo_id="' . $row['path'] . '" AND
                                     exe_user_id="' . $user_id . '" AND
                                     orig_lp_id = "' . $lp_id . '" AND
                                     orig_lp_item_id = "' . $row['myid'] . '" AND
                                     c_id = ' . $course_id . ' AND
                                     status <> "incomplete" AND
                                     session_id = ' . $session_id . '
                                  ORDER BY exe_date DESC ';
                         $resultLastAttempt = Database::query($sql);
                         $num = Database::num_rows($resultLastAttempt);
                         if ($num > 0) {
                             if ($extendedAttempt == 1 && $lp_id == $my_lp_id && $lp_item_id == $my_id) {
                                 $correct_test_link = Display::url(Display::return_icon('view_less_stats.gif', get_lang('HideAllAttempts')), api_get_self() . '?action=stats' . $my_url_suffix . '&session_id=' . $session_id . '&lp_item_id=' . $my_id);
                             } else {
                                 $correct_test_link = Display::url(Display::return_icon('view_more_stats.gif', get_lang('ShowAllAttemptsByExercise')), api_get_self() . '?action=stats&extend_attempt=1' . $my_url_suffix . '&session_id=' . $session_id . '&lp_item_id=' . $my_id);
                             }
                         }
                     }
                     $title = Security::remove_XSS($title);
                     $action = null;
                     if ($type == 'classic') {
                         $action = '<td>' . $correct_test_link . '</td>';
                     }
                     if ($lp_id == $my_lp_id && false) {
                         $output .= '<tr class =' . $oddclass . '>
                                 <td>' . $extend_link . '</td>
                                 <td colspan="4">' . $title . '</td>
                                 <td colspan="2">&nbsp;</td>
                                 <td colspan="2">&nbsp;</td>
                                 <td colspan="2">&nbsp;</td>
                                 ' . $action . '
                             </tr>';
                         $output .= '</tr>';
                     } else {
                         if ($lp_id == $my_lp_id && $lp_item_id == $my_id) {
                             $output .= "<tr class='{$oddclass}'>";
                         } else {
                             $output .= "<tr class='{$oddclass}'>";
                         }
                         $scoreItem = null;
                         if ($row['item_type'] == 'quiz') {
                             if (!$is_allowed_to_edit && $result_disabled_ext_all) {
                                 $scoreItem .= Display::return_icon('invisible.gif', get_lang('ResultsHiddenByExerciseSetting'));
                             } else {
                                 $scoreItem .= ExerciseLib::show_score($score, $maxscore, false);
                             }
                         } else {
                             $scoreItem .= $score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . $maxscore);
                         }
                         $output .= '
                             <td>' . $extend_link . '</td>
                             <td colspan="4">' . $title . '</td>
                             <td colspan="2">' . learnpathitem::humanize_status($lesson_status) . '</td>
                             <td colspan="2">' . $scoreItem . '</td>
                             <td colspan="2">' . $time . '</td>
                             ' . $action . '
                          ';
                         $output .= '</tr>';
                     }
                     if (!empty($export_csv)) {
                         $temp = array();
                         $temp[] = api_html_entity_decode($title, ENT_QUOTES);
                         $temp[] = api_html_entity_decode($lesson_status, ENT_QUOTES);
                         if ($row['item_type'] == 'quiz') {
                             if (!$is_allowed_to_edit && $result_disabled_ext_all) {
                                 $temp[] = '/';
                             } else {
                                 $temp[] = $score == 0 ? '0/' . $maxscore : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1));
                             }
                         } else {
                             $temp[] = $score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1));
                         }
                         $temp[] = $time;
                         $csv_content[] = $temp;
                     }
                 }
                 $counter++;
                 $action = null;
                 if ($type == 'classic') {
                     $action = '<td></td>';
                 }
                 if ($extend_this_attempt || $extend_all) {
                     $list1 = learnpath::get_iv_interactions_array($row['iv_id']);
                     foreach ($list1 as $id => $interaction) {
                         if ($counter % 2 == 0) {
                             $oddclass = 'row_odd';
                         } else {
                             $oddclass = 'row_even';
                         }
                         $output .= '<tr class="' . $oddclass . '">
                                 <td></td>
                                 <td></td>
                                 <td></td>
                                 <td>' . $interaction['order_id'] . '</td>
                                 <td>' . $interaction['id'] . '</td>
                                 <td colspan="2">' . $interaction['type'] . '</td>
                                 <td>' . urldecode($interaction['student_response']) . '</td>
                                 <td>' . $interaction['result'] . '</td>
                                 <td>' . $interaction['latency'] . '</td>
                                 <td>' . $interaction['time'] . '</td>
                                 ' . $action . '
                            </tr>';
                         $counter++;
                     }
                     $list2 = learnpath::get_iv_objectives_array($row['iv_id']);
                     foreach ($list2 as $id => $interaction) {
                         if ($counter % 2 == 0) {
                             $oddclass = 'row_odd';
                         } else {
                             $oddclass = 'row_even';
                         }
                         $output .= '<tr class="' . $oddclass . '">
                                 <td></td>
                                 <td></td>
                                 <td></td>
                                 <td>' . $interaction['order_id'] . '</td>
                                 <td colspan="2">' . $interaction['objective_id'] . '</td>
                                 <td colspan="2">' . $interaction['status'] . '</td>
                                 <td>' . $interaction['score_raw'] . '</td>
                                 <td>' . $interaction['score_max'] . '</td>
                                 <td>' . $interaction['score_min'] . '</td>
                                 ' . $action . '
                            </tr>';
                         $counter++;
                     }
                 }
                 // Attempts listing by exercise.
                 if ($lp_id == $my_lp_id && $lp_item_id == $my_id && $extendedAttempt) {
                     // Get attempts of a exercise.
                     if (!empty($lp_id) && !empty($lp_item_id) && $row['item_type'] === 'quiz') {
                         $sql = "SELECT path FROM {$TBL_LP_ITEM}\n                                    WHERE\n                                        c_id = {$course_id} AND\n                                        id = '{$lp_item_id}' AND\n                                        lp_id = '{$lp_id}'";
                         $res_path = Database::query($sql);
                         $row_path = Database::fetch_array($res_path);
                         if (Database::num_rows($res_path) > 0) {
                             $sql = 'SELECT * FROM ' . $tbl_stats_exercices . '
                                     WHERE
                                         exe_exo_id="' . (int) $row_path['path'] . '" AND
                                         status <> "incomplete" AND
                                         exe_user_id="' . $user_id . '" AND
                                         orig_lp_id = "' . (int) $lp_id . '" AND
                                         orig_lp_item_id = "' . (int) $lp_item_id . '" AND
                                         c_id = ' . $course_id . '  AND
                                         session_id = ' . $session_id . '
                                     ORDER BY exe_date';
                             $res_attempts = Database::query($sql);
                             $num_attempts = Database::num_rows($res_attempts);
                             if ($num_attempts > 0) {
                                 $n = 1;
                                 while ($row_attempts = Database::fetch_array($res_attempts)) {
                                     $my_score = $row_attempts['exe_result'];
                                     $my_maxscore = $row_attempts['exe_weighting'];
                                     $my_exe_id = $row_attempts['exe_id'];
                                     $my_orig_lp = $row_attempts['orig_lp_id'];
                                     $my_orig_lp_item = $row_attempts['orig_lp_item_id'];
                                     $my_exo_exe_id = $row_attempts['exe_exo_id'];
                                     $mktime_start_date = api_strtotime($row_attempts['start_date'], 'UTC');
                                     $mktime_exe_date = api_strtotime($row_attempts['exe_date'], 'UTC');
                                     if ($mktime_start_date && $mktime_exe_date) {
                                         $mytime = (int) $mktime_exe_date - (int) $mktime_start_date;
                                         $time_attemp = learnpathItem::getScormTimeFromParameter('js', $mytime);
                                         $time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
                                     } else {
                                         $time_attemp = ' - ';
                                     }
                                     if (!$is_allowed_to_edit && $result_disabled_ext_all) {
                                         $view_score = Display::return_icon('invisible.gif', get_lang('ResultsHiddenByExerciseSetting'));
                                     } else {
                                         // Show only float when need it
                                         if ($my_score == 0) {
                                             $view_score = ExerciseLib::show_score(0, $my_maxscore, false);
                                         } else {
                                             if ($my_maxscore == 0) {
                                                 $view_score = $my_score;
                                             } else {
                                                 $view_score = ExerciseLib::show_score($my_score, $my_maxscore, false);
                                             }
                                         }
                                     }
                                     $my_lesson_status = $row_attempts['status'];
                                     if ($my_lesson_status == '') {
                                         $my_lesson_status = learnpathitem::humanize_status('completed');
                                     } elseif ($my_lesson_status == 'incomplete') {
                                         $my_lesson_status = learnpathitem::humanize_status('incomplete');
                                     }
                                     $output .= '<tr class="' . $oddclass . '" >
                                     <td></td>
                                     <td>' . $extend_attempt_link . '</td>
                                     <td colspan="3">' . get_lang('Attempt') . ' ' . $n . '</td>
                                     <td colspan="2">' . $my_lesson_status . '</td>
                                     <td colspan="2">' . $view_score . '</td>
                                     <td colspan="2">' . $time_attemp . '</td>';
                                     if ($action == 'classic') {
                                         if ($origin != 'tracking') {
                                             if (!$is_allowed_to_edit && $result_disabled_ext_all) {
                                                 $output .= '<td>
                                                         <img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="' . get_lang('ShowAttempt') . '" title="' . get_lang('ShowAttempt') . '">
                                                         </td>';
                                             } else {
                                                 $output .= '<td>
                                                         <a href="../exercice/exercise_show.php?origin=' . $origin . '&id=' . $my_exe_id . '&cidReq=' . $courseCode . '" target="_parent">
                                                         <img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" alt="' . get_lang('ShowAttempt') . '" title="' . get_lang('ShowAttempt') . '">
                                                         </a></td>';
                                             }
                                         } else {
                                             if (!$is_allowed_to_edit && $result_disabled_ext_all) {
                                                 $output .= '<td>
                                                             <img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="' . get_lang('ShowAndQualifyAttempt') . '" title="' . get_lang('ShowAndQualifyAttempt') . '"></td>';
                                             } else {
                                                 $output .= '<td>
                                                                 <a href="../exercice/exercise_show.php?cidReq=' . $courseCode . '&origin=correct_exercise_in_lp&id=' . $my_exe_id . '" target="_parent">
                                                                 <img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" alt="' . get_lang('ShowAndQualifyAttempt') . '" title="' . get_lang('ShowAndQualifyAttempt') . '"></a></td>';
                                             }
                                         }
                                     }
                                     $output .= '</tr>';
                                     $n++;
                                 }
                             }
                             $output .= '<tr><td colspan="12">&nbsp;</td></tr>';
                         }
                     }
                 }
             }
             $total_time += $time_for_total;
             // QUIZZ IN LP
             $a_my_id = array();
             if (!empty($my_lp_id)) {
                 $a_my_id[] = $my_lp_id;
             }
         }
     }
     // NOT Extend all "left green cross"
     if (!empty($a_my_id)) {
         if ($extendedAttempt) {
             // "Right green cross" extended
             $total_score = self::get_avg_student_score($user_id, $course_id, $a_my_id, $session_id, false, false);
         } else {
             // "Left green cross" extended
             $total_score = self::get_avg_student_score($user_id, $course_id, $a_my_id, $session_id, false, true);
         }
     } else {
         // Extend all "left green cross"
         $total_score = self::get_avg_student_score($user_id, $course_id, array($lp_id), $session_id, false, false);
     }
     $total_time = learnpathItem::getScormTimeFromParameter('js', $total_time);
     $total_time = str_replace('NaN', '00' . $h . '00\'00"', $total_time);
     if (!$is_allowed_to_edit && $result_disabled_ext_all) {
         $final_score = Display::return_icon('invisible.gif', get_lang('ResultsHiddenByExerciseSetting'));
     } else {
         if (is_numeric($total_score)) {
             $final_score = $total_score . '%';
         } else {
             $final_score = $total_score;
         }
     }
     $progress = learnpath::getProgress($lp_id, $user_id, $course_id, $session_id);
     if ($counter % 2 == 0) {
         $oddclass = 'row_odd';
     } else {
         $oddclass = 'row_even';
     }
     $action = null;
     if ($type == 'classic') {
         $action = '<td></td>';
     }
     $output .= '<tr class="' . $oddclass . '">
             <td></td>
             <td colspan="4">
                 <i>' . get_lang('AccomplishedStepsTotal') . '</i>
             </td>
             <td colspan="2">' . $progress . '%</td>
             <td colspan="2">
                 ' . $final_score . '
             </td>
             <td colspan="2">' . $total_time . '</div>
             ' . $action . '
        </tr>';
     $output .= '
                 </tbody>
             </table>
         </div>
     ';
     if (!empty($export_csv)) {
         $temp = array('', '', '', '');
         $csv_content[] = $temp;
         $temp = array(get_lang('AccomplishedStepsTotal'), '', $final_score, $total_time);
         $csv_content[] = $temp;
         ob_end_clean();
         Export::arrayToCsv($csv_content, 'reporting_learning_path_details');
         exit;
     }
     return $output;
 }
Example #20
0
         $table_row[] = $coaches['lastname'];
     } else {
         $table_row[] = $coaches['lastname'];
         $table_row[] = $coaches['firstname'];
     }
     $table_row[] = $time_on_platform;
     $table_row[] = $last_connection;
     $table_row[] = $nb_students;
     $table_row[] = $nb_courses;
     $table_row[] = $nb_sessions;
     $table_row[] = '<a href="session.php?id_coach=' . $coaches['user_id'] . '"><img src="' . api_get_path(WEB_IMG_PATH) . '2rightarrow.gif" border="0" /></a>';
     $all_datas[] = $table_row;
     if ($is_western_name_order) {
         $csv_content[] = array(api_html_entity_decode($coaches['firstname'], ENT_QUOTES, $charset), api_html_entity_decode($coaches['lastname'], ENT_QUOTES, $charset), $time_on_platform, $last_connection, $nb_students, $nb_courses, $nb_sessions);
     } else {
         $csv_content[] = array(api_html_entity_decode($coaches['lastname'], ENT_QUOTES, $charset), api_html_entity_decode($coaches['firstname'], ENT_QUOTES, $charset), $time_on_platform, $last_connection, $nb_students, $nb_courses, $nb_sessions);
     }
 }
 if ($tracking_column != 3) {
     if ($tracking_direction == 'DESC') {
         usort($all_datas, 'rsort_users');
     } else {
         usort($all_datas, 'sort_users');
     }
 }
 if ($export_csv && $tracking_column != 3) {
     usort($csv_content, 'sort_users');
 }
 if ($export_csv) {
     $csv_content = array_merge($csv_header, $csv_content);
 }
 /**
  * Send a system announcement by e-mail to all teachers/students depending on parameters
  * @param	string	Title
  * @param	string	Content
  * @param	int		Whether to send to all teachers (1) or not (0)
  * @param	int		Whether to send to all students (1) or not (0)
  * @param	string	Language (optional, considered for all languages if left empty)
  * @return  bool    True if the message was sent or there was no destination matching. False on database or e-mail sending error.
  */
 public static function send_system_announcement_by_email($title, $content, $teacher, $student, $language = null, $sendEmailTest = false)
 {
     global $charset;
     $title = api_html_entity_decode(stripslashes($title), ENT_QUOTES, $charset);
     $content = api_html_entity_decode(stripslashes(str_replace(array('\\r\\n', '\\n', '\\r'), '', $content)), ENT_QUOTES, $charset);
     if ($sendEmailTest) {
         MessageManager::send_message_simple(api_get_user_id(), $title, $content);
         return true;
     }
     $user_table = Database::get_main_table(TABLE_MAIN_USER);
     if (api_is_multiple_url_enabled()) {
         $current_access_url_id = api_get_current_access_url_id();
         $url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $url_condition = " INNER JOIN {$url_rel_user} uu ON uu.user_id = u.user_id ";
     }
     if ($teacher != 0 and $student == 0) {
         $sql = "SELECT DISTINCT u.user_id FROM {$user_table} u {$url_condition} WHERE status = '1' ";
     }
     if ($teacher == 0 and $student != 0) {
         $sql = "SELECT DISTINCT u.user_id FROM {$user_table} u {$url_condition} WHERE status = '5' ";
     }
     if ($teacher != 0 and $student != 0) {
         $sql = "SELECT DISTINCT u.user_id FROM {$user_table} u {$url_condition} WHERE 1 = 1 ";
     }
     if (!empty($language)) {
         //special condition because language was already treated for SQL insert before
         $sql .= " AND language = '" . Database::escape_string($language) . "' ";
     }
     if (api_is_multiple_url_enabled()) {
         $sql .= " AND access_url_id = '" . $current_access_url_id . "' ";
     }
     // Sent to active users.
     $sql .= " AND email <>'' AND active = 1 ";
     if ((empty($teacher) or $teacher == '0') and (empty($student) or $student == '0')) {
         return true;
     }
     $result = Database::query($sql);
     if ($result === false) {
         return false;
     }
     $message_sent = false;
     while ($row = Database::fetch_array($result, 'ASSOC')) {
         MessageManager::send_message_simple($row['user_id'], $title, $content);
         $message_sent = true;
     }
     return $message_sent;
     //true if at least one e-mail was sent
 }
Example #22
0
        }
    }
    /*
     * Export to a CSV file
     * Force the browser to save the file instead of opening it.
     */
    $len = strlen($title_line . $line);
    header('Content-type: application/octet-stream');
    //header('Content-Type: application/force-download');
    header('Content-length: ' . $len);
    $filename = api_html_entity_decode(str_replace(":", "", str_replace(" ", "_", $title[0] . '_' . $title[1] . '.csv')));
    $filename = api_replace_dangerous_char($filename);
    if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
        header('Content-Disposition: filename= ' . $filename);
    } else {
        header('Content-Disposition: attachment; filename= ' . $filename);
    }
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
        header('Pragma: ');
        header('Cache-Control: ');
        header('Cache-Control: public');
        // IE cannot download from sessions without a cache
    }
    header('Content-Description: ' . $filename);
    header('Content-transfer-encoding: binary');
    echo api_html_entity_decode($title_line, ENT_COMPAT);
    echo api_html_entity_decode($line, ENT_COMPAT);
    exit;
} else {
    api_not_allowed();
}
Example #23
0
/**
 * Clean text like a description
 **/
function formatExerciseQtiDescription($text)
{
    $entities = api_html_entity_decode($text);
    return htmlspecialchars($entities);
}
Example #24
0
$list_course_extra_field = CourseManager::get_course_extra_field_list($course_code);
//@todo this is wrong
foreach ($list_course_extra_field as $extra_field) {
    switch ($extra_field['field_type']) {
        case CourseManager::COURSE_FIELD_TYPE_CHECKBOX:
            $checked = array_key_exists('extra_field_value', $extra_field) && $extra_field['extra_field_value'] == 1 ? array('checked' => 'checked') : '';
            $form->addElement('hidden', '_extra_' . $extra_field['field_variable'], 0);
            $field_display_text = $extra_field['field_display_text'];
            $form->addElement('checkbox', 'extra_' . $extra_field['field_variable'], array(null, get_lang('AllUsersAreAutomaticallyRegistered')), get_lang('SpecialCourse'), $checked);
            break;
    }
}
$form->addElement('style_submit_button', 'button', get_lang('ModifyCourseInfo'), 'onclick="valide()"; class="save"');
// Set some default values
$course['disk_quota'] = round(DocumentManager::get_course_quota($course_code) / 1024 / 1024, 1);
$course['title'] = api_html_entity_decode($course['title'], ENT_QUOTES, $charset);
$course['real_code'] = $course['code'];
$course['add_teachers_to_sessions_courses'] = isset($course['add_teachers_to_sessions_courses']) ? $course['add_teachers_to_sessions_courses'] : 0;
$form->setDefaults($course);
// Validate form
if ($form->validate()) {
    $course = $form->getSubmitValues();
    $visibility = $course['visibility'];
    global $_configuration;
    $urlId = api_get_current_access_url_id();
    if (isset($_configuration[$urlId]) && isset($_configuration[$urlId]['hosting_limit_active_courses']) && $_configuration[$urlId]['hosting_limit_active_courses'] > 0) {
        // Check if
        if ($course_info['visibility'] == COURSE_VISIBILITY_HIDDEN && $visibility != $course_info['visibility']) {
            $num = CourseManager::countActiveCourses($urlId);
            if ($num >= $_configuration[$urlId]['hosting_limit_active_courses']) {
                api_warn_hosting_contact('hosting_limit_active_courses');
 /**
  * Manages chapter splitting
  * @param	string	Chapter header
  * @param	string	Content
  * @return	void
  */
 function dealPerChapter($header, $content)
 {
     $_course = api_get_course_info();
     $content = str_replace('||page_break||', '', $content);
     // Get all the h1.
     preg_match_all("|<h1[^>]*>([^(h1)+]*)</h1>|is", $content, $matches_temp);
     // Empty the fake chapters.
     $new_index = 0;
     for ($i = 0; $i < count($matches_temp[0]); $i++) {
         if (trim($matches_temp[1][$i]) !== '') {
             $matches[0][$new_index] = $matches_temp[0][$i];
             $matches[1][$new_index] = $matches_temp[1][$i];
             $new_index++;
         }
     }
     // Add intro item.
     $intro_content = api_substr($content, 0, api_strpos($content, $matches[0][0]));
     $items_to_create[get_lang('Introduction')] = $intro_content;
     for ($i = 0; $i < count($matches[0]); $i++) {
         if (empty($matches[1][$i])) {
             continue;
         }
         $content = api_strstr($content, $matches[0][$i]);
         if ($i + 1 !== count($matches[0])) {
             $chapter_content = api_substr($content, 0, api_strpos($content, $matches[0][$i + 1]));
         } else {
             $chapter_content = $content;
         }
         $items_to_create[$matches[1][$i]] = $chapter_content;
     }
     $i = 0;
     foreach ($items_to_create as $item_title => $item_content) {
         $i++;
         $page_content = $this->format_page_content($header, $item_content);
         $html_file = $this->created_dir . '-' . $i . '.html';
         $handle = fopen($this->base_work_dir . $this->created_dir . '/' . $html_file, 'w+');
         fwrite($handle, $page_content);
         fclose($handle);
         $document_id = add_document($_course, $this->created_dir . '/' . $html_file, 'file', filesize($this->base_work_dir . $this->created_dir . '/' . $html_file), $html_file);
         if ($document_id) {
             // Put the document in item_property update.
             api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_SESSION['_uid'], 0, 0, null, null, api_get_session_id());
             $infos = pathinfo($this->filepath);
             $slide_name = strip_tags(nl2br($item_title));
             $slide_name = str_replace(array("\r\n", "\r", "\n"), '', $slide_name);
             $slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding());
             $previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
             if ($this->first_item == 0) {
                 $this->first_item = $previous;
             }
         }
     }
 }
Example #26
0
 /**
  * This function saves all the invitations of course users and additional users in the database
  * and sends the invitations by email
  *
  * @param	array	Users array can be both a list of course uids AND a list of additional emailaddresses
  * @param 	string	Title of the invitation, used as the title of the mail
  * @param 	string	Text of the invitation, used as the text of the mail.
  * 				 The text has to contain a **link** string or this will automatically be added to the end
  *
  * @author Patrick Cool <*****@*****.**>, Ghent University
  * @author Julio Montoya - Adding auto-generated link support
  * @version January 2007
  *
  */
 public static function saveInvitations($users_array, $invitation_title, $invitation_text, $reminder = 0, $sendmail = 0, $remindUnAnswered = 0)
 {
     if (!is_array($users_array)) {
         // Should not happen
         return 0;
     }
     // Getting the survey information
     $survey_data = SurveyManager::get_survey($_GET['survey_id']);
     $survey_invitations = SurveyUtil::get_invitations($survey_data['survey_code']);
     $already_invited = SurveyUtil::get_invited_users($survey_data['code']);
     // Remind unanswered is a special version of remind all reminder
     $exclude_users = array();
     if ($remindUnAnswered == 1) {
         // Remind only unanswered users
         $reminder = 1;
         $exclude_users = SurveyManager::get_people_who_filled_survey($_GET['survey_id']);
     }
     $counter = 0;
     // Nr of invitations "sent" (if sendmail option)
     $course_id = api_get_course_int_id();
     $session_id = api_get_session_id();
     $result = CourseManager::separateUsersGroups($users_array);
     $groupList = $result['groups'];
     $users_array = $result['users'];
     foreach ($groupList as $groupId) {
         $userGroupList = GroupManager::getStudents($groupId);
         $userGroupIdList = array_column($userGroupList, 'user_id');
         $users_array = array_merge($users_array, $userGroupIdList);
         $params = array('c_id' => $course_id, 'session_id' => $session_id, 'group_id' => $groupId, 'survey_code' => $survey_data['code']);
         $invitationExists = self::invitationExists($course_id, $session_id, $groupId, $survey_data['code']);
         if (empty($invitationExists)) {
             self::save_invitation($params);
         }
     }
     $users_array = array_unique($users_array);
     foreach ($users_array as $key => $value) {
         if (!isset($value) || $value == '') {
             continue;
         }
         // Skip user if reminding only unanswered people
         if (in_array($value, $exclude_users)) {
             continue;
         }
         // Get the unique invitation code if we already have it
         if ($reminder == 1 && array_key_exists($value, $survey_invitations)) {
             $invitation_code = $survey_invitations[$value]['invitation_code'];
         } else {
             $invitation_code = md5($value . microtime());
         }
         $new_user = false;
         // User not already invited
         // Store the invitation if user_id not in $already_invited['course_users'] OR email is not in $already_invited['additional_users']
         $addit_users_array = isset($already_invited['additional_users']) && !empty($already_invited['additional_users']) ? explode(';', $already_invited['additional_users']) : array();
         $my_alredy_invited = $already_invited['course_users'] == null ? array() : $already_invited['course_users'];
         if (is_numeric($value) && !in_array($value, $my_alredy_invited) || !is_numeric($value) && !in_array($value, $addit_users_array)) {
             $new_user = true;
             if (!array_key_exists($value, $survey_invitations)) {
                 $params = array('c_id' => $course_id, 'session_id' => $session_id, 'user' => $value, 'survey_code' => $survey_data['code'], 'invitation_code' => $invitation_code, 'invitation_date' => api_get_utc_datetime());
                 self::save_invitation($params);
             }
         }
         // Send the email if checkboxed
         if (($new_user || $reminder == 1) && $sendmail != 0) {
             // Make a change for absolute url
             if (isset($invitation_text)) {
                 $invitation_text = api_html_entity_decode($invitation_text, ENT_QUOTES);
                 $invitation_text = str_replace('src="../../', 'src="' . api_get_path(WEB_PATH), $invitation_text);
                 $invitation_text = trim(stripslashes($invitation_text));
             }
             SurveyUtil::send_invitation_mail($value, $invitation_code, $invitation_title, $invitation_text);
             $counter++;
         }
     }
     return $counter;
     // Number of invitations sent
 }
Example #27
0
 /**
  * Displays a basic form on the overview page for changing the item title and the item description.
  *
  * @param string $item_type
  * @param string $title
  * @param array $data
  * @return string
  */
 function display_item_small_form($item_type, $title = '', $data)
 {
     global $charset;
     $return .= '<div class="lp_small_form">' . "\n";
     $return .= '<p class="lp_title">' . $title . '</p>';
     $return .= '<form method="post">' . "\n";
     $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
     $return .= "\t\t" . '<tr>' . "\n";
     $return .= "\t\t\t" . '<td class="label"><label for="idTitle">Title&nbsp;:</label></td>' . "\n";
     $return .= "\t\t\t" . '<td class="input"><input class="small_form" id="idTitle" name="title" type="text" value="' . api_html_entity_decode(api_convert_encoding(htmlspecialchars($data['title']), $charset, $this->encoding), ENT_QUOTES, $charset) . '" /></td>' . "\n";
     $return .= "\t\t" . '</tr>' . "\n";
     //it said these lines of code - see SVN#11724 and SVN#10770
     //$return .= "\t\t" . '<tr>' . "\n";
     //$return .= "\t\t\t" . '<td class="label"><label for="idDescription">Description&nbsp;:</label></td>' . "\n";
     //$return .= "\t\t\t" . '<td class="input"><textarea class="small_form" id="idDescription" name="description" rows="4">' . $data['description'] . '</textarea></td>' . "\n";
     //$return .= "\t\t" . '</tr>' . "\n";
     $return .= "\t\t" . '<tr>' . "\n";
     $return .= "\t\t\t" . '<td colspan="2"><button class="save" name="submit_button" type="submit">' . get_lang('Save') . '</button></td>' . "\n";
     $return .= "\t\t" . '</tr>' . "\n";
     $return .= "\t\t" . '</table>' . "\n";
     $return .= "\t" . '<input name="parent" type="hidden" value="' . $data['parent_item_id'] . '"/>' . "\n";
     $return .= "\t" . '<input name="previous" type="hidden" value="' . $data['previous_item_id'] . '"/>' . "\n";
     $return .= '</form>';
     $return .= '</div>';
     return $return;
 }
Example #28
0
        case 'unassign':
            if ($isAdmin && isset($_GET['ticket_id'])) {
                TicketManager::assign_ticket_user($_GET['ticket_id'], 0);
            }
            break;
        case 'alert':
            if (!$isAdmin && isset($_GET['ticket_id'])) {
                TicketManager::send_alert($_GET['ticket_id'], $user_id);
            }
            break;
        case 'export':
            $data = array(array($plugin->get_lang('TicketNum'), $plugin->get_lang('Date'), $plugin->get_lang('DateLastEdition'), $plugin->get_lang('Category'), $plugin->get_lang('User'), $plugin->get_lang('Program'), $plugin->get_lang('Responsible'), $plugin->get_lang('Status'), $plugin->get_lang('Message'), $plugin->get_lang('Description')));
            $datos = $table->get_clean_html();
            foreach ($datos as $ticket) {
                $ticket[0] = substr(strip_tags($ticket[0]), 0, 12);
                $ticket_rem = array(utf8_decode(strip_tags($ticket[0])), utf8_decode(api_html_entity_decode($ticket[1])), utf8_decode(strip_tags($ticket[2])), utf8_decode(strip_tags($ticket[3])), utf8_decode(strip_tags($ticket[4])), utf8_decode(strip_tags($ticket[5])), utf8_decode(strip_tags($ticket[6])), utf8_decode(strip_tags($ticket[7])), utf8_decode(strip_tags($ticket[8])), utf8_decode(strip_tags($ticket[10])));
                $data[] = $ticket_rem;
            }
            Export::export_table_xls($data, $plugin->get_lang('Tickets'));
            exit;
            break;
        case 'close_tickets':
            TicketManager::close_old_tickets();
            break;
        default:
            break;
    }
}
//$nameTools = api_xml_http_response_encode($plugin->get_lang('MyTickets'));
$user_id = api_get_user_id();
$isAdmin = api_is_platform_admin();
 function add_docs_to_visio($files = array())
 {
     global $_course;
     foreach ($files as $file) {
         list($slide_name,$file_name) = explode('||',$file); // '||' is used as separator between slide name (with accents) and file name (without accents).
         $slide_name = api_htmlentities($slide_name, ENT_COMPAT, $this->original_charset);
         $slide_name = str_replace('&rsquo;', '\'', $slide_name);
         $slide_name = api_convert_encoding($slide_name, api_get_system_encoding(), $this->original_charset);
         $slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding());
         $did = add_document($_course, $this->created_dir.'/'.urlencode($file_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$file_name), $slide_name);
         if ($did) {
             api_item_property_update($_course, TOOL_DOCUMENT, $did, 'DocumentAdded', $_SESSION['_uid'], 0, null, null, null, api_get_session_id());
         }
     }
 }
} else {
    $form = new FormValidator('introduction_text');
}
$renderer =& $form->defaultRenderer();
$renderer->setCustomElementTemplate('<div style="width: 80%; margin: 0px auto; padding-bottom: 10px; ">{element}</div>');
$config = array('ToolbarSet' => 'IntroductionTool', 'Width' => '100%', 'Height' => '300');
$form->addHtmlEditor('intro_content', null, null, false, $config);
$form->addButtonSave(get_lang('SaveIntroText'), 'intro_cmdUpdate');
/* INTRODUCTION MICRO MODULE - COMMANDS SECTION (IF ALLOWED) */
$course_id = api_get_course_int_id();
if ($intro_editAllowed) {
    /* Replace command */
    if ($intro_cmdUpdate) {
        if ($form->validate()) {
            $form_values = $form->exportValues();
            $intro_content = Security::remove_XSS(stripslashes(api_html_entity_decode($form_values['intro_content'])), COURSEMANAGERLOWSECURITY);
            $criteria = ['cId' => $course_id, 'id' => $moduleId, 'sessionId' => $session_id];
            if (!empty($intro_content)) {
                /** @var CToolIntro $toolIntro */
                $toolIntro = Database::getManager()->getRepository('ChamiloCourseBundle:CToolIntro')->findOneBy($criteria);
                if ($toolIntro) {
                    $toolIntro->setIntroText($intro_content);
                } else {
                    $toolIntro = new CToolIntro();
                    $toolIntro->setSessionId($session_id)->setCId($course_id)->setIntroText($intro_content)->setId($moduleId);
                }
                Database::getManager()->persist($toolIntro);
                Database::getManager()->flush();
                $introduction_section .= Display::return_message(get_lang('IntroductionTextUpdated'), 'confirmation', false);
            } else {
                // got to the delete command