Exemple #1
0
	public function test_detect_encoding()
	{
	    $this->assertTrue(test_detect_encoding());
	    
            $utf8_str = file_get_contents(dirname(__FILE__) . "/../tools/utf8_str.txt");
            $this->assertEquals("UTF-8", detect_encoding($utf8_str));
            $iso_str = file_get_contents(dirname(__FILE__) . "/../tools/iso-8859-1_str.txt");
            $this->assertEquals("ISO-8859-15", detect_encoding($iso_str));
	    
	}
function test_detect_encoding()
{
    if ("UTF-8" != detect_encoding("auie")) {echo 'échec ligne 45 mod_serveur/test_encoding_functions.php'; return false;} 
    if ("UTF-8" != detect_encoding("bépowǜdlj")) {echo 'échec ligne 46 mod_serveur/test_encoding_functions.php'; return false;} 
    if ("UTF-8" != detect_encoding(";œ€âũ")) {echo 'échec ligne 47 mod_serveur/test_encoding_functions.php'; return false;} 
    if ("UTF-8" != detect_encoding("é")) {echo 'échec ligne 48 mod_serveur/test_encoding_functions.php'; return false;}
    if ("ISO-8859-15" != detect_encoding("\xe9")) {echo 'échec ligne 48 mod_serveur/test_encoding_functions.php'; return false;}
    if ("ISO-8859-15" != detect_encoding("\xa4")) {echo 'échec ligne 48 mod_serveur/test_encoding_functions.php'; return false;}
	return true;
}
function convert_encoding($string, $to_encoding, $from_encoding = '')
{
    if ($from_encoding == '') {
        $from_encoding = detect_encoding($string);
    }
    if ($from_encoding == $to_encoding) {
        return $string;
    }
    return mb_convert_encoding($string, $to_encoding, $from_encoding);
}
Exemple #4
0
 function __construct($area, $news_id, $author, $t_size, $t_seite, $make_thumb = true, $make_watermark = true, $flash_mode = false)
 {
     global $config, $db, $member_id;
     $this->allowed_files = explode(',', strtolower($config['files_type']));
     $this->area = totranslit($area);
     if ($config['charset'] == "windows-1251" and $config['charset'] != detect_encoding($author)) {
         $author = iconv("UTF-8", "windows-1251//IGNORE", $author);
     }
     $this->author = $db->safesql($author);
     $this->news_id = intval($news_id);
     $this->t_size = $t_size;
     $this->t_seite = $t_seite;
     $this->make_thumb = $make_thumb;
     $this->make_watermark = $make_watermark;
     $this->flash_mode = $flash_mode;
     if (isset($_FILES['qqfile'])) {
         $this->file = new UploadFileViaForm();
     } elseif (isset($_FILES['Filedata'])) {
         $this->file = new UploadFileViaFlash();
     } elseif ($_POST['imageurl'] != "") {
         $this->file = new UploadFileViaURL();
     } elseif ($member_id['user_group'] == 1 and $_POST['ftpurl'] != "") {
         $this->file = new UploadFileViaFTP();
     } else {
         $this->file = false;
     }
     if (@ini_get('safe_mode') == 1) {
         define('FOLDER_PREFIX', "");
     } else {
         define('FOLDER_PREFIX', date("Y-m") . "/");
     }
 }
 function show_html_mail()
 {
     $pre = array_var($_GET, 'pre');
     $filename = ROOT . "/tmp/" . $pre . "_temp_mail_content.html";
     if (!file_exists($filename)) {
         ajx_current("empty");
         return;
     }
     $content = file_get_contents($filename);
     $encoding = detect_encoding($content, array('UTF-8', 'ISO-8859-1', 'WINDOWS-1252'));
     header("Expires: " . gmdate("D, d M Y H:i:s", mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y"))) . " GMT");
     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
     header("Content-Type: text/html;charset=" . $encoding);
     header("Content-Length: " . (string) strlen($content));
     print $content;
     die;
 }
Exemple #6
0
 // check and correct file encoding
 function detect_encoding($string)
 {
     $list = array('utf-8', 'iso-8859-15', 'iso-8859-1', 'iso-8859-3', 'windows-1251');
     foreach ($list as $item) {
         try {
             $sample = iconv($item, $item, $string);
             if (md5($sample) == md5($string)) {
                 return $item;
             }
         } catch (Exception $e) {
         }
     }
     return null;
 }
 $enc = detect_encoding($data);
 // works better than mb_detect_encoding($data);
 if (strtolower($enc) != "utf-8") {
     $data = mb_convert_encoding($data, "utf-8", $enc);
 }
 try {
     if ($result['success']) {
         $filename = $chart->writeData($data);
         $chart->save();
         //echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
         unlink($uploader->filename);
         ok($result);
     } else {
         error('upload-error', $result['error']);
     }
 } catch (Exception $e) {
 function SaveMail(&$content, MailAccount $account, $uidl, $state = 0, $imap_folder_name = '', $read = null, &$received_count)
 {
     try {
         if (strpos($content, '+OK ') > 0) {
             $content = substr($content, strpos($content, '+OK '));
         }
         self::parseMail($content, $decoded, $parsedMail, $warnings);
         $encoding = array_var($parsedMail, 'Encoding', 'UTF-8');
         $enc_conv = EncodingConverter::instance();
         $to_addresses = self::getAddresses(array_var($parsedMail, "To"));
         $from = self::getAddresses(array_var($parsedMail, "From"));
         $message_id = self::getHeaderValueFromContent($content, "Message-ID");
         $in_reply_to_id = self::getHeaderValueFromContent($content, "In-Reply-To");
         $uid = trim($uidl);
         if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) {
             $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding);
         }
         if ($uid == '') {
             $uid = trim($message_id);
             if ($uid == '') {
                 $uid = array_var($parsedMail, 'Subject', 'MISSING UID');
             }
             if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) {
                 $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding);
             }
         }
         // do not save duplicate emails
         if (MailContents::mailRecordExists($account->getId(), $uid, $imap_folder_name == '' ? null : $imap_folder_name)) {
             return;
         }
         if (!$from) {
             $parsedMail["From"] = self::getFromAddressFromContent($content);
             $from = array_var($parsedMail["From"][0], 'address', '');
         }
         if (defined('EMAIL_MESSAGEID_CONTROL') && EMAIL_MESSAGEID_CONTROL) {
             if (trim($message_id) != "") {
                 $id_condition = " AND `message_id`='" . trim($message_id) . "' AND `from`='{$from}'";
             } else {
                 $id_condition = " AND `name`= " . DB::escape(trim(array_var($parsedMail, 'Subject'))) . " AND `from`='{$from}'";
                 if (array_var($parsedMail, 'Date')) {
                     $sent_date_dt = new DateTimeValue(strtotime(array_var($parsedMail, 'Date')));
                     $sent_date_str = $sent_date_dt->toMySQL();
                     $id_condition .= " AND `sent_date`='" . $sent_date_str . "'";
                 }
             }
             $same = MailContents::findOne(array('conditions' => "`account_id`=" . $account->getId() . $id_condition, 'include_trashed' => true));
             if ($same instanceof MailContent) {
                 return;
             }
         }
         $from_spam_junk_folder = strpos(strtolower($imap_folder_name), 'spam') !== FALSE || strpos(strtolower($imap_folder_name), 'junk') !== FALSE || strpos(strtolower($imap_folder_name), 'trash') !== FALSE;
         $user_id = logged_user() instanceof Contact ? logged_user()->getId() : $account->getContactId();
         $max_spam_level = user_config_option('max_spam_level', null, $user_id);
         if ($max_spam_level < 0) {
             $max_spam_level = 0;
         }
         $spam_level_header = 'x-spam-level:';
         foreach ($decoded[0]['Headers'] as $hdr_name => $hdrval) {
             if (strpos(strtolower($hdr_name), "spamscore") !== false || strpos(strtolower($hdr_name), "x-spam-level")) {
                 $spam_level_header = $hdr_name;
                 break;
             }
         }
         $mail_spam_level = strlen(trim(array_var($decoded[0]['Headers'], $spam_level_header, '')));
         // if max_spam_level >= 10 then nothing goes to junk folder
         $spam_in_subject = false;
         if (config_option('check_spam_in_subject')) {
             $spam_in_subject = strpos_utf(strtoupper(array_var($parsedMail, 'Subject')), "**SPAM**") !== false;
         }
         if ($max_spam_level < 10 && ($mail_spam_level > $max_spam_level || $from_spam_junk_folder) || $spam_in_subject) {
             $state = 4;
             // send to Junk folder
         }
         //if you are in the table spam MailSpamFilters
         if ($state != 4) {
             $spam_email = MailSpamFilters::getFrom($account->getId(), $from);
             if ($spam_email) {
                 $state = 0;
                 if ($spam_email[0]->getSpamState() == "spam") {
                     $state = 4;
                 }
             } else {
                 if ($state == 0) {
                     if (strtolower($from) == strtolower($account->getEmailAddress())) {
                         if (strpos($to_addresses, $from) !== FALSE) {
                             $state = 5;
                         } else {
                             $state = 1;
                         }
                         //Show only in sent folder
                     }
                 }
             }
         }
         if (!isset($parsedMail['Subject'])) {
             $parsedMail['Subject'] = '';
         }
         $mail = new MailContent();
         $mail->setAccountId($account->getId());
         $mail->setState($state);
         $mail->setImapFolderName($imap_folder_name);
         $mail->setFrom($from);
         $cc = trim(self::getAddresses(array_var($parsedMail, "Cc")));
         if ($cc == '' && array_var($decoded, 0) && array_var($decoded[0], 'Headers')) {
             $cc = array_var($decoded[0]['Headers'], 'cc:', '');
         }
         $mail->setCc($cc);
         $from_name = trim(array_var(array_var(array_var($parsedMail, 'From'), 0), 'name'));
         $from_encoding = detect_encoding($from_name);
         if ($from_name == '') {
             $from_name = $from;
         } else {
             if (strtoupper($encoding) == 'KOI8-R' || strtoupper($encoding) == 'CP866' || $from_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($from_name)) {
                 //KOI8-R and CP866 are Russian encodings which PHP does not detect
                 $utf8_from = $enc_conv->convert($encoding, 'UTF-8', $from_name);
                 if ($enc_conv->hasError()) {
                     $utf8_from = utf8_encode($from_name);
                 }
                 $utf8_from = utf8_safe($utf8_from);
                 $mail->setFromName($utf8_from);
             } else {
                 $mail->setFromName($from_name);
             }
         }
         $subject_aux = $parsedMail['Subject'];
         $subject_encoding = detect_encoding($subject_aux);
         $subject_multipart_encoding = array_var($parsedMail, 'SubjectEncoding', strtoupper($encoding));
         if ($subject_multipart_encoding != 'UTF-8' && ($subject_multipart_encoding == 'KOI8-R' || $subject_multipart_encoding == 'CP866' || $subject_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($subject_aux))) {
             //KOI8-R and CP866 are Russian encodings which PHP does not detect
             $utf8_subject = $enc_conv->convert($subject_multipart_encoding, 'UTF-8', $subject_aux);
             if ($enc_conv->hasError()) {
                 $utf8_subject = utf8_encode($subject_aux);
             }
             $utf8_subject = utf8_safe($utf8_subject);
             $mail->setSubject($utf8_subject);
         } else {
             $utf8_subject = utf8_safe($subject_aux);
             $mail->setSubject($utf8_subject);
         }
         $mail->setTo($to_addresses);
         $sent_timestamp = false;
         if (array_key_exists("Date", $parsedMail)) {
             $sent_timestamp = strtotime($parsedMail["Date"]);
         }
         if ($sent_timestamp === false || $sent_timestamp === -1 || $sent_timestamp === 0) {
             $mail->setSentDate(DateTimeValueLib::now());
         } else {
             $mail->setSentDate(new DateTimeValue($sent_timestamp));
         }
         // if this constant is defined, mails older than this date will not be fetched
         if (defined('FIRST_MAIL_DATE')) {
             $first_mail_date = DateTimeValueLib::makeFromString(FIRST_MAIL_DATE);
             if ($mail->getSentDate()->getTimestamp() < $first_mail_date->getTimestamp()) {
                 // return true to stop getting older mails from the server
                 return true;
             }
         }
         $received_timestamp = false;
         if (array_key_exists("Received", $parsedMail) && $parsedMail["Received"]) {
             $received_timestamp = strtotime($parsedMail["Received"]);
         }
         if ($received_timestamp === false || $received_timestamp === -1 || $received_timestamp === 0) {
             $mail->setReceivedDate($mail->getSentDate());
         } else {
             $mail->setReceivedDate(new DateTimeValue($received_timestamp));
             if ($state == 5 && $mail->getSentDate()->getTimestamp() > $received_timestamp) {
                 $mail->setReceivedDate($mail->getSentDate());
             }
         }
         $mail->setSize(strlen($content));
         $mail->setCreatedOn(new DateTimeValue(time()));
         $mail->setCreatedById($account->getContactId());
         $mail->setAccountEmail($account->getEmail());
         $mail->setMessageId($message_id);
         $mail->setInReplyToId($in_reply_to_id);
         // set hasAttachments=true onlu if there is any attachment with FileDisposition='attachment'
         $has_attachments = false;
         foreach (array_var($parsedMail, "Attachments", array()) as $attachment) {
             if (array_var($attachment, 'FileDisposition') == 'attachment') {
                 $has_attachments = true;
             }
         }
         $mail->setHasAttachments($has_attachments);
         $mail->setUid($uid);
         $type = array_var($parsedMail, 'Type', 'text');
         switch ($type) {
             case 'html':
                 $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', ''));
                 //Solve bad syntax styles outlook if it exists
                 if (substr_count($utf8_body, "<style>") != substr_count($utf8_body, "</style>") && substr_count($utf8_body, "/* Font Definitions */") >= 1) {
                     $p1 = strpos($utf8_body, "/* Font Definitions */", 0);
                     $utf8_body1 = substr($utf8_body, 0, $p1);
                     $p0 = strrpos($utf8_body1, "</style>");
                     $html_content = ($p0 >= 0 ? substr($utf8_body1, 0, $p0) : $utf8_body1) . substr($utf8_body, $p1);
                     $utf8_body = str_replace_first("/* Font Definitions */", "<style>", $utf8_body);
                 }
                 if ($enc_conv->hasError()) {
                     $utf8_body = utf8_encode(array_var($parsedMail, 'Data', ''));
                 }
                 $utf8_body = utf8_safe($utf8_body);
                 $mail->setBodyHtml($utf8_body);
                 break;
             case 'text':
                 $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', ''));
                 if ($enc_conv->hasError()) {
                     $utf8_body = utf8_encode(array_var($parsedMail, 'Data', ''));
                 }
                 $utf8_body = utf8_safe($utf8_body);
                 $mail->setBodyPlain($utf8_body);
                 break;
             case 'delivery-status':
                 $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Response', ''));
                 if ($enc_conv->hasError()) {
                     $utf8_body = utf8_encode(array_var($parsedMail, 'Response', ''));
                 }
                 $utf8_body = utf8_safe($utf8_body);
                 $mail->setBodyPlain($utf8_body);
                 break;
             default:
                 if (array_var($parsedMail, 'FileDisposition') == 'inline') {
                     $attachs = array_var($parsedMail, 'Attachments', array());
                     $attached_body = "";
                     foreach ($attachs as $k => $attach) {
                         if (array_var($attach, 'Type') == 'html' || array_var($attach, 'Type') == 'text') {
                             $attached_body .= $enc_conv->convert(array_var($attach, 'Encoding'), 'UTF-8', array_var($attach, 'Data'));
                         }
                     }
                     $mail->setBodyHtml($attached_body);
                 } else {
                     if (isset($parsedMail['FileName'])) {
                         // content-type is a file type => set as it has attachments, they will be parsed when viewing email
                         $mail->setHasAttachments(true);
                     }
                 }
                 break;
         }
         if (isset($parsedMail['Alternative'])) {
             foreach ($parsedMail['Alternative'] as $alt) {
                 if ($alt['Type'] == 'html' || $alt['Type'] == 'text') {
                     $body = $enc_conv->convert(array_var($alt, 'Encoding', 'UTF-8'), 'UTF-8', array_var($alt, 'Data', ''));
                     if ($enc_conv->hasError()) {
                         $body = utf8_encode(array_var($alt, 'Data', ''));
                     }
                     // remove large white spaces
                     //$exploded = preg_split("/[\s]+/", $body, -1, PREG_SPLIT_NO_EMPTY);
                     //$body = implode(" ", $exploded);
                     // remove html comments
                     $body = preg_replace('/<!--.*-->/i', '', $body);
                 }
                 $body = utf8_safe($body);
                 if ($alt['Type'] == 'html') {
                     $mail->setBodyHtml($body);
                 } else {
                     if ($alt['Type'] == 'text') {
                         $plain = html_to_text(html_entity_decode($body, null, "UTF-8"));
                         $mail->setBodyPlain($plain);
                     }
                 }
                 // other alternative parts (like images) are not saved in database.
             }
         }
         $repository_id = self::SaveContentToFilesystem($mail->getUid(), $content);
         $mail->setContentFileId($repository_id);
         // START TRANSACTION
         DB::beginWork();
         // Conversation
         //check if exists a conversation for this mail
         $conv_mail = "";
         if ($in_reply_to_id != "" && $message_id != "") {
             $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND (`message_id` = '{$in_reply_to_id}' OR `in_reply_to_id` = '{$message_id}')"));
             //check if this mail is in two diferent conversations and fixit
             if ($conv_mail) {
                 $other_conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `conversation_id` != " . $conv_mail->getConversationId() . " AND (`message_id` = '{$in_reply_to_id}' OR `in_reply_to_id` = '{$message_id}')"));
                 if ($other_conv_mail) {
                     $other_conv = MailContents::findAll(array("conditions" => "`account_id`=" . $account->getId() . " AND `conversation_id` = " . $other_conv_mail->getConversationId()));
                     if ($other_conv) {
                         foreach ($other_conv as $mail_con) {
                             $mail_con->setConversationId($conv_mail->getConversationId());
                             $mail_con->save();
                         }
                     }
                 }
             }
         } elseif ($in_reply_to_id != "") {
             $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}'"));
         } elseif ($message_id != "") {
             $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `in_reply_to_id` = '{$message_id}'"));
         }
         if ($conv_mail instanceof MailContent) {
             $conv_id = $conv_mail->getConversationId();
         } else {
             $conv_id = MailContents::getNextConversationId($account->getId());
         }
         $mail->setConversationId($conv_id);
         $mail->save();
         // CLASSIFY RECEIVED MAIL WITH THE CONVERSATION
         $classified_with_conversation = false;
         $member_ids = array();
         if (user_config_option('classify_mail_with_conversation', null, $account->getContactId()) && isset($conv_mail) && $conv_mail instanceof MailContent) {
             $member_ids = array_merge($member_ids, $conv_mail->getMemberIds());
             $classified_with_conversation = true;
         }
         // CLASSIFY MAILS IF THE ACCOUNT HAS A DIMENSION MEMBER AND NOT CLASSIFIED WITH CONVERSATION
         $account_owner = Contacts::findById($account->getContactId());
         if ($account->getMemberId() != '' && !$classified_with_conversation) {
             $acc_mem_ids = explode(',', $account->getMemberId());
             foreach ($acc_mem_ids as $acc_mem_id) {
                 $member_ids[] = $acc_mem_id;
             }
         }
         foreach ($member_ids as $k => &$mem_id) {
             if ($mem_id == "") {
                 unset($member_ids[$k]);
             }
         }
         if (count($member_ids) > 0) {
             $members = Members::instance()->findAll(array('conditions' => 'id IN (' . implode(',', $member_ids) . ')'));
             $mail->addToMembers($members, true);
             /*	$ctrl = new ObjectController();
             			$ctrl->add_to_members($mail, $member_ids, $account_owner);*/
             $mail_controller = new MailController();
             $mail_controller->do_classify_mail($mail, $member_ids, null, false, true);
         }
         $user = Contacts::findById($account->getContactId());
         if ($user instanceof Contact) {
             $mail->subscribeUser($user);
         }
         $mail->addToSharingTable();
         $mail->orderConversation();
         //if email is from an imap account copy the state (read/unread) from the server
         if (!is_null($read)) {
             $mail->setIsRead($account->getContactId(), $read);
         }
         // increase received count
         $received_count++;
         // to apply email rules
         $null = null;
         Hook::fire('after_mail_download', $mail, $null);
         DB::commit();
     } catch (Exception $e) {
         $ret = null;
         Hook::fire('on_save_mail_error', array('content' => $content, 'account' => $account, 'exception' => $e), $ret);
         Logger::log($e->__toString());
         DB::rollback();
         if (FileRepository::isInRepository($repository_id)) {
             FileRepository::deleteFile($repository_id);
         }
         if (strpos($e->getMessage(), "Query failed with message 'Got a packet bigger than 'max_allowed_packet' bytes'") === false) {
             throw $e;
         }
     }
     unset($parsedMail);
     return false;
 }
 public function test()
 {
     edump(md5('jinyanlin123456'));
     //Input::get('pass') == 'jUT4GlZtq3tHoPUE')
     exit;
     $phones = file_get_contents('phones.txt');
     $arr = preg_split('/\\s+/', $phones);
     $array = array_chunk($arr, intval(count($arr) / 3) + 1);
     $rse = [];
     foreach ($array as $k => $v) {
         $key = '7WQRJOnYAQUYGVSzke';
         $phone = $v;
         $message = '仁仁提醒:近期同学反馈有不法分子在百度留下私人电话冒充仁仁客服,对方会谎称同学还款失败需要重新还款,并要求将款项打入私人账户!请同学们提高警惕,如有任何问题先拨打官方唯一客服电话4007800087或风控部电话13454129972咨询!';
         $params = array('mobile' => implode(',', $phone), 'message' => $message);
         $params['pass'] = '******';
         $url = "https://secure.renrenfenqi.com/interface/crm/sms";
         $rse[] = curl_post($url, $params);
         sleep(2);
     }
     $url = "https://gw.alicdn.com/tps/i3/TB1QeiDGFXXXXb8XVXXszjdGpXX-140-140.png?imgtag=avatar";
     $content = file_get_contents($url);
     file_put_contents("TB1QeiDGFXXXXb8XVXXszjdGpXX-140-140.png", $content);
     exit;
     $content = file_get_contents('20160218');
     edump(detect_encoding($content));
     dump(__FUNCTION__);
     exit;
     $unit = new \App\Gather\RPG\UnitBase('Unit001');
     $unit->showDiedMessage();
     exit;
     $str = 'showInjuredMessage';
     dump(preg_replace('/[A-Z]/', '#\\0', $str));
     edump(preg_split('/[A-Z]/', $str));
     exit;
     if (version_compare(PHP_VERSION, '5.3.6', '>=')) {
         list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
     } else {
         list($current, $caller) = debug_backtrace(false, 2);
     }
     //         edump($backtrace);
     //         list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
     dump($current);
     edump($caller);
     \App\Gather\AESTool::main();
     exit;
     $url = 'http://www.xunshu.la/22_22665/7813282.html';
     $word = \Input::get('w');
     //         if(!$word){
     //             echo 'Word Is Required!';
     //             exit();
     //         }
     $sourceData = \App\Models\Transfer::all()->toArray();
     $transferData = [];
     $file = 'yun.xml';
     $content = file_get_contents($file);
     $resEN = $this->__xmlToArray($content);
     $n = 0;
     \DB::beginTransaction();
     foreach ($sourceData as $v) {
         if ($v['status'] == 0 && $v['eng'] != $resEN[$v['uid']]) {
             $str = html_entity_decode($resEN[$v['uid']]);
             $r = preg_replace('/<[^>]*>/', '', $str);
             preg_match_all('/[a-zA-Z]/i', $r, $metchs);
             if (count($metchs[0]) >= 1) {
                 continue;
             }
             echo $n . '[En]' . $v['eng'] . '<br/>';
             echo $n . '[Ch]' . $resEN[$v['uid']] . '<br/>';
             $n++;
             \App\Models\Transfer::where('id', $v['id'])->update(['status' => 2, 'chi' => htmlspecialchars($resEN[$v['uid']])]);
         }
     }
     \DB::commit();
     exit;
     foreach ($sourceData as $v) {
         $transferData[$v['contentuid']] = $v;
         $reg = '/' . $word . '/i';
         if ($word && preg_match($reg, $v['eng'])) {
             $str = preg_replace($reg, '<font color="red">\\0</font>', $v['eng']);
             echo '[EN]:' . $str . '<br/>';
             echo '[CH]:' . ($v['status'] == 1 ? $v['chi'] : '<textarea></textarea>') . '<br/>';
         }
     }
     //         dump($transferData);
     exit;
     exit;
     $fbsdk = \App\Services\Merchants\FBSdkService::getInstance();
     $file = 'english.xml';
     $content = file_get_contents($file);
     $resEN = $this->__xmlToArray($content);
     $file = 'hanhua.xml';
     $content = file_get_contents($file);
     $resCH = $this->__xmlToArray($content);
     //         $fp = fopen('result.xml', 'w');
     //         fputs($fp, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?\>
     // <contentList>'.PHP_EOL);
     //         $fp1 = fopen('eng.xml', 'w');
     //         fputs($fp1, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?\>
     // <contentList>'.PHP_EOL);
     $word = \Input::get('w');
     if (!$word) {
         echo 'Word Is Required!';
         exit;
     }
     set_time_limit(0);
     $fromEn = 0;
     $fromCh = 0;
     $length = 0;
     $insertData = [];
     foreach ($resEN as $k => $v) {
         if (strlen($v) > $length) {
             $length = strlen($v);
         }
         //             $reg = '/'.$word.'/i';
         //             if(preg_match($reg, $resEN[$k])){
         //                 $resEN[$k] = preg_replace($reg, '<font color="red">\\0</font>', $resEN[$k]);
         //                 echo ''.$resEN[$k] .'--'. ( isset($resCH[$k]) ? $resCH[$k] : '<textarea></textarea>' ) .'<br/>';
         //             }
         if (isset($resCH[$k])) {
             //                 $resEN[$k] = $resCH[$k];
             $fromCh++;
             $record = ['uid' => $k, 'eng' => $resEN[$k], 'chi' => $resCH[$k], 'status' => 1];
         } else {
             $resEN[$k] = htmlspecialchars($resEN[$k]);
             $fromEn++;
             $str = "\t<content contentuid=\"{$k}\">{$resEN[$k]}</content>" . PHP_EOL;
             //                 if(strlen($resEN[$k]) < 20)
             //                 echo htmlspecialchars($resEN[$k]).'<br/>';;
             //                 fputs($fp1, $str);
             $record = ['uid' => $k, 'eng' => $resEN[$k], 'chi' => '', 'status' => 0];
         }
         $resEN[$k] = htmlspecialchars($resEN[$k]);
         $str = "\t<content contentuid=\"{$k}\">{$resEN[$k]}</content>" . PHP_EOL;
         //             fputs($fp, $str);
         $insertData[] = $record;
         if (count($insertData) > 100) {
             \App\Models\Transfer::insert($insertData);
             $insertData = [];
         }
     }
     $insertData && \App\Models\Transfer::insert($insertData);
     //         fputs($fp, '</contentList>');
     //         fputs($fp1, '</contentList>');
     //         fclose($fp);
     //         fclose($fp1);
     dump('From English:' . $fromEn);
     dump('From Chinese:' . $fromCh);
     dump($length);
     exit;
     edump($resEN);
     //         http://fanyi.baidu.com/v2transapi
     //         from:en
     //         to:zh
     //         query:Invariant
     //         transtype:realtime
     //         simple_means_flag:3
     $res = curl_post('http://fanyi.baidu.com/v2transapi', ['from' => 'en', 'to' => 'zh', 'query' => 'realtime', 'transtype' => 'realtime', 'simple_means_flag' => '3']);
     edump(json_decode($res, 1));
 }
} else {
    $newsid = 0;
}
if (isset($_GET['cstart'])) {
    $cstart = intval($_GET['cstart']);
} else {
    $cstart = 0;
}
if (isset($_GET['news_page'])) {
    $news_page = intval($_GET['news_page']);
} else {
    $news_page = 0;
}
if (isset($_GET['user'])) {
    $user = @strip_tags(str_replace('/', '', urldecode($_GET['user'])));
    if ($config['charset'] == "windows-1251" and $config['charset'] != detect_encoding($user)) {
        $user = iconv("UTF-8", "windows-1251//IGNORE", $user);
    }
    $user = $db->safesql($user);
    if (preg_match("/[\\||\\'|\\<|\\>|\"|\\!|\\?|\$|\\@|\\/|\\\\|\\&\\~\\*\\+]/", $user)) {
        $user = "";
    }
} else {
    $user = '';
}
$category = '';
if (isset($_REQUEST['do'])) {
    $do = totranslit($_REQUEST['do']);
} else {
    $do = "";
}
 function __construct($area, $news_id, $author, $t_size, $t_seite, $make_thumb = true, $make_watermark = true, $flash_mode = false)
 {
     global $config, $db, $member_id, $user_group;
     $this->area = totranslit($area);
     if ($this->area == "adminupload") {
         if (!isset($_FILES['qqfile']) or $member_id['user_group'] != 1) {
             die("Hacking attempt!");
         }
         if ($_REQUEST['userdir']) {
             $userdir = totranslit($_REQUEST['userdir'], true, false) . "/";
         } else {
             $userdir = "";
         }
         if ($_REQUEST['subdir']) {
             $subdir = totranslit($_REQUEST['subdir'], true, false) . "/";
         } else {
             $subdir = "";
         }
         $this->upload_path = $userdir . $subdir;
         $this->use_prefix = false;
     } else {
         $this->allowed_files = explode(',', strtolower($user_group[$member_id['user_group']]['files_type']));
     }
     if ($config['charset'] == "windows-1251" and $config['charset'] != detect_encoding($author)) {
         if (function_exists('mb_convert_encoding')) {
             $author = mb_convert_encoding($author, "windows-1251", "UTF-8");
         } elseif (function_exists('iconv')) {
             $author = iconv("UTF-8", "windows-1251//IGNORE", $author);
         }
     }
     $this->author = $db->safesql($author);
     $this->news_id = intval($news_id);
     $this->t_size = $t_size;
     $this->t_seite = $t_seite;
     $this->make_thumb = $make_thumb;
     $this->make_watermark = $make_watermark;
     $this->flash_mode = $flash_mode;
     $ftp_upload_flag = false;
     if (isset($_FILES['qqfile'])) {
         $this->file = new UploadFileViaForm();
     } elseif (isset($_FILES['Filedata'])) {
         $this->file = new UploadFileViaFlash();
     } elseif ($_POST['imageurl'] != "") {
         $this->file = new UploadFileViaURL();
     } elseif ($member_id['user_group'] == 1 and $_POST['ftpurl'] != "") {
         $this->file = new UploadFileViaFTP();
         $ftp_upload_flag = true;
     } else {
         $this->file = false;
     }
     if (@ini_get('safe_mode') == 1 or $ftp_upload_flag or $this->area == "adminupload") {
         define('FOLDER_PREFIX', "");
     } else {
         define('FOLDER_PREFIX', date("Y-m") . "/");
     }
 }
Exemple #11
0
 function _parse_config_section($body)
 {
     $_result = array();
     preg_match_all('!(\\n\\s*[a-zA-Z0-9_]+)\\s*=\\s*(' . $this->_qstr_regexp . ')!s', $body, $ini);
     $keys = $ini[1];
     $values = $ini[2];
     for ($i = 0, $for_max = count($ini[0]); $i < $for_max; $i++) {
         if ($this->booleanize) {
             if (preg_match('/^(' . $this->_bool_true_regexp . ')$/i', $values[$i])) {
                 $values[$i] = true;
             } elseif (preg_match('/^(' . $this->_bool_false_regexp . ')$/i', $values[$i])) {
                 $values[$i] = false;
             }
         }
         if (!is_numeric($values[$i]) && !is_bool($values[$i])) {
             $values[$i] = str_replace("\n", '', stripslashes(substr($values[$i], 1, -1)));
             if (function_exists("iconv") && detect_encoding($values[$i]) != 'utf-8') {
                 $values[$i] = iconv('', 'UTF-8//IGNORE', $values[$i]);
             }
         }
         if ($this->overwrite || !isset($_result[trim($keys[$i])])) {
             $_result[trim($keys[$i])] = $values[$i];
         } else {
             if (!is_array($_result[trim($keys[$i])])) {
                 $_result[trim($keys[$i])] = array($_result[trim($keys[$i])]);
             }
             $_result[trim($keys[$i])][] = $values[$i];
         }
     }
     return $_result;
 }
Exemple #12
0
/**
 * Cette méthode prend une chaîne de caractères et s'assure qu'elle est bien retournée en UTF-8
 * Attention, certain encodages sont très similaire et ne peuve pas être théoriquement distingué sur une chaine de caractere.
 * Si vous connaissez déjà l'encodage de votre chaine de départ, il est préférable de le préciser
 * 
 * @param string $str La chaine à encoder
 * @param string $encoding L'encodage de départ
 * @return string La chaine en utf8
 * @throws Exception si la chaine n'a pas pu être encodée correctement
 */
function ensure_utf8($str, $from_encoding = null)
{
    if ($str === null || $str === '') {
        return $str;
    } else {
        if ($from_encoding == null && detect_utf8($str)) {
            return $str;
        }
    }
    if ($from_encoding != null) {
        $encoding = $from_encoding;
    } else {
        $encoding = detect_encoding($str);
    }
    $result = null;
    if ($encoding !== false && $encoding != null) {
        if (function_exists('mb_convert_encoding')) {
            $result = mb_convert_encoding($str, 'UTF-8', $encoding);
        }
    }
    if ($result === null || !detect_utf8($result)) {
        throw new Exception('Impossible de convertir la chaine vers l\'utf8');
    }
    return $result;
}
Exemple #13
0
?>
" action="<?php 
echo get_url('files', 'text_edit');
?>
" method="post" enctype="multipart/form-data">

	<div>
		<input type="hidden" name="file[id]" value="<?php 
echo $file->getId();
?>
" />
		<input type="hidden" name="file[name]" value="<?php 
echo clean($file->getFilename());
?>
" />
		<input type="hidden" name="file[encoding]" value="<?php 
echo detect_encoding($filecontent, array('UTF-8', 'ISO-8859-1'));
?>
" />
		<input type="hidden" name="new_revision_document" value="" />
 	</div>

	<textarea class="textedit" name="fileContent"><?php 
echo htmlEntities(EncodingConverter::instance()->convert(detect_encoding($filecontent, array('UTF-8', 'ISO-8859-1')), 'UTF-8', $filecontent), null, 'UTF-8');
?>
</textarea>
<?php 
add_page_action(lang("save"), "javascript:(function(){ var form = document.getElementById('{$iname}'); form.new_revision_document.value = 'checked'; form.onsubmit(); })()", "save");
?>
</form>
    $string = implode("", gzfile($srcName));
    $fp = fopen($dstName, "w");
    fwrite($fp, $string, strlen($string));
    fclose($fp);
}
$subs_file = file_get_contents("export.txt");
$subs = array();
preg_match_all("/.*[\\n\\r]+/iu", $subs_file, $matches);
foreach ($matches[0] as $line) {
    $subtitle = explode("\t", $line);
    if (!is_numeric($subtitle[1])) {
        continue;
    }
    uncompress('/home/soshial/subs/opensubtitles/' . $subtitle[1] . '.gz', '/home/soshial/subs/opensubtitles2/' . $subtitle[1] . '.srt');
    $sub_text = file_get_contents('/home/soshial/subs/opensubtitles2/' . $subtitle[1] . '.srt');
    if (detect_encoding($sub_text) == 'windows-1251') {
        $sub_text = strip_tags_smart(iconv('windows-1251', 'UTF-8//IGNORE', $sub_text));
    }
    // изменяем кодировку на юникод, и вычищаем от тегов
    $sub_text = preg_replace('/\\s*\\d+\\r\\n\\d\\d:\\d\\d:\\d\\d,\\d+ --> \\d\\d:\\d\\d:\\d\\d,\\d+/i', '', $sub_text, -1, $count);
    // вырезаем временные метки
    $sub_text = preg_replace('/\\.{2,}/i', '…', $sub_text, -1, $count);
    // заменяем многоточия
    /* склеиваем текст */
    $sub_text = preg_replace("/([^!…\\?_][a-z0-9а-яё])(\\s)*\\r\\n(\\s)*([…«\"\\-]{0,1}(\\s)*[a-zа-яё]{1,}[^\\)])/u", '$1 $4', $sub_text, -1, $count);
    // ориентация на отсутствие препинаний в конце первого параграфа и на строчные в начале второго п.,
    // где перед буквами могут находиться кавычки: «" и дефис
    // предполагается автоматическое объединение
    $sub_text = preg_replace("/([^!…\\?_][a-z0-9А-яё,;—–\\-\\»\\)IVX])(\\s)*\\r\\n(\\s)*([«\\(\\[\"\\-–—=…]{0,1}(\\s)*[a-z0-9а-яё\\?\\!…\"]+[^\\)])/u", '$1 $4', $sub_text, -1, $count);
    // ориентация на отсутствие точки в конце первого параграфа и на строчные в начале второго п.,
    // где перед буквами и цифрами могут находиться кавычки: «", дефис и скобки: ([
/**
* get_feed_data($_params)
* returns the parsed feed.
* */
function get_feed_data($_params)
{
    global $user, $config;
    $feed_data = array('items' => array(), 'setup' => array('date' => false, 'author' => false, 'desclen' => 0, 'chantitle' => '', 'chanlink' => ''));
    @ini_set('user_agent', 'GYM Sitemaps &amp; RSS / www.phpBB-SEO.com');
    @ini_set('default_socket_timeout', 5);
    $xml = @file_get_contents($_params['url']);
    if ($xml) {
        // Get encoding
        $encoding = get_match('`encoding=[\'"]([a-z0-9_-]+)[\'"]`Usi', $xml);
        $encoding = !empty($encoding) ? strtolower($encoding) : detect_encoding($xml);
        if (preg_match('`<item>(.*)</item>`si', $xml, $matches)) {
            // Get chan info
            $feed_data['setup']['chantitle'] = get_match('`<title>(.*)</title>`Usi', $xml, $encoding);
            $feed_data['setup']['chanlink'] = get_match('`<link>(.*)</link>`Usi', $xml, $encoding);
            $xml = trim($matches[0]);
            unset($matches);
            preg_match_all('`<item>(.*)</item>`Usi', $xml, $matches);
            unset($matches[0]);
            if (!empty($matches[1]) && is_array($matches[1])) {
                $i = 1;
                foreach ($matches[1] as $key => $item) {
                    if ($i > $_params['limit']) {
                        break;
                    }
                    if ($title = get_match('`<title>(.*)</title>`Usi', $item, $encoding)) {
                        if ($link = get_match('`<link>(.*)</link>`Usi', $item, $encoding)) {
                            $feed_data['items'][$i]['PUBDATE'] = false;
                            if ($pubdate = get_match('`<pubDate>(.*)</pubDate>`Usi', $item, $encoding)) {
                                if (($pubdate = strtotime($pubdate, $user->time_now)) > 0) {
                                    $feed_data['items'][$i]['PUBDATE'] = $user->format_date($pubdate, $config['default_dateformat']);
                                    $feed_data['setup']['date'] = true;
                                }
                            }
                            $feed_data['items'][$i]['DESC'] = false;
                            if ($_params['desc'] && ($description = get_match('`<description>(.*)</description>`Usi', $item, $encoding))) {
                                if (empty($_params['html'])) {
                                    $description = htmlspecialchars($_params['striptags'] ? strip_tags($description) : $description, ENT_COMPAT, 'UTF-8');
                                }
                                $feed_data['items'][$i]['DESC'] = str_replace(array("\r", "\n"), '<br />', $description);
                                $feed_data['setup']['desclen'] += utf8_strlen($feed_data['items'][$i]['DESC']);
                            }
                            $feed_data['items'][$i]['SOURCE'] = false;
                            if ($source = get_match('`<source[\\s]+url="(.*)">(.*)</source>`Usi', $item, $encoding)) {
                                $feed_data['items'][$i]['SOURCE'] = htmlspecialchars($source, ENT_COMPAT, 'UTF-8');
                            }
                            $feed_data['items'][$i]['TITLE'] = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
                            $feed_data['items'][$i]['LINK'] = htmlspecialchars($link, ENT_COMPAT, 'UTF-8');
                            $feed_data['items'][$i]['IMG'] = $user->img('topic_read', $feed_data['items'][$i]['TITLE'], false, '', 'src');
                            $i++;
                        }
                    }
                    unset($matches[1][$key]);
                }
            }
            unset($matches);
        }
    }
    unset($xml);
    return $feed_data;
}
function admin_language_showpage()
{
    global $main_smarty, $the_template;
    include_once 'config.php';
    include_once mnminclude . 'html1.php';
    include_once mnminclude . 'link.php';
    include_once mnminclude . 'tags.php';
    include_once mnminclude . 'smartyvariables.php';
    $main_smarty = do_sidebar($main_smarty);
    force_authentication();
    $canIhaveAccess = 0;
    $canIhaveAccess = $canIhaveAccess + checklevel('god');
    if ($canIhaveAccess == 1) {
        if ($_REQUEST['var_id'] != "") {
            $lines = file('./languages/lang_' . pligg_language . '.conf');
            $filename = './languages/lang_' . pligg_language . '.conf';
            if ($handle = fopen($filename, 'w')) {
                foreach ($lines as $line_num => $line) {
                    if (substr($line, 0, 2) != "//") {
                        if (strlen(trim($line)) > 2) {
                            $x = strpos($line, "=");
                            if (trim(substr($line, 0, $x)) == str_replace('emptytext_', '', $_REQUEST["var_id"])) {
                                $y = trim(substr($line, $x + 1, 10000));
                                $y = str_replace('"', '', $y);
                                $line = trim(substr($line, 0, $x)) . ' = "' . $_REQUEST["var_value"] . '"' . "\n";
                                $returnVal = $_REQUEST["var_value"];
                            }
                        }
                    }
                    if (fwrite($handle, $line)) {
                    } else {
                        echo "<b>Could not write to '{$filename}' file</b>";
                    }
                }
                fclose($handle);
                //header('Location: admin_modifylanguage.php');
            } else {
                echo "<b>Could not open '{$filename}' file for writing</b>";
            }
            echo $returnVal;
            die;
        }
        $canContinue = 1;
        $canContinue = isWriteable($canContinue, './languages/lang_' . pligg_language . '.conf', 0777, './languages/lang_' . pligg_language . '.conf');
        if (!$canContinue) {
            echo 'File is not writeable. Please CHMOD /languages/lang_' . pligg_language . '.conf to 777 and refresh this page.<br /><br /><br />';
            die;
        }
        $lines = file('./languages/lang_' . pligg_language . '.conf');
        $section = "x";
        $lastsection = "";
        $tabA = "&nbsp;&nbsp;&nbsp;&nbsp;";
        if (isset($_GET["mode"])) {
            if ($_GET["mode"] == "edit") {
                $outputHtml[] = "<form>";
                $outputHtml[] = "<table class='listing'>";
                $outputHtml[] = "Editing <b>" . sanitize($_GET["edit"], 1) . "</b><br /><br />";
                foreach ($lines as $line_num => $line) {
                    if (substr($line, 0, 2) != "//") {
                        if (strlen(trim($line)) > 2) {
                            $x = strpos($line, "=");
                            if (trim(substr($line, 0, $x)) == $_GET["edit"]) {
                                $y = trim(substr($line, $x + 1, 10000));
                                $y = str_replace('"', "", $y);
                                $outputHtml[] = "Current Value: " . $y . "<br />";
                                $outputHtml[] = '<input type = "hidden" name = "edit" value = "' . $_GET["edit"] . '">';
                                $outputHtml[] = '<input type = "hidden" name = "mode" value = "save">';
                                $outputHtml[] = '<input name = "newvalue" value = "' . $y . '" size=75><br />';
                                $outputHtml[] = '<input type = "submit" name = "save" value = "save" class = "log2">';
                            }
                        }
                    }
                }
            }
            if ($_GET["mode"] == "save") {
                //print_r($_GET);
                //print "New: ".js_urldecode($_GET["newvalue"]);
                $_GET["newvalue"] = js_urldecode($_GET["newvalue"]);
                $outputHtml[] = "saving <b>" . $_GET["edit"] . "</b><br />";
                $filename = './languages/lang_' . pligg_language . '.conf';
                if ($handle = fopen($filename, 'w')) {
                    foreach ($lines as $line_num => $line) {
                        if (substr($line, 0, 2) != "//") {
                            if (strlen(trim($line)) > 2) {
                                $x = strpos($line, "=");
                                if (trim(substr($line, 0, $x)) == $_GET["edit"]) {
                                    $y = trim(substr($line, $x + 1, 10000));
                                    $y = str_replace('"', '', $y);
                                    $line = trim(substr($line, 0, $x)) . ' = "' . addslashes($_GET["newvalue"]) . '"' . "\n";
                                }
                            }
                        }
                        if (fwrite($handle, $line)) {
                        } else {
                            $outputHtml[] = "<b>Could not write to '{$filename}' file</b>";
                        }
                    }
                    fclose($handle);
                    exit;
                    //					header('Location: admin_modifylanguage.php');
                } else {
                    $outputHtml[] = "<b>Could not open '{$filename}' file for writing</b>";
                }
            }
        } else {
            $outputHtml = array();
            $outputHtml[] = '<table id="mytable" class="listing">';
            foreach ($lines as $line_num => $line) {
                if (substr($line, 0, 2) == "//") {
                    $x = strpos($line, "<LANG>");
                    if ($x === false) {
                    } else {
                        $y = strpos($line, "</LANG>");
                        $lang = substr($line, $x + 6, $y);
                    }
                    $x = strpos($line, "<TITLE>");
                    if ($x === false) {
                    } else {
                        $y = strpos($line, "</TITLE>");
                        $outputHtml[] = "<tr><td bgcolor = BFBFBF><b>Title:</b>" . substr($line, $x + 7, $y) . "</td></tr>";
                    }
                    $x = strpos($line, "<SECTION>");
                    if ($x > 0) {
                        $y = strpos($line, '</SECTION>');
                        $section = substr($line, $x + 9, $y - $x);
                        if ($section != $lastsection) {
                            $lastsection = $section;
                            $outputHtml[] = '<tr id="row_ASDFGHJK"><td></td></tr>';
                            $outputHtml[] = '<tr id="row_ASDFGHJK"><td></td></tr>';
                            $outputHtml[] = '<tr id="row_ASDFGHJK"><td></td></tr>';
                            $outputHtml[] = '<tr id="row_ASDFGHJK"><th><b>Section</b>: ' . $section . '</th></tr>';
                        }
                    }
                    $x = strpos($line, "<VERSION>");
                    if ($x === false) {
                    } else {
                        $y = strpos($line, "</VERSION>");
                        $version = substr($line, $x + 9, $y);
                    }
                    $x = strpos($line, "<ADDED>");
                    if ($x === false) {
                    } else {
                        $y = strpos($line, "</ADDED>");
                        $added = substr($line, $x + 7, $y) * 1;
                    }
                } else {
                    if (strlen(trim($line)) > 2) {
                        $x = strpos($line, "=");
                        $outputHtml[] = '<tr id = "row_' . str_replace('"', '', trim(substr($line, $x + 1, 10000))) . '"><td><form onsubmit="return false"><fieldset>';
                        $grey = "grey1";
                        $outputHtml[] = "<b>" . $tabA . trim(substr($line, 0, $x));
                        $outputHtml[] = "</b><br />";
                        $outputHtml[] = "" . $tabA . $tabA;
                        $ID = trim(substr($line, 0, $x));
                        $VALUE = htmlspecialchars(trim(substr(stripslashes($line), $x + 1, 10000), " \t\n\r\"\\'"));
                        //						$VALUE = htmlspecialchars(str_replace('"', '', trim(substr($line, $x + 1, 10000))));
                        if (function_exists("iconv") && detect_encoding($VALUE) != 'utf-8') {
                            $VALUE = iconv('', 'UTF-8//IGNORE', $VALUE);
                        }
                        $outputHtml[] = "Value: <span class=\"emptytext\" id=\"editme{$ID}\" onclick=\"show_edit('{$ID}')\">{$VALUE}</span>";
                        $outputHtml[] = "<span id=\"showme{$ID}\" style=\"display:none;\">";
                        $outputHtml[] = "<input type=\"text\" name=\"var_value\" value=\"{$VALUE}\">";
                        $outputHtml[] = "<br><div style='margin:5px 0 0 75px;'><input type=\"submit\" value=\"Save\" onclick=\"save_changes('{$ID}',this.form)\">";
                        $outputHtml[] = "<input type=\"reset\" value=\"Cancel\" onclick=\"hide_edit('{$ID}')\"></span></div><br>";
                        $outputHtml[] = "</fieldset></form>";
                        $outputHtml[] = "</td></tr>";
                    }
                }
            }
        }
        $outputHtml[] = "</table>";
        $main_smarty->assign('outputHtml', $outputHtml);
        // breadcrumbs
        $navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel');
        $navwhere['link1'] = getmyurl('admin', '');
        $navwhere['text2'] = "Modify Language";
        $navwhere['link2'] = my_pligg_base . "/module.php?module=admin_language";
        $main_smarty->assign('navbar_where', $navwhere);
        $main_smarty->assign('posttitle', " | " . $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel'));
        // breadcrumbs
        //Method for identifying modules rather than pagename
        define('modulename', 'admin_language');
        $main_smarty->assign('modulename', modulename);
        define('pagename', 'admin_modifylanguage');
        $main_smarty->assign('pagename', pagename);
        $main_smarty->assign('editinplace_init', $editinplace_init);
        $main_smarty->assign('tpl_center', admin_language_tpl_path . 'admin_language_main');
        $main_smarty->display($template_dir . '/admin/admin.tpl');
    } else {
        header("Location: " . getmyurl('login', $_SERVER['REQUEST_URI']));
    }
}
	function display_content() {
		
		$file = ProjectFiles::findById(get_id());
		if (!$file instanceof ProjectFile) {
			die(lang("file dnx"));
		}
		if (!$file->canView(logged_user())) {
			die(lang("no access permissions"));
		}
		
		if (defined('SANDBOX_URL')) {
			$html_content = $file->getFileContentWithRealUrls();
		} else {
			$html_content = purify_html($file->getFileContentWithRealUrls());
		}
		$charset = "";
		if ($file->getTypeString() == "text/html") {
			$encoding = detect_encoding($html_content, array('UTF-8', 'ISO-8859-1', 'WINDOWS-1252'));
			$charset = ";charset=".$encoding;
		}
		
		if ($file->getTypeString() == 'text/html') {
			// Include stylesheet from FCK Editor
			$css = '<style type="text/css">';
			$css .= file_get_contents(ROOT.'/public/assets/javascript/ckeditor/contents.css');
			$css .= '</style>';
			$html_content = $css.$html_content;
		}
		
		header("Expires: " . gmdate("D, d M Y H:i:s", mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y"))) . " GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Content-Type: " . $file->getTypeString() . $charset);
		header("Content-Length: " . (string) strlen($html_content));

		print($html_content);
		die();
	}
 function SaveMail(&$content, MailAccount $account, $uidl, $state = 0, $imap_folder_name = '')
 {
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("UID: {$uidl}");
     }
     if (!mysql_ping(DB::connection()->getLink())) {
         DB::connection()->reconnect();
         Logger::log("*** Connection Lost -> Reconnected ***");
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  1) " . format_filesize(memory_get_usage()));
     }
     if (strpos($content, '+OK ') > 0) {
         $content = substr($content, strpos($content, '+OK '));
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  2) " . format_filesize(memory_get_usage()));
     }
     self::parseMail($content, $decoded, $parsedMail, $warnings);
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  3) " . format_filesize(memory_get_usage()));
     }
     $encoding = array_var($parsedMail, 'Encoding', 'UTF-8');
     $enc_conv = EncodingConverter::instance();
     $to_addresses = self::getAddresses(array_var($parsedMail, "To"));
     $from = self::getAddresses(array_var($parsedMail, "From"));
     $message_id = self::getHeaderValueFromContent($content, "Message-ID");
     $in_reply_to_id = self::getHeaderValueFromContent($content, "In-Reply-To");
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  4) " . format_filesize(memory_get_usage()));
     }
     $uid = trim($uidl);
     if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) {
         $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding);
     }
     if ($uid == '') {
         $uid = trim($message_id);
         if ($uid == '') {
             $uid = array_var($parsedMail, 'Subject', 'MISSING UID');
         }
         if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) {
             $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding);
         }
         if (MailContents::mailRecordExists($account->getId(), $uid, $imap_folder_name == '' ? null : $imap_folder_name)) {
             return;
         }
     }
     if (!$from) {
         $parsedMail["From"] = self::getFromAddressFromContent($content);
         $from = array_var($parsedMail["From"][0], 'address', '');
         if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
             Logger::log("mem  4.1) " . format_filesize(memory_get_usage()));
         }
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  5) " . format_filesize(memory_get_usage()));
     }
     if (defined('EMAIL_MESSAGEID_CONTROL') && EMAIL_MESSAGEID_CONTROL) {
         if (trim($message_id) != "") {
             $id_condition = " AND `message_id`='" . trim($message_id) . "'";
         } else {
             $id_condition = " AND `subject`='" . trim(array_var($parsedMail, 'Subject')) . "' AND `from`='{$from}'";
             if (array_var($parsedMail, 'Date')) {
                 $sent_date_dt = new DateTimeValue(strtotime(array_var($parsedMail, 'Date')));
                 $sent_date_str = $sent_date_dt->toMySQL();
                 $id_condition .= " AND `sent_date`='" . $sent_date_str . "'";
             }
         }
         $same = MailContents::findOne(array('conditions' => "`account_id`=" . $account->getId() . $id_condition, 'include_trashed' => true));
         if ($same instanceof MailContent) {
             return;
         }
     }
     if ($state == 0) {
         if ($from == $account->getEmailAddress()) {
             if (strpos($to_addresses, $from) !== FALSE) {
                 $state = 5;
             } else {
                 $state = 1;
             }
             //Show only in sent folder
         }
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  6) " . format_filesize(memory_get_usage()));
         self::log_connection_status();
     }
     $from_spam_junk_folder = strpos(strtolower($imap_folder_name), 'spam') !== FALSE || strpos(strtolower($imap_folder_name), 'junk') !== FALSE || strpos(strtolower($imap_folder_name), 'trash') !== FALSE;
     $user_id = logged_user() instanceof User ? logged_user()->getId() : $account->getUserId();
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
     }
     $max_spam_level = user_config_option('max_spam_level', null, $user_id);
     if ($max_spam_level < 0) {
         $max_spam_level = 0;
     }
     $mail_spam_level = strlen(trim(array_var($decoded[0]['Headers'], 'x-spam-level:', '')));
     // if max_spam_level >= 10 then nothing goes to junk folder
     $spam_in_subject = false;
     if (config_option('check_spam_in_subject')) {
         $spam_in_subject = strpos_utf(strtoupper(array_var($parsedMail, 'Subject')), "**SPAM**") !== false;
     }
     if ($max_spam_level < 10 && ($mail_spam_level > $max_spam_level || $from_spam_junk_folder) || $spam_in_subject) {
         $state = 4;
         // send to Junk folder
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  7) " . format_filesize(memory_get_usage()));
         self::log_connection_status();
     }
     if (!isset($parsedMail['Subject'])) {
         $parsedMail['Subject'] = '';
     }
     $mail = new MailContent();
     $mail->setAccountId($account->getId());
     $mail->setState($state);
     $mail->setImapFolderName($imap_folder_name);
     $mail->setFrom($from);
     $cc = trim(self::getAddresses(array_var($parsedMail, "Cc")));
     if ($cc == '' && array_var($decoded, 0) && array_var($decoded[0], 'Headers')) {
         $cc = array_var($decoded[0]['Headers'], 'cc:', '');
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("mem  8) " . format_filesize(memory_get_usage()));
     }
     $mail->setCc($cc);
     $from_name = trim(array_var(array_var(array_var($parsedMail, 'From'), 0), 'name'));
     $from_encoding = detect_encoding($from_name);
     if ($from_name == '') {
         $from_name = $from;
     } else {
         if (strtoupper($encoding) == 'KOI8-R' || strtoupper($encoding) == 'CP866' || $from_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($from_name)) {
             //KOI8-R and CP866 are Russian encodings which PHP does not detect
             $utf8_from = $enc_conv->convert($encoding, 'UTF-8', $from_name);
             if ($enc_conv->hasError()) {
                 $utf8_from = utf8_encode($from_name);
             }
             $utf8_from = utf8_safe($utf8_from);
             $mail->setFromName($utf8_from);
         } else {
             $mail->setFromName($from_name);
         }
     }
     $subject_aux = $parsedMail['Subject'];
     $subject_encoding = detect_encoding($subject_aux);
     if (strtoupper($encoding) == 'KOI8-R' || strtoupper($encoding) == 'CP866' || $subject_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($subject_aux)) {
         //KOI8-R and CP866 are Russian encodings which PHP does not detect
         $utf8_subject = $enc_conv->convert($encoding, 'UTF-8', $subject_aux);
         if ($enc_conv->hasError()) {
             $utf8_subject = utf8_encode($subject_aux);
         }
         $utf8_subject = utf8_safe($utf8_subject);
         $mail->setSubject($utf8_subject);
     } else {
         $utf8_subject = utf8_safe($subject_aux);
         $mail->setSubject($utf8_subject);
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("mem  9) " . format_filesize(memory_get_usage()));
     }
     $mail->setTo($to_addresses);
     $sent_timestamp = false;
     if (array_key_exists("Date", $parsedMail)) {
         $sent_timestamp = strtotime($parsedMail["Date"]);
     }
     if ($sent_timestamp === false || $sent_timestamp === -1 || $sent_timestamp === 0) {
         $mail->setSentDate(DateTimeValueLib::now());
     } else {
         $mail->setSentDate(new DateTimeValue($sent_timestamp));
     }
     // if this constant is defined, mails older than this date will not be fetched
     if (defined('FIRST_MAIL_DATE')) {
         $first_mail_date = DateTimeValueLib::makeFromString(FIRST_MAIL_DATE);
         if ($mail->getSentDate()->getTimestamp() < $first_mail_date->getTimestamp()) {
             // return true to stop getting older mails from the server
             return true;
         }
     }
     $received_timestamp = false;
     if (array_key_exists("Received", $parsedMail) && $parsedMail["Received"]) {
         $received_timestamp = strtotime($parsedMail["Received"]);
     }
     if ($received_timestamp === false || $received_timestamp === -1 || $received_timestamp === 0) {
         $mail->setReceivedDate($mail->getSentDate());
     } else {
         $mail->setReceivedDate(new DateTimeValue($received_timestamp));
         if ($state == 5 && $mail->getSentDate()->getTimestamp() > $received_timestamp) {
             $mail->setReceivedDate($mail->getSentDate());
         }
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("mem 10) " . format_filesize(memory_get_usage()));
     }
     $mail->setSize(strlen($content));
     $mail->setHasAttachments(!empty($parsedMail["Attachments"]));
     $mail->setCreatedOn(new DateTimeValue(time()));
     $mail->setCreatedById($account->getUserId());
     $mail->setAccountEmail($account->getEmail());
     $mail->setMessageId($message_id);
     $mail->setInReplyToId($in_reply_to_id);
     $mail->setUid($uid);
     $type = array_var($parsedMail, 'Type', 'text');
     switch ($type) {
         case 'html':
             $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', ''));
             if ($enc_conv->hasError()) {
                 $utf8_body = utf8_encode(array_var($parsedMail, 'Data', ''));
             }
             $utf8_body = utf8_safe($utf8_body);
             $mail->setBodyHtml($utf8_body);
             break;
         case 'text':
             $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', ''));
             if ($enc_conv->hasError()) {
                 $utf8_body = utf8_encode(array_var($parsedMail, 'Data', ''));
             }
             $utf8_body = utf8_safe($utf8_body);
             $mail->setBodyPlain($utf8_body);
             break;
         case 'delivery-status':
             $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Response', ''));
             if ($enc_conv->hasError()) {
                 $utf8_body = utf8_encode(array_var($parsedMail, 'Response', ''));
             }
             $utf8_body = utf8_safe($utf8_body);
             $mail->setBodyPlain($utf8_body);
             break;
         default:
             break;
     }
     if (isset($parsedMail['Alternative'])) {
         foreach ($parsedMail['Alternative'] as $alt) {
             if ($alt['Type'] == 'html' || $alt['Type'] == 'text') {
                 $body = $enc_conv->convert(array_var($alt, 'Encoding', 'UTF-8'), 'UTF-8', array_var($alt, 'Data', ''));
                 if ($enc_conv->hasError()) {
                     $body = utf8_encode(array_var($alt, 'Data', ''));
                 }
                 // remove large white spaces
                 $exploded = preg_split("/[\\s]+/", $body, -1, PREG_SPLIT_NO_EMPTY);
                 $body = implode(" ", $exploded);
                 // remove html comments
                 $body = preg_replace('/<!--.*-->/i', '', $body);
             }
             $body = utf8_safe($body);
             if ($alt['Type'] == 'html') {
                 $mail->setBodyHtml($body);
             } else {
                 if ($alt['Type'] == 'text') {
                     $plain = html_to_text(html_entity_decode($utf8_body, null, "UTF-8"));
                     $mail->setBodyPlain($plain);
                 }
             }
             // other alternative parts (like images) are not saved in database.
         }
     }
     $repository_id = self::SaveContentToFilesystem($mail->getUid(), $content);
     $mail->setContentFileId($repository_id);
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("mem 11) " . format_filesize(memory_get_usage()));
     }
     try {
         if ($in_reply_to_id != "") {
             if ($message_id != "") {
                 $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `in_reply_to_id` = '{$message_id}'"));
                 if (!$conv_mail) {
                     $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}'"));
                 } else {
                     // Search for other discontinued conversation part to link it
                     $other_conv_emails = MailContents::findAll(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}' AND `conversation_id`<>" . $conv_mail->getConversationId()));
                 }
             } else {
                 $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}'"));
             }
             if ($conv_mail instanceof MailContent) {
                 // Remove "Re: ", "Fwd: ", etc to compare the subjects
                 $conv_original_subject = strtolower($conv_mail->getSubject());
                 if (($pos = strrpos($conv_original_subject, ":")) !== false) {
                     $conv_original_subject = trim(substr($conv_original_subject, $pos + 1));
                 }
             }
             if ($conv_mail instanceof MailContent && strpos(strtolower($mail->getSubject()), strtolower($conv_original_subject)) !== false) {
                 $mail->setConversationId($conv_mail->getConversationId());
                 if (isset($other_conv_emails) && is_array($other_conv_emails)) {
                     foreach ($other_conv_emails as $ocm) {
                         $ocm->setConversationId($conv_mail->getConversationId());
                         $ocm->save();
                     }
                 }
             } else {
                 $conv_id = MailContents::getNextConversationId($account->getId());
                 $mail->setConversationId($conv_id);
             }
         } else {
             $conv_id = MailContents::getNextConversationId($account->getId());
             $mail->setConversationId($conv_id);
         }
         if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
             self::log_connection_status();
             Logger::log("mem 12) " . format_filesize(memory_get_usage()));
         }
         $mail->save();
         if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
             self::log_connection_status();
             Logger::log("mem 13) " . format_filesize(memory_get_usage()));
         }
         // CLASSIFY RECEIVED MAIL WITH THE CONVERSATION
         if (user_config_option('classify_mail_with_conversation', null, $account->getUserId()) && isset($conv_mail) && $conv_mail instanceof MailContent) {
             $wss = $conv_mail->getWorkspaces();
             foreach ($wss as $ws) {
                 $acc_user = Users::findById($account->getUserId());
                 if ($acc_user instanceof User && $acc_user->hasProjectPermission($ws, ProjectUsers::CAN_READ_MAILS)) {
                     $mail->addToWorkspace($ws);
                 }
             }
         }
         // CLASSIFY MAILS IF THE ACCOUNT HAS A WORKSPACE
         if ($account->getColumnValue('workspace', 0) != 0) {
             $workspace = Projects::findById($account->getColumnValue('workspace', 0));
             if ($workspace && $workspace instanceof Project && !$mail->hasWorkspace($workspace)) {
                 $mail->addToWorkspace($workspace);
             }
         }
         //END CLASSIFY
         $user = Users::findById($account->getUserId());
         if ($user instanceof User) {
             $mail->subscribeUser($user);
         }
     } catch (Exception $e) {
         FileRepository::deleteFile($repository_id);
         if (strpos($e->getMessage(), "Query failed with message 'Got a packet bigger than 'max_allowed_packet' bytes'") === false) {
             throw $e;
         }
     }
     unset($parsedMail);
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem fin) " . format_filesize(memory_get_usage()));
         self::log_connection_status();
     }
     return false;
 }
 function read_csv_file($filename, $delimiter, $only_first_record = false)
 {
     // if encoding=ISO-8859-1 use ut8_encoding function
     $file_content = file_get_contents($filename);
     $file_encoding = detect_encoding($file_content, array('ASCII', 'UTF-8', 'ISO-8859-1'));
     if ($file_encoding == 'ISO-8859-1') {
         $new_filename = ROOT . "/tmp/" . gen_id() . "_utf8.csv";
         $file_content = utf8_encode($file_content);
         file_put_contents($new_filename, $file_content);
         $filename = $new_filename;
     }
     $handle = fopen($filename, 'rb');
     if (!$handle) {
         flash_error(lang('file not exists'));
         ajx_current("empty");
         return;
     }
     if ($only_first_record) {
         $result = fgetcsv($handle, null, $delimiter);
         $aux = array();
         if (function_exists('mb_convert_encoding')) {
             foreach ($result as $title) {
                 $aux[] = mb_convert_encoding($title, "UTF-8", detect_encoding($title));
             }
         } else {
             foreach ($result as $title) {
                 $aux[] = $title;
             }
         }
         $result = $aux;
     } else {
         $result = array();
         while ($fields = fgetcsv($handle, null, $delimiter)) {
             $aux = array();
             if (function_exists('mb_convert_encoding')) {
                 foreach ($fields as $field) {
                     $aux[] = mb_convert_encoding($field, "UTF-8", detect_encoding($field));
                 }
             } else {
                 foreach ($fields as $field) {
                     $aux[] = $field;
                 }
             }
             $result[] = $aux;
         }
     }
     fclose($handle);
     return $result;
 }
	function read_csv_file($filename, $delimiter, $only_first_record = false) {
		
		$handle = fopen($filename, 'rb');
		if (!$handle) {
			flash_error(lang('file not exists'));
			ajx_current("empty");
			return;
		}
		
		if ($only_first_record) {
			$result = fgetcsv($handle, null, $delimiter);
			$aux = array();
			foreach ($result as $title) $aux[] = mb_convert_encoding($title, "UTF-8", detect_encoding($title));
			$result = $aux;			
		} else {
			
			$result = array();
			while ($fields = fgetcsv($handle, null, $delimiter)) {
				$aux = array();
				foreach ($fields as $field) $aux[] = mb_convert_encoding($field, "UTF-8", detect_encoding($field));
				$result[] = $aux;
			}
		}

		fclose($handle);
		return $result;
	} //read_csv_file
Exemple #21
0
 public static function main()
 {
     $AESTool = new AESTool();
     $AESTool->setSecretKey('icevisual');
     $sourceFileName = 'secret.txt';
     $sourceFileContent = file_get_contents($sourceFileName);
     $encoding = detect_encoding($sourceFileContent);
     $encryptedData = $AESTool->encrypt($sourceFileContent);
     $storeFileName = 'secret.ept';
     file_put_contents($storeFileName, $encryptedData);
     $encryptedFileContent = file_get_contents($storeFileName);
     $decryptedData = $AESTool->decrypt($encryptedFileContent);
     //         $content = iconv('ASCII','UTF-8', $content);
     header('Content-type:text/html;charset=' . $encoding);
     echo $decryptedData;
     exit;
 }
Exemple #22
0
function gbk_encoding($fname)
{
    //探测编码
    $encoding1 = detect_encoding($fname);
    var_dump('文件' . $fname . '编码:' . $encoding1);
    if (strcasecmp($encoding1, 'GB2312') == 0) {
        return;
    }
    $encoding2 = 'GB2312';
    //编码转换
    $str = file_get_contents($fname);
    $str = iconv($encoding1, $encoding2, $str);
    file_put_contents($fname, $str);
}
function admin_language_showpage()
{
    global $main_smarty, $the_template;
    include_once 'config.php';
    include_once mnminclude . 'html1.php';
    include_once mnminclude . 'link.php';
    include_once mnminclude . 'tags.php';
    include_once mnminclude . 'smartyvariables.php';
    $main_smarty = do_sidebar($main_smarty);
    force_authentication();
    $canIhaveAccess = 0;
    $canIhaveAccess = $canIhaveAccess + checklevel('admin');
    if ($canIhaveAccess == 1) {
        // Lines from all language files
        $files = new LangFiles();
        // Update a line
        if ($_GET["mode"] == "save") {
            #echo "ankan";
            if ($error = $files->set($_REQUEST['edit'], js_urldecode($_REQUEST['newvalue']), $_REQUEST['file'])) {
                echo "<strong>{$error}</strong>";
            }
            // Display the list of all lines
        } else {
            $lines = array();
            $oldmodule = '';
            // All lines from all files here
            foreach ($files as $lnum => $line) {
                $l = array();
                // Extract filename
                list($file, $pos) = explode('#', $lnum);
                $l['file'] = $file;
                // Add SECTION line for a new module
                if ($files->getName($file) != $oldmodule) {
                    $l['section'] = $oldmodule = $files->getName($file);
                    $lines[] = $l;
                    unset($l['section']);
                }
                // Commented lines (auxiliary info)
                if (substr($line, 0, 2) == "//") {
                    if (preg_match('/<TITLE>(.+)<\\/TITLE>/', $line, $m)) {
                        $l['title'] = $m[1];
                    } elseif (preg_match('/<SECTION>(.+)<\\/SECTION>/', $line, $m)) {
                        $l['section'] = $m[1];
                    } else {
                        continue;
                    }
                } elseif (strlen(trim($line)) > 2) {
                    if (preg_match('/^([^=]+)\\s*=\\s*"?(.+)"?$/', trim($line), $m)) {
                        $l['id'] = trim($m[1]);
                        $l['value'] = htmlspecialchars(str_replace('"', '', trim($m[2])));
                        if (function_exists("iconv") && detect_encoding($l['value']) != 'utf-8') {
                            $l['value'] = iconv('', 'UTF-8//IGNORE', $l['value']);
                        }
                    } else {
                        $l['error'] = "Can't parse {$line}";
                    }
                } else {
                    continue;
                }
                $lines[] = $l;
            }
            $main_smarty->assign('lines', $lines);
            // breadcrumbs
            $navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel');
            $navwhere['link1'] = getmyurl('admin', '');
            $navwhere['text2'] = "Modify Language";
            $navwhere['link2'] = my_pligg_base . "/module.php?module=admin_language";
            $main_smarty->assign('navbar_where', $navwhere);
            $main_smarty->assign('posttitle', " | " . $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel'));
            // breadcrumbs
            //Method for identifying modules rather than pagename
            define('modulename', 'admin_language');
            $main_smarty->assign('modulename', modulename);
            define('pagename', 'admin_modifylanguage');
            $main_smarty->assign('pagename', pagename);
            $main_smarty->assign('editinplace_init', $editinplace_init);
            $main_smarty->assign('tpl_center', admin_language_tpl_path . 'admin_language_main');
            $main_smarty->display($template_dir . '/admin/admin.tpl');
        }
    } else {
        header("Location: " . getmyurl('login', $_SERVER['REQUEST_URI']));
    }
}