/**
  * 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;
 }
/**
 * XML-parser: handle character data
 * @param   string  $parser Parser (deprecated?)
 * @param   string  $data The data to be parsed
 * @return  void
 */
function character_data($parser, $data)
{
    $data = trim(api_utf8_decode($data));
    global $current_value;
    $current_value = $data;
}
/**
 * This callback function converts from UTF-8 to other encoding. It works with strings or arrays of strings.
 * @param mixed $variable	The variable to be converted, a string or an array.
 * @return mixed			Returns the converted form UTF-8 $variable with the same type, string or array.
 */
function _api_array_utf8_decode($variable)
{
    global $_api_encoding;
    if (is_array($variable)) {
        return array_map('_api_array_utf8_decode', $variable);
    }
    if (is_string($variable)) {
        return api_utf8_decode($variable, $_api_encoding);
    }
    return $variable;
}
 /**
  * @author Isaac flores <*****@*****.**>
  * @param string The email administrator
  * @param integer The user id
  * @param string The message title
  * @param string The content message
  */
 public static function send_message_in_outbox($email_administrator, $user_id, $title, $content)
 {
     $table_message = Database::get_main_table(TABLE_MESSAGE);
     $table_user = Database::get_main_table(TABLE_MAIN_USER);
     $title = api_utf8_decode($title);
     $content = api_utf8_decode($content);
     $email_administrator = Database::escape_string($email_administrator);
     //message in inbox
     $sql_message_outbox = 'SELECT id from ' . $table_user . ' WHERE email="' . $email_administrator . '" ';
     //$num_row_query = Database::num_rows($sql_message_outbox);
     $res_message_outbox = Database::query($sql_message_outbox);
     $array_users_administrator = array();
     while ($row_message_outbox = Database::fetch_array($res_message_outbox, 'ASSOC')) {
         $array_users_administrator[] = $row_message_outbox['id'];
     }
     //allow to insert messages in outbox
     for ($i = 0; $i < count($array_users_administrator); $i++) {
         $sql_insert_outbox = "INSERT INTO {$table_message}(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) " . " VALUES (" . "'" . (int) $user_id . "', '" . (int) $array_users_administrator[$i] . "', '4', '" . api_get_utc_datetime() . "','" . Database::escape_string($title) . "','" . Database::escape_string($content) . "'" . ")";
         Database::query($sql_insert_outbox);
     }
 }
 // adding coachs to session course user
 foreach ($course_coaches as $course_coach) {
     $coach_id = UserManager::purify_username(api_utf8_decode($course_coach), $purification_option_for_usernames);
     $coach_id = UserManager::get_user_id_from_username($course_coach);
     if ($coach_id !== false) {
         $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n                                                        id_user='******',\n                                                        course_code='{$vcourse['code']}',\n                                                        id_session = '{$session_id}',\n                                                        status = 2 ";
         $rs_coachs = Database::query($sql);
     } else {
         $error_message .= get_lang('UserDoesNotExist') . ' : ' . $user . '<br />';
     }
 }
 // adding users
 $course_counter++;
 $users_in_course_counter = 0;
 foreach ($node_course->User as $node_user) {
     $username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
     $user_id = UserManager::get_user_id_from_username($username);
     if ($user_id !== false) {
         // Adding to session_rel_user table.
         $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n                                                        id_user='******',\n                                                        id_session = '{$session_id}'";
         $rs_user = Database::query($sql);
         $user_counter++;
         // Adding to session_rel_user_rel_course table.
         $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n                                                        id_user='******',\n                                                        course_code='{$vcourse['code']}',\n                                                        id_session = '{$session_id}'";
         $rs_users = Database::query($sql);
         $users_in_course_counter++;
     } else {
         $error_message .= get_lang('UserDoesNotExist') . ' : ' . $username . '<br />';
     }
 }
 $update_session_course = "UPDATE {$tbl_session_course} SET nbr_users='{$users_in_course_counter}' WHERE course_code='{$course_code}'";
示例#6
0
 /**
  * Import the scorm object (as a result from the parse_manifest function) into the database structure
  * @param    string    Unique course code
  * @return    bool    Returns -1 on error
  */
 function import_manifest($course_code, $use_max_score = 1)
 {
     if ($this->debug > 0) {
         error_log('New LP - Entered import_manifest(' . $course_code . ')', 0);
     }
     $course_info = api_get_course_info($course_code);
     $course_id = $course_info['real_id'];
     // Get table names.
     $new_lp = Database::get_course_table(TABLE_LP_MAIN);
     $new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
     $use_max_score = intval($use_max_score);
     foreach ($this->organizations as $id => $dummy) {
         $is_session = api_get_session_id();
         $is_session != 0 ? $session_id = $is_session : ($session_id = 0);
         $oOrganization =& $this->organizations[$id];
         // Prepare and execute insert queries:
         // -for learnpath
         // -for items
         // -for views?
         $get_max = "SELECT MAX(display_order) FROM {$new_lp} WHERE c_id = {$course_id} ";
         $res_max = Database::query($get_max);
         $dsp = 1;
         if (Database::num_rows($res_max) > 0) {
             $row = Database::fetch_array($res_max);
             $dsp = $row[0] + 1;
         }
         $myname = $oOrganization->get_name();
         $myname = api_utf8_decode($myname);
         $sql = "INSERT INTO {$new_lp} (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order, session_id, use_max_score)" . "VALUES ({$course_id} , 2,'" . $myname . "', '" . $oOrganization->get_ref() . "','','" . $this->subdir . "', 0, 'embedded', '" . $this->manifest_encoding . "', 'scorm_api.php', {$dsp}, {$session_id}, {$use_max_score})";
         if ($this->debug > 1) {
             error_log('New LP - In import_manifest(), inserting path: ' . $sql, 0);
         }
         $res = Database::query($sql);
         $lp_id = Database::insert_id();
         $this->lp_id = $lp_id;
         // Insert into item_property.
         api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'LearnpathAdded', api_get_user_id());
         api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'visible', api_get_user_id());
         // Now insert all elements from inside that learning path.
         // Make sure we also get the href and sco/asset from the resources.
         $list = $oOrganization->get_flat_items_list();
         $parents_stack = array(0);
         $parent = 0;
         $previous = 0;
         $level = 0;
         foreach ($list as $item) {
             if ($item['level'] > $level) {
                 // Push something into the parents array.
                 array_push($parents_stack, $previous);
                 $parent = $previous;
             } elseif ($item['level'] < $level) {
                 $diff = $level - $item['level'];
                 // Pop something out of the parents array.
                 for ($j = 1; $j <= $diff; $j++) {
                     $outdated_parent = array_pop($parents_stack);
                 }
                 $parent = array_pop($parents_stack);
                 // Just save that value, then add it back.
                 array_push($parents_stack, $parent);
             }
             $path = '';
             $type = 'dir';
             if (isset($this->resources[$item['identifierref']])) {
                 $oRes =& $this->resources[$item['identifierref']];
                 $path = @$oRes->get_path();
                 if (!empty($path)) {
                     $temptype = $oRes->get_scorm_type();
                     if (!empty($temptype)) {
                         $type = $temptype;
                     }
                 }
             }
             $level = $item['level'];
             $field_add = '';
             $value_add = '';
             if (!empty($item['masteryscore'])) {
                 $field_add .= 'mastery_score, ';
                 $value_add .= $item['masteryscore'] . ',';
             }
             if (!empty($item['maxtimeallowed'])) {
                 $field_add .= 'max_time_allowed, ';
                 $value_add .= "'" . $item['maxtimeallowed'] . "',";
             }
             $title = Database::escape_string($item['title']);
             $title = api_utf8_decode($title);
             $max_score = Database::escape_string($item['max_score']);
             if ($max_score == 0 || is_null($max_score) || $max_score == '') {
                 //If max score is not set The use_max_score parameter is check in order to use 100 (chamilo style) or '' (strict scorm)
                 if ($use_max_score) {
                     $max_score = "'100'";
                 } else {
                     $max_score = "NULL";
                 }
             } else {
                 //Otherwise save the max score
                 $max_score = "'{$max_score}'";
             }
             $identifier = Database::escape_string($item['identifier']);
             if (empty($title)) {
                 $title = get_lang('Untitled');
             }
             $prereq = Database::escape_string($item['prerequisites']);
             $sql_item = "INSERT INTO {$new_lp_item} (c_id, lp_id,item_type,ref,title, path,min_score,max_score, {$field_add} parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters) VALUES " . "({$course_id}, {$lp_id}, '{$type}','{$identifier}', '{$title}', '{$path}' , 0, {$max_score}, {$value_add}" . "{$parent}, {$previous}, 0, " . "'{$prereq}', " . $item['rel_order'] . ", '" . $item['datafromlms'] . "'," . "'" . $item['parameters'] . "'" . ")";
             $res_item = Database::query($sql_item);
             if ($this->debug > 1) {
                 error_log('New LP - In import_manifest(), inserting item : ' . $sql_item . ' : ' . Database::error(), 0);
             }
             $item_id = Database::insert_id();
             // Now update previous item to change next_item_id.
             $upd = "UPDATE {$new_lp_item} SET next_item_id = {$item_id} WHERE c_id = {$course_id} AND id = {$previous}";
             $upd_res = Database::query($upd);
             // Update previous item id.
             $previous = $item_id;
             // Code for indexing, now only index specific fields like terms and the title.
             if (!empty($_POST['index_document'])) {
                 require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
                 require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
                 require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
                 $di = new ChamiloIndexer();
                 isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english');
                 $di->connectDb(null, null, $lang);
                 $ic_slide = new IndexableChunk();
                 $ic_slide->addValue('title', $title);
                 $specific_fields = get_specific_field_list();
                 $all_specific_terms = '';
                 foreach ($specific_fields as $specific_field) {
                     if (isset($_REQUEST[$specific_field['code']])) {
                         $sterms = trim($_REQUEST[$specific_field['code']]);
                         $all_specific_terms .= ' ' . $sterms;
                         if (!empty($sterms)) {
                             $sterms = explode(',', $sterms);
                             foreach ($sterms as $sterm) {
                                 $ic_slide->addTerm(trim($sterm), $specific_field['code']);
                             }
                         }
                     }
                 }
                 $body_to_index = $all_specific_terms . ' ' . $title;
                 $ic_slide->addValue("content", $body_to_index);
                 // TODO: Add a comment to say terms separated by commas.
                 $courseid = api_get_course_id();
                 $ic_slide->addCourseId($courseid);
                 $ic_slide->addToolId(TOOL_LEARNPATH);
                 $xapian_data = array(SE_COURSE_ID => $courseid, SE_TOOL_ID => TOOL_LEARNPATH, SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => ''), SE_USER => (int) api_get_user_id());
                 $ic_slide->xapian_data = serialize($xapian_data);
                 $di->addChunk($ic_slide);
                 // Index and return search engine document id.
                 $did = $di->index();
                 if ($did) {
                     // Save it to db.
                     $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
                     $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
                             VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
                     $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
                     Database::query($sql);
                 }
             }
         }
     }
 }
/**
 * Note: Try to avoid using this function. Use api_preg_replace() with Perl-compatible regular expression syntax.
 *
 * Scans string for matches to pattern, then replaces the matched text with replacement, ignoring case, with extended multibyte support.
 * By default this function uses the platform character set.
 * @param string $pattern                The regular expression pattern.
 * @param string $replacement            The replacement text.
 * @param string $string                The searched string.
 * @param string $option (optional)        Matching condition.
 * If i is specified for the matching condition parameter, the case will be ignored.
 * If x is specified, white space will be ignored.
 * If m is specified, match will be executed in multiline mode and line break will be included in '.'.
 * If p is specified, match will be executed in POSIX mode, line break will be considered as normal character.
 * If e is specified, replacement string will be evaluated as PHP expression.
 * @return mixed                        The modified string is returned. If no matches are found within the string, then it will be returned unchanged. FALSE will be returned on error.
 * This function is aimed at replacing the functions eregi_replace() and mb_eregi_replace() for human-language strings.
 * @link http://php.net/manual/en/function.eregi-replace
 * @link http://php.net/manual/en/function.mb-eregi-replace
 */
function api_eregi_replace($pattern, $replacement, $string, $option = null)
{
    $encoding = _api_mb_regex_encoding();
    if (_api_mb_supports($encoding)) {
        if (is_null($option)) {
            return @mb_eregi_replace($pattern, $replacement, $string);
        }
        return @mb_eregi_replace($pattern, $replacement, $string, $option);
    }
    if (MBSTRING_INSTALLED && api_is_encoding_supported($encoding)) {
        _api_mb_regex_encoding('UTF-8');
        if (is_null($option)) {
            $result = api_utf8_decode(@mb_eregi_replace(api_utf8_encode($pattern, $encoding), api_utf8_encode($replacement, $encoding), api_utf8_encode($string, $encoding)), $encoding);
        } else {
            $result = api_utf8_decode(@mb_eregi_replace(api_utf8_encode($pattern, $encoding), api_utf8_encode($replacement, $encoding), api_utf8_encode($string, $encoding), $option), $encoding);
        }
        _api_mb_regex_encoding($encoding);
        return $result;
    }
    return eregi_replace($pattern, $replacement, $string);
}
/**
 * Converts HTML entities into normal characters.
 * @param string $string				The input string.
 * @param int $quote_style (optional)	The quote style - ENT_COMPAT (default), ENT_QUOTES, ENT_NOQUOTES.
 * @param string $encoding (optional)	The encoding (of the result) used in conversion.
 * If it is omitted, the platform character set is assumed.
 * @return string						Returns the converted string.
 * This function is aimed at replacing the function html_entity_decode() for human-language strings.
 * @link http://php.net/html_entity_decode
 */
function api_html_entity_decode($string, $quote_style = ENT_COMPAT, $encoding = 'UTF-8')
{
    if (empty($encoding)) {
        $encoding = _api_mb_internal_encoding();
    }
    if (api_is_encoding_supported($encoding)) {
        if (!api_is_utf8($encoding)) {
            $string = api_utf8_encode($string, $encoding);
        }
        $string = html_entity_decode($string, $quote_style, 'UTF-8');
        if (!api_is_utf8($encoding)) {
            return api_utf8_decode($string, $encoding);
        }
        return $string;
    }
    return $string;
    // Here the function gives up.
}
示例#9
0
 $annee = $row['annee'];
 $code_ufr = $row['code_ufr'];
 $etape = $row['code_etape'];
 */
 // LDAP Query
 // edupersonorgunitdn=ou=12CI1,ou=2006,ou=diploma,o=Paris1,dc=univ-paris1,dc=fr
 //etapescommented
 //$sr = @ ldap_search($ds, "ou=people,$LDAPbasedn", "edupersonorgunitdn=ou=$etape,ou=$annee,ou=diploma,$LDAPbasedn");
 $sr = @ldap_search($ds, $ldap_basedn, '(uid=*)');
 $info = ldap_get_entries($ds, $sr);
 for ($key = 0; $key < $info["count"]; $key++) {
     echo "<pre>";
     print_r($info[$key]);
     echo "</pre>";
     $lastname = api_utf8_decode($info[$key]["sn"][0]);
     $firstname = api_utf8_decode($info[$key]["givenname"][0]);
     $email = $info[$key]["mail"][0];
     // Get uid from dn
     $dn_array = ldap_explode_dn($info[$key]["dn"], 1);
     $username = $dn_array[0];
     // uid is first key
     $outab[] = $info[$key]["edupersonprimaryaffiliation"][0];
     // Ici "student"
     $val = ldap_get_values_len($ds, $sr, "userPassword");
     $password = $val[0];
     // Pour faciliter la gestion on ajoute le code "etape-annee"
     $official_code = $etape . "-" . $annee;
     $auth_source = "ldap";
     // Pas de date d'expiration d'etudiant (a recuperer par rapport au shadow expire LDAP)
     $expiration_date = '0000-00-00 00:00:00';
     $active = 1;
示例#10
0
Display::display_header($nameTools);
$lp_id = intval($_GET['lp_id']);
$sql = 'SELECT name	FROM ' . Database::get_course_table(TABLE_LP_MAIN) . ' WHERE c_id = ' . $course_info['real_id'] . ' AND id=' . $lp_id;
$rs = Database::query($sql);
$lp_title = Database::result($rs, 0, 0);
echo '<div class ="actions">';
echo '<a href="javascript:history.back();">' . Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM) . '</a>';
echo '<a href="javascript: void(0);" onclick="javascript: window.print();">
' . Display::return_icon('printer.png', get_lang('Print'), '', ICON_SIZE_MEDIUM) . '</a>';
echo '<a href="' . api_get_self() . '?export=csv&' . Security::remove_XSS($_SERVER['QUERY_STRING']) . '">
' . Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), '', ICON_SIZE_MEDIUM) . '</a>';
echo '</div>';
echo '<div class="clear"></div>';
$session_name = api_get_session_name($session_id);
$table_title = ($session_name ? Display::return_icon('session.png', get_lang('Session'), array(), ICON_SIZE_SMALL) . ' ' . $session_name . ' ' : ' ') . Display::return_icon('course.png', get_lang('Course'), array(), ICON_SIZE_SMALL) . ' ' . $course_info['name'] . ' ' . Display::return_icon('user.png', get_lang('User'), array(), ICON_SIZE_SMALL) . ' ' . $name;
echo Display::page_header($table_title);
echo Display::page_subheader('<h3>' . Display::return_icon('learnpath.png', get_lang('ToolLearnpath'), array(), ICON_SIZE_SMALL) . ' ' . $lp_title . '</h3>');
//Needed in newscorm/lp_stats.php
$list = learnpath::get_flat_ordered_items_list($lp_id, 0, $course_info['real_id']);
$origin = 'tracking';
if ($export_csv) {
    require_once api_get_path(SYS_CODE_PATH) . 'newscorm/lp_stats.php';
    //Export :: export_table_csv($csv_content, 'reporting_student');
} else {
    ob_start();
    require_once api_get_path(SYS_CODE_PATH) . 'newscorm/lp_stats.php';
    $tracking_content = ob_get_contents();
    ob_end_clean();
    echo api_utf8_decode($tracking_content, $charset);
}
Display::display_footer();
示例#11
0
 $annee = $row['annee'];
 $code_ufr = $row['code_ufr'];
 $etape = $row['code_etape'];
 */
 // LDAP Query
 // edupersonorgunitdn=ou=12CI1,ou=2006,ou=diploma,o=Paris1,dc=univ-paris1,dc=fr
 //etapescommented
 //$sr = @ ldap_search($ds, "ou=people,$LDAPbasedn", "edupersonorgunitdn=ou=$etape,ou=$annee,ou=diploma,$LDAPbasedn");
 $sr = @ldap_search($ds, $ldap_basedn, '(uid=*)');
 $info = ldap_get_entries($ds, $sr);
 for ($key = 0; $key < $info["count"]; $key++) {
     echo "<pre>";
     print_r($info[$key]);
     echo "</pre>";
     $lastname = api_utf8_decode($info[$key]["sn"][0], api_get_system_encoding());
     $firstname = api_utf8_decode($info[$key]["givenname"][0], api_get_system_encoding());
     $email = $info[$key]["mail"][0];
     // Get uid from dn
     $dn_array = ldap_explode_dn($info[$key]["dn"], 1);
     $username = $dn_array[0];
     // uid is first key
     $outab[] = $info[$key]["edupersonprimaryaffiliation"][0];
     // Ici "student"
     $val = ldap_get_values_len($ds, $sr, "userPassword");
     $password = $val[0];
     // Pour faciliter la gestion on ajoute le code "etape-annee"
     $official_code = $etape . "-" . $annee;
     $auth_source = "ldap";
     // Pas de date d'expiration d'etudiant (a recuperer par rapport au shadow expire LDAP)
     $expiration_date = '0000-00-00 00:00:00';
     $active = 1;
示例#12
0
 /**
  * Converts a string from UTF-8 based on configuration.
  * @note Currently, this is a lossy conversion, with unexpressable
  *       characters being omitted.
  */
 public static function convertFromUTF8($str, $config, $context)
 {
     $encoding = $config->get('Core.Encoding');
     if ($encoding === 'utf-8') {
         return $str;
     }
     static $iconv = null;
     if ($iconv === null) {
         $iconv = function_exists('iconv');
     }
     if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {
         $str = HTMLPurifier_Encoder::convertToASCIIDumbLossless($str);
     }
     set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
     if ($iconv && !$config->get('Test.ForceNoIconv')) {
         // Undo our previous fix in convertToUTF8, otherwise iconv will barf
         $ascii_fix = HTMLPurifier_Encoder::testEncodingSupportsASCII($encoding);
         if (!$escape && !empty($ascii_fix)) {
             $clear_fix = array();
             foreach ($ascii_fix as $utf8 => $native) {
                 $clear_fix[$utf8] = '';
             }
             $str = strtr($str, $clear_fix);
         }
         $str = strtr($str, array_flip($ascii_fix));
         // Normal stuff
         $str = iconv('utf-8', $encoding . '//IGNORE', $str);
         restore_error_handler();
         return $str;
     } elseif ($encoding === 'iso-8859-1') {
         $str = utf8_decode($str);
         restore_error_handler();
         return $str;
     } elseif (function_exists('api_is_encoding_supported')) {
         if (api_is_encoding_supported($encoding)) {
             $str = api_utf8_decode($str, $encoding);
             restore_error_handler();
             return $str;
         }
     }
     //
     trigger_error('Encoding not supported', E_USER_ERROR);
 }
/**
 * Detects encoding of plain text.
 * @param string $string				The input text.
 * @param string $language (optional)	The language of the input text, provided if it is known.
 * @return string						Returns the detected encoding.
 */
function api_detect_encoding($string, $language = null)
{
    // Testing against valid UTF-8 first.
    if (api_is_valid_utf8($string)) {
        return 'UTF-8';
    }
    $result = null;
    $delta_points_min = LANGUAGE_DETECT_MAX_DELTA;
    // Testing non-UTF-8 encodings.
    $encodings = api_get_valid_encodings();
    foreach ($encodings as &$encoding) {
        if (api_is_encoding_supported($encoding) && !api_is_utf8($encoding)) {
            $stringToParse = api_substr($string, 0, LANGUAGE_DETECT_MAX_LENGTH, $encoding);
            $strintToParse2 = _api_generate_n_grams($stringToParse, $encoding);
            $result_array = _api_compare_n_grams($strintToParse2, $encoding);
            if (!empty($result_array)) {
                list($key, $delta_points) = each($result_array);
                if ($delta_points < $delta_points_min) {
                    $pos = strpos($key, ':');
                    $result_encoding = api_refine_encoding_id(substr($key, $pos + 1));
                    if (api_equal_encodings($encoding, $result_encoding)) {
                        if ($string == api_utf8_decode(api_utf8_encode($string, $encoding), $encoding)) {
                            $delta_points_min = $delta_points;
                            $result = $encoding;
                        }
                    }
                }
            }
        }
    }
    // "Broken" UTF-8 texts are to be detected as UTF-8.
    // This functionality is enabled when language of the text is known.
    $language = api_purify_language_id((string) $language);
    if (!empty($language)) {
        $encoding = 'UTF-8';
        $result_array =& _api_compare_n_grams(_api_generate_n_grams(api_substr($string, 0, LANGUAGE_DETECT_MAX_LENGTH, $encoding), $encoding), $encoding);
        if (!empty($result_array)) {
            list($key, $delta_points) = each($result_array);
            if ($delta_points < $delta_points_min) {
                $pos = strpos($key, ':');
                $result_encoding = api_refine_encoding_id(substr($key, $pos + 1));
                $result_language = substr($key, 0, $pos);
                if ($language == $result_language && api_is_utf8($result_encoding)) {
                    $delta_points_min = $delta_points;
                    $result = $encoding;
                }
            }
        }
    }
    return $result;
}