顯示具有 php8 標籤的文章。 顯示所有文章
顯示具有 php8 標籤的文章。 顯示所有文章

2024年3月27日 星期三

PHP 開發筆記 - 追蹤 osTicket v1.18.1 在 PHP8 環境處理信件的流程

公司用 osTicket 系統幾年了,最近把環境升級到 PHP8 和最新版 osTicket v1.18.1 後,同事回報踩到信件內容的 cid 圖片沒正常處理,就先追蹤一下信件處理流程,主要先追到 MIMEDecode 即可。

從官網文件 POP3/IMAP Settings Guide 得知,信件處理的觸發有從 crontab 和 api 的管道,目前就從 crontab 來追:

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.6 LTS
Release:        20.04
Codename:       focal

$ php -v
PHP 8.2.17 (cli) (built: Mar 16 2024 08:41:44) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.17, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.17, Copyright (c), by Zend Technologies

$ php api/cron.php

接著開始看 api/cron.php 程式碼,大概追到 include/class.cron.php 時,就可以看到 osTicket\Mail\Fetcher::run(); 和 include/class.email.php 檔案了,從 include/class.mailfetch.php 可以看到:

```php
 78     function processMessage(int $i, array $defaults = []) {
 79         try {
 80             // Please note that the returned object could be anything from
 81             // ticket, task to thread entry or a boolean.
 82             // Don't let TicketApi call fool you!
 83             return $this->getTicketsApi()->processEmail(
 84                     $this->mbox->getRawEmail($i), $defaults);
 85         } catch (\TicketDenied $ex) {
 86             // If a ticket is denied we're going to report it as processed
 87             // so it can be moved out of the Fetch Folder or Deleted based
 88             // on the MailBox settings.
 89             return true;
 90         } catch (\EmailParseError $ex) {
 91             // Upstream we try to create a ticket on email parse error - if
 92             // it fails then that means we have invalid headers.
 93             // For Debug purposes log the parse error + headers as a warning
 94             $this->logWarning(sprintf("%s\n\n%s",
 95                         $ex->getMessage(),
 96                         $this->mbox->getRawHeader($i)));
 97         }
 98         return false;
 99     }
```

接著在 processEmail 前埋一個 @file_put_contents('/tmp/debug-mail', print_r($this->mbox->getRawEmail($i), true)); ,如此處理信件時,原始格式就會被記錄在 /tmp/debug-mail 裡,下一刻就能再重現信件格式的處理流程

小改後面:

$ sudo cp api/cron.php  api/cron-debug.php
$ tail -n 5 api/cron-debug.php 
//LocalCronApiController::call();
//
$obj = new \TicketApiController('cli');
print_r($obj->processEmail(file_get_contents('/tmp/debug-mail'), []));
?>

如此運行時就可以看資訊:

$ php api/cron-debug.php 
Ticket Object
(
    [ht] => Array
        (
            [ticket_id] => #
            [ticket_pid] => 
            [number] => #####
...

接著要來研究信件處理流程,就來到了 include/api.tickets.php 檔案:

```php
    function processEmail($data=false, array $defaults = []) {

        try {
            if (!$data)
                $data = $this->getEmailRequest();
            elseif (!is_array($data))
                $data = $this->parseEmail($data);
            print_r($data);
        } catch (Exception $ex)  {
            throw new EmailParseError($ex->getMessage());
        }
...
```

繼續追 include/class.api.php 檔案:

```php
238     function parseRequest($stream, $format, $validate=true) {
239         $parser = null;
240         switch(strtolower($format)) {
241             case 'xml':
242                 if (!function_exists('xml_parser_create'))
243                     return $this->exerr(501, __('XML extension not supported'));
244                 $parser = new ApiXmlDataParser();
245                 break;
246             case 'json':
247                 $parser = new ApiJsonDataParser();
248                 break;
249             case 'email': 
250                 $parser = new ApiEmailDataParser();
251                 break;
252             default:
253                 return $this->exerr(415, __('Unsupported data format'));
254         }
255         
256         if (!($data = $parser->parse($stream)) || !is_array($data)) {
257             $this->exerr(400, $parser->lastError());
258         }
259         
260         //Validate structure of the request.
261         if ($validate && $data)
262             $this->validate($data, $format, false);
263         
264         return $data;
265     }
266     
267     function parseEmail($content) {
268         return $this->parseRequest($content, 'email', false);
269     }
```

繼續追 include/class.mailparse.php 檔案,主要是追蹤 EmailDataParser -> Mail_Parse -> Mail_mimeDecode ,最後就是 include/pear/Mail/mimeDecode.php 的處理 MIMEDecode 的實作了。

剩下的工作就是研究它解析原始信件的流程,看看是 MIMEDecode 是否少了遞迴解,還是有什麼限制了:

2023年9月20日 星期三

Windows 開發筆記 - 使用 Command Line / CMD / ssh 與 PHP 8.2 / Composer / Git / VIM 開發環境 @ Windows 11

幫同事看了一下 Windows 開發環境,要在此環境使用 PHP8.2 與 PHP Laravel v10 framework,由於之前採用 xampp 管理套件被環境變數卡住。這些問題描述,瞬間拉回到學生時代在那邊設置 Windows %PATH% 環境變數 XD 我也忘了那時在幹嘛?推論是配置 Java 環境吧

目前就把手邊的 Windows 11 筆電拿來遠端,但懶得打開它。並且實際在 command line 測試會碰到幾個問題。

1. 從 https://windows.php.net/download/ 下載 VS16 x64 Non Thread Safe ,並解壓在 C:\php 目錄中,必須在設置 php.ini 。想要知道自己的 php.ini 位置,可以用 php.exe --ini

C:\php>php.exe --ini 
Configuration File (php.ini) Path: 
Loaded Configuration File:         (none)
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

接著把 C:\php\php.ini-development 複製到 C:\php\php.ini 使用:

C:\php>copy php.ini-development php.ini     
複製了         1 個檔案。

後續就編輯 php.ini 開啟一些項目,在此就靠 C:\cygwin64\bin\vim.exe 當編輯器(若碰到滑鼠圈選文字難複製,記得關掉滑鼠模式 :set mouse-=a),主要打開一些 php.ini 註解:

; Directory in which the loadable extensions (modules) reside.
; https://php.net/extension-dir
;extension_dir = "./"
; On windows:
extension_dir = "ext"
; ...
extension=curl
extension=fileinfo
extension=gd
extension=intl
extension=mbstring
extension=exif
extension=mysqli
extension=openssl
extension=sqlite3

C:\php>php.exe --ini 
Configuration File (php.ini) Path: 
Loaded Configuration File:         C:\php\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

2. 下載 composer 後,預設會失敗:

C:\php>php.exe composer.phar self-update

In Factory.php line 648:
                                                                                                                          The openssl extension is required for SSL/TLS protection but is not available. If you can not enable the openssl extension, you can   
   disable this error, at your own risk, by setting the 'disable-tls' option to true.                          

self-update [-r|--rollback] [--clean-backups] [--no-progress] [--update-keys] [--stable] [--preview] [--snapshot] [--1] [--2] [--2.2] [--set-channel-only] [--] [<version>]

設置後:

C:\php>php.exe composer.phar self-update 
You are already using the latest available Composer version 2.6.3 (stable channel).

3. 在管理專案時,透過 C:\php\php.exe composer.phar install 時,會需要 GIT 指令,解法就是去官方安裝一下,安裝完的目錄位置在 C:\Program Files\Git 位置

C:\>"C:\Program Files\Git\bin\git.exe" --version
git version 2.42.0.windows.2

4. 回過頭來,更新環境變數 %PATH% 

C:\>git
'git' 不是內部或外部命令、可執行的程式或批次檔。
C:\>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Docker\Docker\resources\bin;C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps;C:\Users\user\AppData\Local\Microsoft\WindowsApps;
C:\>set PATH=%PATH%;C:\Program Files\Git\bin\
C:\>git --version
git version 2.42.0.windows.2

如此在 Windows 的 command line (PowerShell) 環境下,也可以靠純指令做一點事了