OSDN Git Service

初回コミット(v2.6.17.1)
[magic3/magic3.git] / widgets / admin_main / include / container / admin_mainTemplistWidgetContainer.php
1 <?php
2 /**
3  * コンテナクラス
4  *
5  * PHP versions 5
6  *
7  * LICENSE: This source file is licensed under the terms of the GNU General Public License.
8  *
9  * @package    Magic3 Framework
10  * @author     平田直毅(Naoki Hirata) <naoki@aplo.co.jp>
11  * @copyright  Copyright 2006-2012 Magic3 Project.
12  * @license    http://www.gnu.org/copyleft/gpl.html  GPL License
13  * @version    SVN: $Id: admin_mainTemplistWidgetContainer.php 5499 2012-12-31 10:37:44Z fishbone $
14  * @link       http://www.magic3.org
15  */
16 require_once($gEnvManager->getCurrentWidgetContainerPath() .    '/admin_mainBaseWidgetContainer.php');
17 require_once($gEnvManager->getCurrentWidgetDbPath() . '/admin_mainDb.php');
18 require_once($gEnvManager->getLibPath()                         . '/pcl/pclzip.lib.php' );
19 require_once($gEnvManager->getCurrentWidgetContainerPath()              . '/admin_mainDef.php');                        // 定義クラス
20 require_once($gEnvManager->getCommonPath()              . '/archive.php');
21 // Joomlaテンプレート用
22 require_once($gEnvManager->getJoomlaRootPath() . '/JParameter.php');
23 require_once($gEnvManager->getJoomlaRootPath() . '/JRender.php');
24                                 
25 class admin_mainTemplistWidgetContainer extends admin_mainBaseWidgetContainer
26 {
27         private $db;    // DB接続オブジェクト
28         private $sysDb;         // システムDBオブジェクト
29         private $newTemplate = array();         // 新規追加テンプレート
30         private $defalutTemplate;       // デフォルトのテンプレート
31         private $templateTypeArray;             // テンプレートタイプ
32         private $templateType;                  // 現在のテンプレートタイプ
33         private $showDetail;                    // 詳細表示するかどうか
34         private $isExistsTemplateList;          // テンプレートが存在するかどうか
35         const TEMPLATE_THUMBNAIL_FILENAME = 'template_thumbnail.png';           // テンプレートサムネール
36         const previewImageSizeHeight = 27;
37         const previewImageSizeWidth = 42;
38         const imageSizeHeight = 135;
39         const imageSizeWidth = 210;
40         const JOOMLA_CONFIG_FILENAME = 'templateDetails.xml';           // Joomla!のテンプレート設定ファイル名
41         const NOT_FOUND_TEMPLATE_ICON_FILE = '/images/system/notfound32.png';           // テンプレートが見つからないアイコン
42                 
43         /**
44          * コンストラクタ
45          */
46         function __construct()
47         {
48                 // 親クラスを呼び出す
49                 parent::__construct();
50                 
51                 // DB接続オブジェクト作成
52                 $this->db = new admin_mainDb();
53                 $this->sysDb = $this->gInstance->getSytemDbObject();
54                 
55                 // テンプレートタイプメニュー項目
56                 $this->templateTypeArray = array(       array(  'name' => $this->_('For PC'),                   'value' => '0'),                // PC用
57                                                                                         array(  'name' => $this->_('For Mobile'),               'value' => '1'),                // 携帯用
58                                                                                         array(  'name' => $this->_('For Smartphone'),   'value' => '2'));               // スマートフォン用
59         }
60         /**
61          * テンプレートファイルを設定
62          *
63          * _assign()でデータを埋め込むテンプレートファイルのファイル名を返す。
64          * 読み込むディレクトリは、「自ウィジェットディレクトリ/include/template」に固定。
65          *
66          * @param RequestManager $request               HTTPリクエスト処理クラス
67          * @param object         $param                 任意使用パラメータ。そのまま_assign()に渡る
68          * @return string                                               テンプレートファイル名。テンプレートライブラリを使用しない場合は空文字列「''」を返す。
69          */
70         function _setTemplate($request, &$param)
71         {       
72                 return 'templist.tmpl.html';
73         }
74         /**
75          * ヘルプデータを設定
76          *
77          * ヘルプの設定を行う場合はヘルプIDを返す。
78          * ヘルプデータの読み込むディレクトリは「自ウィジェットディレクトリ/include/help」に固定。
79          *
80          * @param RequestManager $request               HTTPリクエスト処理クラス
81          * @param object         $param                 任意使用パラメータ。そのまま_assign()に渡る
82          * @return string                                               ヘルプID。ヘルプデータはファイル名「help_[ヘルプID].php」で作成。ヘルプを使用しない場合は空文字列「''」を返す。
83          */
84         function _setHelp($request, &$param)
85         {       
86                 return 'templist';
87         }
88         /**
89          * テンプレートにデータ埋め込む
90          *
91          * _setTemplate()で指定したテンプレートファイルにデータを埋め込む。
92          *
93          * @param RequestManager $request               HTTPリクエスト処理クラス
94          * @param object         $param                 任意使用パラメータ。_setTemplate()と共有。
95          * @param                                                               なし
96          */
97         function _assign($request, &$param)
98         {
99                 $act = $request->trimValueOf('act');
100                 $selectedItemNo = $request->trimValueOf('no');          // 処理対象の項目番号
101                 $userId = $this->gEnv->getCurrentUserId();
102                 $templateId = $request->trimValueOf('template');                // テンプレートID
103                 $this->templateType = $request->trimValueOf('item_type');// 現在のテンプレートタイプ
104                 if ($this->templateType == '') $this->templateType = '0';               // デフォルトはPC用テンプレート
105                 $this->showDetail = ($request->trimValueOf('item_show_detail') == 'on') ? 1 : 0;                // 詳細表示するかどうか
106                 
107                 if ($act == 'readnew'){         // テンプレート再読み込みのとき
108                         $addTemplateCount = 0;
109                         // テンプレート一覧取得
110                         if ($this->db->getAllTemplateIdList($rows)){
111                                 // テンプレートディレクトリチェック
112                                 switch ($this->templateType){
113                                         case '0':               // PC用テンプレート
114                                         default:
115                                                 $searchPath = $this->gEnv->getTemplatesPath();
116                                                 break;
117                                         case '1':               // 携帯用テンプレート
118                                                 $searchPath = $this->gEnv->getTemplatesPath() . '/' . M3_DIR_NAME_MOBILE;
119                                                 break;
120                                         case '2':               // スマートフォン用テンプレート
121                                                 $searchPath = $this->gEnv->getTemplatesPath() . '/' . M3_DIR_NAME_SMARTPHONE;
122                                                 break;
123                                 }
124                                 
125                                 if (is_dir($searchPath)){
126                                         $dir = dir($searchPath);
127                                         while (($file = $dir->read()) !== false){
128                                                 $filePath = $searchPath . '/' . $file;
129                                                 // ディレクトリかどうかチェック
130                                                 if (strncmp($file, '.', 1) != 0 && $file != '..' && is_dir($filePath) &&
131                                                         strncmp($file, '_', 1) != 0     &&      // 「_」で始まる名前のディレクトリは読み込まない
132                                                         strlen($file) > 1 &&                    // 携帯、スマートフォン用ディレクトリ「m」「s」は読み込まない
133                                                         !($this->templateType == 0 && $file == 'system')){                              // PC用Joomla!デフォルトテンプレート「system」は読み込まない
134                                                         
135                                                         // テンプレートIDを作成
136                                                         switch ($this->templateType){
137                                                                 case '0':               // PC用テンプレート
138                                                                 default:
139                                                                         $templateId = $file;
140                                                                         break;
141                                                                 case '1':               // 携帯用テンプレート
142                                                                         $templateId = M3_DIR_NAME_MOBILE . '/' . $file;
143                                                                         break;
144                                                                 case '2':               // スマートフォン用テンプレート
145                                                                         $templateId = M3_DIR_NAME_SMARTPHONE . '/' . $file;
146                                                                         break;
147                                                         }
148                                 
149                                                         // DBに登録されていない場合は登録
150                                                         for ($i = 0; $i < count($rows); $i++){
151                                                                 if ($templateId == $rows[$i]['tm_id']) break;
152                                                         }
153                                                         if ($i == count($rows)){
154                                                                 // テンプレートを新規登録
155                                                                 $ret = $this->addNewTemplate(intval($this->templateType), $templateId);
156                                                                 if ($ret){
157                                                                         $this->newTemplate[] = $templateId;
158                                                                         $addTemplateCount++;            // テンプレート追加
159                                                                 }
160                                                         }
161                                                 }
162                                         }
163                                         $dir->close();
164                                 }
165                         } else {
166                         }
167                         // 終了メッセージを表示
168                         if ($addTemplateCount > 0){
169                                 //$msg = '新規テンプレートを追加しました(追加数=' . $addTemplateCount . ')';
170                                 $msg = sprintf($this->_('New templates added. (templates count=%d)'), $addTemplateCount);                       // 新規テンプレートを追加しました(追加数=%d)
171                         } else {
172                                 //$msg = '新規テンプレートはありません';
173                                 $msg = $this->_('No new templates added.');             // 新規テンプレートはありません
174                         }
175                         $this->setMsg(self::MSG_GUIDANCE, $msg);
176                 } else if ($act == 'updateline'){               // 行更新のとき
177                         // パラメータエラーチェック
178                         if (empty($templateId)) $this->setMsg(self::MSG_APP_ERR, $this->_('Template not selected.'));           // テンプレートが選択されていません
179                         
180                         if (!$this->isExistsMsg()){             // エラーなしのとき
181                                 // 変更可能値
182                                 $updateName = $request->trimValueOf('item' . $selectedItemNo . '_name');                                // 名前
183                                 $updateIsDefault = ($request->trimValueOf('item' . $selectedItemNo . '_isdefault') == 'on') ? 1 : 0;            // デフォルトかどうか
184                                 $ret = $this->db->updateTemplate($templateId, $updateName);
185                                 if ($ret){              // データ更新成功のとき
186                                         //$this->setMsg(self::MSG_GUIDANCE, 'データを更新しました(テンプレートID:' . $templateId . ')');
187                                         $this->setMsg(self::MSG_GUIDANCE, sprintf($this->_('Line updated. (template ID: %s)'), $templateId));   // データを更新しました(テンプレートID:%s)
188                                 } else {
189                                         //$this->setMsg(self::MSG_APP_ERR, 'データ更新に失敗しました(テンプレートID:' . $templateId . ')');
190                                         $this->setMsg(self::MSG_APP_ERR, sprintf($this->_('Failed in updating line. (template ID: %s)'), $templateId)); // データ更新に失敗しました(テンプレートID:%s)
191                                 }
192                         }
193                 } else if ($act == 'deleteline'){               // テンプレート削除のとき
194                         // パラメータエラーチェック
195                         if (empty($templateId)) $this->setMsg(self::MSG_APP_ERR, $this->_('Template not selected.'));           // テンプレートが選択されていません
196                         
197                         if (!$this->isExistsMsg()){             // エラーなしのとき
198                                 // テンプレートディレクトリ取得
199                                 $templatePath = $this->gEnv->getTemplatesPath() . '/' . $templateId;
200                 
201                                 // ディレクトリ削除
202                                 if ((is_dir($templatePath) && rmDirectory($templatePath)) || !is_dir($templatePath)){// 削除成功か、ディレクトリが存在しないとき
203                                         $ret = $this->db->deleteTemplate($templateId);
204                                         if ($ret){              // データ更新成功のとき
205                                                 //$this->setMsg(self::MSG_GUIDANCE, 'テンプレートを削除しました(テンプレートID:' . $templateId . ')');
206                                                 $this->setMsg(self::MSG_GUIDANCE, sprintf($this->_('Template deleted. (template ID: %s)'), $templateId));       // テンプレートを削除しました(テンプレートID:%s)
207                                         } else {
208                                                 //$this->setMsg(self::MSG_APP_ERR, 'テンプレート削除に失敗しました(テンプレートID:' . $templateId . ')');
209                                                 $this->setMsg(self::MSG_APP_ERR, sprintf($this->_('Failed in deleting template. (template ID: %s)'), $templateId));     // テンプレート削除に失敗しました(テンプレートID:%s)
210                                         }
211                                 } else {
212                                         //$this->setMsg(self::MSG_APP_ERR, 'テンプレートのディレクトリが削除できませんでした(テンプレートID:' . $templateId . ')');
213                                         $this->setMsg(self::MSG_APP_ERR, sprintf($this->_('Failed in deleting template directory. (directory: %s)'), $templatePath));   // テンプレートのディレクトリが削除できませんでした(ディレクトリ:%s)
214                                 }
215                         }
216                 } else if ($act == 'upload'){           // ファイルアップロードの場合
217                         // アップロードされたファイルか?セキュリティチェックする
218                         if (is_uploaded_file($_FILES['upfile']['tmp_name'])){
219                                 $uploadFilename = $_FILES['upfile']['name'];            // アップロードされたファイルのファイル名取得
220
221                                 // ファイル名の解析
222                                 $pathParts = pathinfo($uploadFilename);
223                                 $ext = $pathParts['extension'];         // 拡張子
224                                 $templateName = basename($uploadFilename, '.' . $ext);          // 拡張子をはずす
225                                 $ext = strtolower($ext);
226                                 
227                                 // ファイル拡張子のチェック
228                                 if ($ext != 'zip'){
229                                         //$msg = 'zip圧縮のファイルのみアップロード可能です';
230                                         $msg = $this->_('Only zip format file is allowed to upload.');  // zip圧縮のファイルのみアップロード可能です
231                                         $this->setAppErrorMsg($msg);
232                                 }
233                                 
234                                 // テンポラリディレクトリの書き込み権限をチェック
235                                 if (!is_writable($this->gEnv->getWorkDirPath())){
236                                         //$msg = '一時ディレクトリに書き込み権限がありません。ディレクトリ:' . $this->gEnv->getWorkDirPath();
237                                         $msg = sprintf($this->_('You are not allowed to write temporary directory. (directory: %s)'), $this->gEnv->getWorkDirPath());   // 一時ディレクトリに書き込み権限がありません。(ディレクトリ:%s)
238                                         $this->setAppErrorMsg($msg);
239                                 }
240                                 
241                                 if ($this->getMsgCount() == 0){         // エラーが発生していないとき
242                                         // ファイルを保存するサーバディレクトリを指定
243                                         $tmpFile = tempnam($this->gEnv->getWorkDirPath(), M3_SYSTEM_WORK_UPLOAD_FILENAME_HEAD);
244                 
245                                         // アップされたテンポラリファイルを保存ディレクトリにコピー
246                                         $ret = move_uploaded_file($_FILES['upfile']['tmp_name'], $tmpFile);
247                                         if ($ret){
248                                                 // 解凍先ディレクトリ取得
249                                                 $extDir = $this->gEnv->getTempDir();
250                                                 
251                                                 // ファイルを解凍
252                                                 $archiver = new Archive();
253                                                 $ret = $archiver->extract($tmpFile, $extDir, $ext);
254                                                 if ($ret){
255                                                         // 作成されたファイルを取得
256                                                         $fileList = getFileList($extDir);
257                                                         if (count($fileList) == 1 && is_dir($extDir . '/' . $fileList[0])){             // 単一ディレクトリのとき
258                                                                 $srcTemplateDir = $extDir . '/' . $fileList[0];
259                                                         } else {
260                                                                 // 設定ファイルを取得
261                                                                 $srcTemplateDir = $extDir;
262                                                         }
263                                                         // テンプレートIDを求める
264                                                         $templateId = $this->getTemplateId($srcTemplateDir);
265                                                         
266                                                         // テンプレートIDが取得できないときは、送信されたファイルのファイル名を使用
267                                                         if (empty($templateId)) $templateId = $templateName;
268                                                         
269                                                         // テンプレートIDを修正
270                                                         switch ($this->templateType){
271                                                                 case '0':               // PC用テンプレート
272                                                                 default:
273                                                                         break;
274                                                                 case '1':               // 携帯用テンプレート
275                                                                         $templateId = M3_DIR_NAME_MOBILE . '/' . $templateId;
276                                                                         break;
277                                                                 case '2':               // スマートフォン用テンプレート
278                                                                         $templateId = M3_DIR_NAME_SMARTPHONE . '/' . $templateId;
279                                                                         break;
280                                                         }
281                                                         
282                                                         // 同IDのテンプレートがないかチェック
283                                                         if ($this->db->getAllTemplateIdList($rows)){
284                                                                 for ($i = 0; $i < count($rows); $i++){
285                                                                         if ($templateId == $rows[$i]['tm_id']) break;
286                                                                 }
287                                                                 if ($i < count($rows)){
288                                                                         //$msg = '同じIDのテンプレートがすでに存在します(テンプレートID:' . $templateId . ')';
289                                                                         $msg = sprintf($this->_('The template already exists. (template ID: %s)'), $templateId);                // テンプレートがすでに存在します(テンプレートID:%s)
290                                                                         $this->setAppErrorMsg($msg);
291                                                                 }
292                                                         }
293                                                         
294                                                         if ($this->getMsgCount() == 0){         // エラーが発生していないとき
295                                                                 // 既にディレクトリがないかチェック
296                                                                 $destTemplateDir = $this->gEnv->getTemplatesPath() . '/' . $templateId;                 // テンプレートの移動先
297                                                                 if (file_exists($destTemplateDir)){
298                                                                         //$msg = '同じIDのテンプレートディレクトリがすでに存在します(テンプレートID:' . $templateId . ')';
299                                                                         $msg = sprintf($this->_('The template directory already exists. (directory: %s)'), $destTemplateDir);// テンプレートディレクトリがすでに存在します(ディレクトリ:%s)
300                                                                         $this->setAppErrorMsg($msg);
301                                                                 } else {
302                                                                         // ディレクトリを移動
303                                                                         $ret = @rename($srcTemplateDir, $destTemplateDir);
304                                                                         if (!$ret) $ret = mvDirectory($srcTemplateDir, $destTemplateDir);               // 2009/7/17 異なるデバイス間でrenameできなかった問題に対応
305                                                                         if ($ret){
306                                                                                 // テンプレートを新規登録
307                                                                                 $ret = $this->addNewTemplate(intval($this->templateType), $templateId);
308                                                         
309                                                                                 //$msg = 'ファイルのアップロードが完了しました(テンプレートID:' . $templateId . ')';
310                                                                                 $msg = sprintf($this->_('File uploaded. (template ID: %s)'), $templateId);              // ファイルのアップロードが完了しました(テンプレートID: %s)
311                                                                                 $this->setGuidanceMsg($msg);
312                                                                                 $this->newTemplate[] = $templateId;
313                                                                         } else {
314                                                                                 //$msg = 'ディレクトリの移動に失敗しました(ディレクトリ:' . $destTemplateDir . ')';
315                                                                                 $msg = sprintf($this->_('Failed in moving directory. (directory: %s)'), $destTemplateDir);// ディレクトリの移動に失敗しました(ディレクトリ:%s)
316                                                                                 $this->setAppErrorMsg($msg);
317                                                                         }
318                                                                 }
319                                                         }
320                                                 }
321                                                 // 解凍用ディレクトリを削除
322                                                 if (file_exists($extDir)) rmDirectory($extDir);
323                                         } else {
324                                                 //$msg = 'ファイルのアップロードに失敗しました';
325                                                 $msg = $this->_('Failed in uploading file.');           // ファイルのアップロードに失敗しました
326                                                 $this->setAppErrorMsg($msg);
327                                         }
328                                         // テンポラリファイル削除
329                                         unlink($tmpFile);
330                                 }
331                         } else {
332                                 //$msg = 'アップロードファイルが見つかりません(要因:アップロード可能なファイルのMaxサイズを超えている可能性があります - ' . $this->gSystem->getMaxFileSizeForUpload() . 'バイト)';
333                                 $msg = sprintf($this->_('Uploded file not found. (detail: The file may be over maximum size to be allowed to upload. Size %s bytes.'), $this->gSystem->getMaxFileSizeForUpload());      // アップロードファイルが見つかりません(要因:アップロード可能なファイルのMaxサイズを超えている可能性があります。%sバイト)
334                                 $this->setAppErrorMsg($msg);
335                         }
336                 } else if ($act == 'download'){         // ファイルダウンロードのとき
337                         switch ($this->templateType){
338                                 case '0':               // PC用テンプレート
339                                 default:
340                                         $templatesDir = $this->gEnv->getTemplatesPath();                // テンプレートディレクトリ
341                                         $templateDir = $templatesDir . '/' . $templateId;                       // ダウンロードするテンプレートのディレクトリ
342                                         $downloadFilename = $templateId . '.zip';               // ダウンロード時のファイル名
343                                         break;
344                                 case '1':               // 携帯用テンプレート
345                                         $templatesDir = $this->gEnv->getTemplatesPath() . '/' . M3_DIR_NAME_MOBILE;             // テンプレートディレクトリ
346                                         $templateDir = $this->gEnv->getTemplatesPath() . '/' . $templateId;                     // ダウンロードするテンプレートのディレクトリ
347                                         list($dir, $filename) = explode('/', $templateId);      // 先頭の「m/」を削除
348                                         $downloadFilename = $filename . '.zip';         // ダウンロード時のファイル名
349                                         break;
350                                 case '2':               // スマートフォン用テンプレート
351                                         $templatesDir = $this->gEnv->getTemplatesPath() . '/' . M3_DIR_NAME_SMARTPHONE;         // テンプレートディレクトリ
352                                         $templateDir = $this->gEnv->getTemplatesPath() . '/' . $templateId;                     // ダウンロードするテンプレートのディレクトリ
353                                         list($dir, $filename) = explode('/', $templateId);      // 先頭の「s/」を削除
354                                         $downloadFilename = $filename . '.zip';         // ダウンロード時のファイル名
355                                         break;
356                         }
357                         $tmpFile = tempnam($this->gEnv->getWorkDirPath(), M3_SYSTEM_WORK_DOWNLOAD_FILENAME_HEAD);               // zip処理用一時ファイル
358                         
359                         // zip圧縮
360                         $zipFile = new PclZip($tmpFile);
361                         $ret = $zipFile->create($templateDir, PCLZIP_OPT_REMOVE_PATH, $templatesDir);
362                         if ($ret){
363                                 // ページ作成処理中断
364                                 $this->gPage->abortPage();
365                                 
366                                 // ダウンロード処理
367                                 $ret = $this->gPage->downloadFile($tmpFile, $downloadFilename, true/*実行後ファイル削除*/);
368                                 
369                                 // システム強制終了
370                                 $this->gPage->exitSystem();
371                         } else {
372                                 //$msg = 'ファイルのダウンロードに失敗しました(要因: ' . $zipFile->errorName(true) . ')';
373                                 $msg = sprintf($this->_('Failed in downloading file. (detail: %s)'), $zipFile->errorName(true));                // ファイルのダウンロードに失敗しました(要因: %s)
374                                 $this->setAppErrorMsg($msg);
375                                 
376                                 // テンポラリファイル削除
377                                 unlink($tmpFile);
378                         }
379                 } else if ($act == 'changedefault'){            // デフォルトテンプレートの変更のとき
380                         // パラメータエラーチェック
381                         if (empty($templateId)) $this->setMsg(self::MSG_APP_ERR, $this->_('Template not selected.'));           // テンプレートが選択されていません
382                         
383                         if (!$this->isExistsMsg()){             // エラーなしのとき
384                                 switch ($this->templateType){
385                                         case '0':               // PC用テンプレート
386                                         default:
387                                                 // デフォルトテンプレート変更
388                                                 $this->gSystem->changeDefaultTemplate($templateId);
389
390                                                 // セッションのテンプレートIDを更新
391                                                 $request->setSessionValue(M3_SESSION_CURRENT_TEMPLATE, $templateId);
392                                                 break;
393                                         case '1':               // 携帯用テンプレート
394                                                 // デフォルトテンプレート変更
395                                                 $this->gSystem->changeDefaultMobileTemplate($templateId);
396                                                 break;
397                                         case '2':               // スマートフォン用テンプレート
398                                                 // デフォルトテンプレート変更
399                                                 $this->gSystem->changeDefaultSmartphoneTemplate($templateId);
400                                                 break;
401                                 }
402                                 // キャッシュデータをクリア
403                                 $this->gCache->clearAllCache();
404                         }
405                 } else if ($act == 'changedetail'){             // 詳細表示の変更のとき
406                         // 画面設定値を更新
407                         $this->gDisp->setAdminConfig(admin_mainDef::CFG_SHOW_TEMPLATE_DETAIL, strval($this->showDetail));
408                 } else if ($act == 'changetype'){               // テンプレートタイプの変更のとき
409                 }
410                 
411                 // 詳細設定状況を再取得
412                 $this->showDetail = intval($this->gDisp->getAdminConfig(admin_mainDef::CFG_SHOW_TEMPLATE_DETAIL));
413                         
414                 // テンプレートのタイプごとの処理
415                 switch ($this->templateType){
416                         case '0':               // PC用テンプレート
417                         default:
418                                 $this->defalutTemplate = $this->gSystem->defaultTemplateId();// デフォルトのテンプレート
419                                 $installDir = $this->gEnv->getTemplatesPath();// テンプレート格納ディレクトリ
420                                 break;
421                         case '1':               // 携帯用テンプレート
422                                 $this->defalutTemplate = $this->gSystem->defaultMobileTemplateId();// デフォルトのテンプレート
423                                 $installDir = $this->gEnv->getTemplatesPath() . '/' . M3_DIR_NAME_MOBILE;// テンプレート格納ディレクトリ
424                                 break;
425                         case '2':               // スマートフォン用テンプレート
426                                 $this->defalutTemplate = $this->gSystem->defaultSmartphoneTemplateId();// デフォルトのテンプレート
427                                 $installDir = $this->gEnv->getTemplatesPath() . '/' . M3_DIR_NAME_SMARTPHONE;// テンプレート格納ディレクトリ
428                                 break;
429                 }
430                 // 表示制御
431                 if (!empty($this->showDetail)){         // 詳細表示のとき
432                         $this->tmpl->setAttribute('show_dir', 'visibility', 'visible');// ディレクトリ表示
433                 }
434                 
435                 // テンプレート選択メニュー作成
436                 $this->createTemplateTypeMenu();
437                 
438                 // テンプレートリストを取得
439                 $this->db->getAllTemplateList(intval($this->templateType), array($this, 'tempListLoop'));
440                 if (!$this->isExistsTemplateList) $this->tmpl->setAttribute('templist', 'visibility', 'hidden');// テンプレートがないときは、一覧を表示しない
441                 
442                 // 画面にデータを埋め込む
443                 $checkedStr = '';
444                 if (!empty($this->showDetail)) $checkedStr = 'checked';
445                 $this->tmpl->addVar("_widget", "show_detail", $checkedStr);             // 詳細表示
446                 $this->tmpl->addVar("show_dir", "install_dir", $installDir);// インストールディレクトリ
447                 $this->tmpl->addVar("_widget", "admin_url", $this->getUrl($this->gEnv->getDefaultAdminUrl()));// 管理用URL
448                 
449                 // テキストをローカライズ
450                 $localeText = array();
451                 $localeText['msg_update_line'] = $this->_('Update line?');              // 行を更新しますか?
452                 $localeText['msg_delete_line'] = $this->_('Delete tmplate?');           // テンプレートを削除しますか?
453                 $localeText['msg_no_upload_file'] = $this->_('File not selected.');             // アップロードするファイルが選択されていません
454                 $localeText['msg_upload_file'] = $this->_('Upload file.');              // ファイルをアップロードします
455                 $localeText['label_template_list'] = $this->_('Template List');                 // テンプレート一覧
456                 $localeText['label_template_type'] = $this->_('Template Type:');                        // テンプレートタイプ:
457                 $localeText['label_install_dir'] = $this->_('Install Directory:');                      // インストールディレクトリ:
458                 $localeText['label_read_new'] = $this->_('Reload directory');                   // ディレクトリ再読み込み
459                 $localeText['label_show_detail'] = $this->_('Show detail');                     // 詳細表示
460                 $localeText['label_template_name'] = $this->_('Name');                  // 名前
461                 $localeText['label_template_format'] = $this->_('Format');                      // 形式
462                 $localeText['label_template_creator'] = $this->_('Artisteer Version');                  // Artisteerバージョン
463                 $localeText['label_template_default'] = $this->_('Default');                    // デフォルト
464                 $localeText['label_template_date'] = $this->_('Update Date');                   // 更新日時
465                 $localeText['label_template_operation'] = $this->_('Operation');                        // 操作
466                 $localeText['label_template_upload'] = $this->_('Template Upload (zip compressed file)');                       // テンプレートアップロード(zip圧縮ファイル)
467                 $localeText['label_upload'] = $this->_('Upload');                       // アップロード
468                 $this->setLocaleText($localeText);
469         }
470         /**
471          * テンプレートリスト、取得したデータをテンプレートに設定する
472          *
473          * @param int $index                    行番号(0~)
474          * @param array $fetchedRow             フェッチ取得した行
475          * @param object $param                 未使用
476          * @return bool                                 true=処理続行の場合、false=処理終了の場合
477          */
478         function tempListLoop($index, $fetchedRow, $param)
479         {
480                 // テンプレートが存在するかどうかチェック
481                 $isExistsTemplate = false;
482                 $templateId = $fetchedRow['tm_id'];// テンプレートID
483                 $templateDir = $this->gEnv->getTemplatesPath() . '/' . $templateId;                     // テンプレートのディレクトリ
484                 if (file_exists($templateDir)) $isExistsTemplate = true;
485                                                                 
486                 // 詳細表示の設定
487                 if ($this->showDetail){
488                         $this->tmpl->addVar('templist', 'templatetype', 'detail');              // 詳細表示
489                 }
490                 
491                 // デフォルトテンプレート
492                 $defaultCheck = '';
493                 if ($fetchedRow['tm_id'] == $this->defalutTemplate){
494                         $defaultCheck = 'checked ';
495                 }
496                 if (!$isExistsTemplate) $defaultCheck .= 'disabled';            // テンプレートが存在しないときは使用不可
497                 
498                 // 画面イメージ表示設定
499                 $name = $this->convertToDispString($fetchedRow['tm_name']);                     // テンプレート名
500                 $templateIndexFile = $templateDir . '/index.php';                                               // テンプレートindex.phpファイル
501                 $imgUrl = $this->gEnv->getTemplatesUrl() . '/' . $templateId . '/' . self::TEMPLATE_THUMBNAIL_FILENAME;
502                 
503                 // 新規に追加されたテンプレートかチェック
504                 $idText = $this->convertToDispString($templateId);
505                 for ($i = 0; $i < count($this->newTemplate); $i++){
506                         if ($this->newTemplate[$i] == $templateId){
507                                 $idText = '<b><font color="green">' . $this->convertToDispString($templateId) . '</font></b>';
508                                 break;
509                         }
510                 }
511                 // テンプレートサムネール画像
512                 if ($isExistsTemplate){         // テンプレートが存在するとき
513                         $imageTag = '<img src="' . $this->getUrl($imgUrl) . '" width="' . self::previewImageSizeWidth . '" height="' . self::previewImageSizeHeight . '" border="0" />';
514                 } else {
515                         $iconTitle = $this->_('Template not found.');           // テンプレートが見つかりません
516                         $iconUrl = $this->gEnv->getRootUrl() . self::NOT_FOUND_TEMPLATE_ICON_FILE;
517                         $imageTag = '<img src="' . $this->getUrl($iconUrl) . '" border="0" alt="' . $iconTitle . '" title="' . $iconTitle . '" />';
518                 }
519                 
520                 // テンプレートフォーマット
521                 switch ($fetchedRow['tm_type']){
522                         case 0:                                 // Joomla!v1.0型
523                                 $formatType = 'J10';            // テンプレート形式
524                                 break;
525                         case 1:                                 // Joomla!v1.5型
526                                 $formatType = 'J15';            // テンプレート形式
527                                 break;
528                         case 2:                                 // Joomla!v2.5型
529                                 $formatType = 'J25';            // テンプレート形式
530                                 break;
531                         default:
532                                 $formatType = $this->_('Not Detected');                 // 未定
533                                 break;
534                 }
535                 $formatType .= ' /<br />';
536                 
537                 // テンプレートを作成したArtisteerのバージョンを取得
538                 if (file_exists($templateIndexFile)){
539                         $content = file_get_contents($templateIndexFile);
540                         $version = $this->getArtVersion($content);
541                         if (empty($version)){
542                                 $formatType .= $this->_('Not Detected');                // 未検出
543                         } else {
544                                 $formatType .= $version;
545                         }
546                 }
547                 
548                 // ボタンの状態
549                 $downloadButton = '';
550                 if (!$isExistsTemplate) $downloadButton = 'disabled';
551                 
552                 $row = array(
553                         'no' => $index + 1,                                                                                                     // 行番号
554                         'serial' => $this->convertToDispString($fetchedRow['tm_serial']),                       // シリアル番号
555                         'id_str' => $idText,
556                         'id' => $this->convertToDispString($templateId),                        // ID
557                         'name' => $name,                // 名前
558                         'format_type' => $formatType,           // テンプレート形式
559                         'update_dt' => $this->convertToDispDateTime($fetchedRow['tm_create_dt']),       // 更新日時
560                         'is_default' => $defaultCheck,                                                                          // デフォルトテンプレートかどうか
561                         'image_tag' => $imageTag,               // 画像
562                         'download_button' => $downloadButton,           // ダウンロードボタン
563                         'label_preview' => $this->_('Preview'),                 // プレビュー
564                         'label_update' => $this->_('Update'),                   // 更新
565                         'label_delete' => $this->_('Delete'),                   // 削除
566                         'label_download' => $this->_('Download')                        // ダウンロード
567                 );
568                 $this->tmpl->addVars('templist', $row);
569                 $this->tmpl->parseTemplate('templist', 'a');
570                 
571                 $this->isExistsTemplateList = true;             // テンプレートが存在する
572                 return true;
573         }
574         /**
575          * テンプレートを新規追加
576          *
577          * @param int $type                     テンプレート種別(0=PC用、1=携帯用, 2=スマートフォン用)
578          * @param string $id            テンプレートID(ディレクトリ名)
579          * @param bool                          true=成功、false=失敗
580          */
581         function addNewTemplate($type, $id)
582         {
583                 $ret = false;
584                 $templType = 0;                 // テンプレートのタイプデフォルト値(Joomla!1.0)
585                 $cleanType = 0;                 // HTMLの出力のクリーニングタイプ
586                 
587                 // テンプレートの種別を判定
588                 switch ($type){
589                         case '0':               // PC用テンプレート
590                         case '2':               // スマートフォン用テンプレート
591                                 $configFile = $this->gEnv->getTemplatesPath() . '/' . $id . '/' . self::JOOMLA_CONFIG_FILENAME;
592                                 if (file_exists($configFile)){
593                                         if (!function_exists('simplexml_load_file')){
594                                                 $msg = $this->_('SimpleXML module not installed.');             // SimpleXML拡張モジュールがインストールされていません
595                                                 $this->setAppErrorMsg($msg);
596                                                 return false;
597                                         }
598                                         $xml = simplexml_load_file($configFile);
599                                         if ($xml !== false){
600                                                 if ($xml->attributes()->type == 'template'){
601                                                         $version = $xml->attributes()->version;
602                                                         if (version_compare($version, '1.6') >= 0){
603                                                                 $templType = 2;         // Joomla!v2.5テンプレート
604                                                         } else if (version_compare($version, '1.5') >= 0){
605                                                                 $templType = 1;         // Joomla!v1.5テンプレート
606
607                                                                 // テンプレートをテスト
608                                                                 $cleanType = $this->checkTemplate($id);
609                                                         }
610                                                 }
611                                         }
612                                 }
613                                 break;
614                 }
615                 
616                 // テンプレートを登録
617                 $ret = $this->db->addNewTemplate($id, $id, $templType, intval($type), $cleanType);
618                 return $ret;
619         }
620         /**
621          * テンプレートIDを取得
622          *
623          * @param string $dir           テンプレートのディレクトリ
624          * @return string                       テンプレート(取得できないときは空を返す)
625          */
626         function getTemplateId($dir)
627         {
628                 // デフォルトはディレクトリ名
629                 $id = basename($dir);
630
631                 // 設定ファイルがあれば読み込む
632                 $configFile = $dir . '/' . self::JOOMLA_CONFIG_FILENAME;
633                 if (file_exists($configFile)){
634                         if (!function_exists('simplexml_load_file')){
635                                 $msg = $this->_('SimpleXML module not installed.');             // SimpleXML拡張モジュールがインストールされていません
636                                 $this->setAppErrorMsg($msg);
637                                 return '';
638                         }
639                         $xml = simplexml_load_file($configFile);
640                         if ($xml !== false){
641                                 $name = trim($xml->name);
642                                 if (!empty($name)) $id = $name;
643                         }
644                 }
645                 return $id;
646         }
647         /**
648          * タイプ選択メニュー作成
649          *
650          * @return なし
651          */
652         function createTemplateTypeMenu()
653         {
654                 for ($i = 0; $i < count($this->templateTypeArray); $i++){
655                         $value = $this->templateTypeArray[$i]['value'];
656                         $name = $this->templateTypeArray[$i]['name'];
657                         
658                         $selected = '';
659                         if ($value == $this->templateType) $selected = 'selected';
660                         
661                         $row = array(
662                                 'value'    => $value,                   // ページID
663                                 'name'     => $name,                    // ページ名
664                                 'selected' => $selected                                                                                                         // 選択中かどうか
665                         );
666                         $this->tmpl->addVars('item_type_list', $row);
667                         $this->tmpl->parseTemplate('item_type_list', 'a');
668                 }
669         }
670         /**
671          * テンプレートの出力チェック
672          *
673          * @param string $templateId    テンプレートID
674          * @return int                                  クリーン処理タイプ
675          */
676         function checkTemplate($id)
677         {
678                 $cleanType = 0;
679                 
680                 // Joomla!テンプレート共通の設定
681                 define('_JEXEC', 1);
682                         
683                 // Joomla!v1.5用の設定
684                 define('JPATH_BASE', dirname(__FILE__));
685                 define('DS', DIRECTORY_SEPARATOR);
686                 
687                 // バッファ作成
688                 ob_start();
689                 
690                 $render = new JRender();
691                 $render->setTemplate($id);
692                 $contents = $render->getComponentContents('test', 'dummy contents', 'test');
693                 
694                 // 不要なタグをチェック
695                 $pos = strpos($contents, 'PostHeaderIcons');
696                 if ($pos !== false) $cleanType = 1;
697                 
698                 // バッファを破棄
699                 ob_end_clean();
700                 return $cleanType;
701         }
702         /**
703          * テンプレートのindex.phpファイルからArtisteerバージョンを取得
704          *
705          * @param string $src           検索するデータ
706          * @return string                       検出の場合はバージョン文字列、未検出の場合は空文字列。
707          */
708         function getArtVersion($src)
709         {
710                 $version = '';
711                 // <!-- Created by Artisteer v4.1.0.59688 -->
712                 $pattern = '/<!-- Created by Artisteer[^<]*?v([.\d]+)[^<]*?-->/i';
713         $ret = preg_match($pattern, $src, $matches);
714                 if ($ret) $version = $matches[1];
715                 return $version;
716         }
717 }
718 ?>