將 ldapsearch 輸出內容 (LDIF) 轉 UTF-8 編碼

雖然在 ldapadd 匯入 LDIF 格式檔時,已經將檔案內容轉換 UTF-8 格式,可常匯入了,但是在 ldapsearch 搜尋資料時,看到的卻是亂碼
cn 的部分應該是正常的中文字,但現在顯示的卻是亂碼
# /usr/bin/ldapsearch -x -b “ou=Teacher,dc=ldap,dc=tces.ilc.edu.tw” uid=*
# extended LDIF
#
# LDAPv3
# base <ou=Teacher,dc=ldap,dc=tces.ilc.edu.tw> with scope subtree
# filter: uid=*
# requesting: ALL
#

# t850008, Teacher, ldap.tces.ilc.edu.tw
dn: uid=t850008,ou=Teacher,dc=ldap,dc=tces.ilc.edu.tw
uid: t850008
cn:: 5p6X5pit5ZCN
objectClass: account
objectClass: posixAccount
objectClass: top
userPassword:: e2
loginShell: /bin/bash
uidNumber: 953
gidNumber: 500
homeDirectory: /home/t850008

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries: 1 [@more@]底下的內容參考 PHP 程式: ldapsearch 輸出內容 (LDIF) 轉 UTF-8 編碼 « Jamyy’s Weblog
# 建立 php 的轉換檔
# vim /root/utf8ldif.php

<?php

function fn_output($str) {
if (strpos($str,":: ") > 0) {
//解 Base64 編碼
//當 ldap 欄位名稱後面接的是兩個冒號即表示該欄位內容為 Base64 編碼
$head = substr($str,0,strpos($str," ")-1);
$body = substr($str,strpos($str," ")+1);
$str = $head . " " . base64_decode($body) . "n";
} else if (preg_match('/x5c[A-F0-9][A-F0-9]x5c[A-F0-9][A-F0-9]/',$str)) {
//解 URL 編碼
//URL 編碼出現在註解 (#), ldapsearch -LLL 可取消輸出註解內容
$str = urldecode(str_replace("","%",$str));
}
if (!preg_match('/n$/',$str)) {
//如果處理過後的字串沒有換行符號 (n) 就塞一個給他
$str .= "n";
}
return($str);
}

$line_old = "";
$line_merge = "";
$params = count($argv);
if ($params == 1) {
//未給參數時, 開啟 STDIN 串流
$f = fopen("php://stdin","r");
} else {
//開啟指定檔案
$f = fopen("$argv[1]","r");
}
while (!feof($f)) {
$line = fgets($f);
if (substr($line,0,1) == " ") {
//若該行行首為空白字元, 表示因內容過長而斷行
//以 line_merge 變數合併各段落
if ($line_merge == "") {
$line_merge = trim($line_old) . trim($line);
} else {
$line_merge .= trim($line);
}
} else if ($line_merge > "") {
//輸出合併好的內容
echo fn_output($line_merge);
$line_merge = "";
} else {
//輸出一般內容
echo fn_output($line_old);
}
$line_old = $line;
}
fclose($f);
?>

使用方式
# /usr/bin/ldapsearch -x -b “ou=Teacher,dc=ldap,dc=tces.ilc.edu.tw” uid=* | php /root/utf8ldif.php

# extended LDIF
#
# LDAPv3
# base <ou=Teacher,dc=ldap,dc=tces.ilc.edu.tw> with scope subtree
# filter: uid=*
# requesting: ALL
#

# t850008, Teacher, ldap.tces.ilc.edu.tw
dn: uid=t850008,ou=Teacher,dc=ldap,dc=tces.ilc.edu.tw
uid: t850008
cn: 林昭名
objectClass: account
objectClass: posixAccount
objectClass: top
userPassword:: e2
loginShell: /bin/bash
uidNumber: 953
gidNumber: 500
homeDirectory: /home/t850008

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries:

中文字的部分就可以正常顯示了!