OSDN Git Service

#16736 - Remove notification files.
[mulab/XCLite.git] / public_html / modules / legacy / admin / class / ModuleInstallUtils.class.php
1 <?php
2 /**
3  *
4  * @package Legacy
5  * @version $Id: ModuleInstallUtils.class.php,v 1.11 2008/10/26 04:07:23 minahito Exp $
6  * @copyright Copyright 2005-2007 XOOPS Cube Project  <http://xoopscube.sourceforge.net/> 
7  * @license http://xoopscube.sourceforge.net/license/GPL_V2.txt GNU GENERAL PUBLIC LICENSE Version 2
8  *
9  */
10
11 if (!defined('XOOPS_ROOT_PATH')) exit();
12
13 require_once XOOPS_LEGACY_PATH . "/admin/class/ModuleInstallInformation.class.php";
14 require_once XOOPS_LEGACY_PATH . "/admin/class/ModuleInstaller.class.php";
15 require_once XOOPS_LEGACY_PATH . "/admin/class/ModuleUpdater.class.php";
16 require_once XOOPS_LEGACY_PATH . "/admin/class/ModuleUninstaller.class.php";
17
18 require_once XOOPS_ROOT_PATH."/class/template.php";
19
20 define("MODINSTALL_LOGTYPE_REPORT", "report");
21 define("MODINSTALL_LOGTYPE_WARNING", "warning");
22 define("MODINSTALL_LOGTYPE_ERROR", "error");
23
24 /**
25  * A temporary log class.
26  */
27 class Legacy_ModuleInstallLog
28 {
29         var $mFetalErrorFlag = false;
30         var $mMessages = array();
31
32         function add($msg)
33         {
34                 $this->mMessages[] = array('type' => MODINSTALL_LOGTYPE_REPORT, 'message' => $msg);
35         }
36
37         function addReport($msg)
38         {
39                 $this->add($msg);
40         }
41         
42         function addWarning($msg)
43         {
44                 $this->mMessages[] = array('type' => MODINSTALL_LOGTYPE_WARNING, 'message' => $msg);
45         }
46
47         function addError($msg)
48         {
49                 $this->mMessages[] = array('type' => MODINSTALL_LOGTYPE_ERROR, 'message' => $msg);
50                 $this->mFetalErrorFlag = true;
51         }
52         
53         function hasError()
54         {
55                 return $this->mFetalErrorFlag;
56         }
57 }
58
59 /**
60  * This class is collection of static utility functions for module installation.
61  * These functions are useful for Legacy modules' system-fixed-installer and
62  * modules' custom-installer. All functions for the custom-installer are added
63  * notes as "FOR THE CUSTOM-ISNTALLER".
64  * 
65  * For more attentions, see base classes for the custom-installer.
66  * 
67  * @see Legacy_PhasedUpgrader
68  */
69 class Legacy_ModuleInstallUtils
70 {
71         /**
72          * This is factory for the installer. The factory reads xoops_version
73          * without modulehandler, to prevent cache in modulehandler.
74          */
75         function &createInstaller($dirname)
76         {
77                 $installer =& Legacy_ModuleInstallUtils::_createInstaller($dirname, 'installer', 'Legacy_ModuleInstaller');
78         return $installer;
79         }
80         
81         /**
82          * This is factory for the updater. The factory reads xoops_version
83          * without modulehandler, to prevent cache in modulehandler.
84          */
85         function &createUpdater($dirname)
86         {
87                 $updater =& Legacy_ModuleInstallUtils::_createInstaller($dirname, 'updater', 'Legacy_ModulePhasedUpgrader');
88                 return $updater;
89         }
90         
91         /**
92          * This is factory for the uninstaller. The factory reads xoops_version
93          * without modulehandler, to prevent cache in modulehandler.
94          */
95         function &createUninstaller($dirname)
96         {
97                 $uninstaller =& Legacy_ModuleInstallUtils::_createInstaller($dirname, 'uninstaller', 'Legacy_ModuleUninstaller');
98                 return $uninstaller;
99         }
100         
101         /**
102          * The generic factory for installers. This function is used by other
103          * utility functions.
104          * @param string $dirname
105          * @param string $mode 'installer' 'updater' or 'uninstaller'
106          * @param string $defaultClassName
107          */
108         function &_createInstaller($dirname, $mode, $defaultClassName)
109         {
110                 $info = array();
111                 
112                 $filepath = XOOPS_MODULE_PATH . "/${dirname}/xoops_version.php";
113                 if (file_exists($filepath)) {
114                         @include $filepath;
115                         $info = $modversion;
116                 }
117
118                 if (isset($info['legacy_installer']) && is_array($info['legacy_installer']) && isset($info['legacy_installer'][$mode])) {
119                         $updateInfo = $info['legacy_installer'][$mode];
120                                 
121                         $className = $updateInfo['class'];
122                         $filePath = isset($updateInfo['filepath']) ? $updateInfo['filepath'] : XOOPS_MODULE_PATH . "/${dirname}/admin/class/${className}.class.php";
123                         $namespace = isset($updateInfo['namespace']) ? $updateInfo['namespace'] : ucfirst($dirname);
124                                 
125                         if ($namespace != null) {
126                                 $className = "${namespace}_${className}";
127                         }
128                                 
129                         if (!XC_CLASS_EXISTS($className) && file_exists($filePath)) {
130                                 require_once $filePath;
131                         }
132                                 
133                         if (XC_CLASS_EXISTS($className)) {
134                                 $installer =& new $className();
135                                 return $installer;
136                         }
137                 }
138                 
139                 $installer =& new $defaultClassName();
140                 return $installer;
141         }
142         
143         
144         /**
145          * Executes SQL file which xoops_version of $module specifies. This
146          * function is usefull for installers, but it's impossible to control
147          * for detail.
148          * 
149          * @static
150          * @param XoopsModule $module
151          * @param Legacy_ModuleInstallLog $log
152          * @note FOR THE CUSTOM-INSTALLER
153          */
154         function installSQLAutomatically(&$module, &$log)
155         {
156                 $sqlfileInfo =& $module->getInfo('sqlfile');
157                 $dirname = $module->getVar('dirname');
158
159                 if (!isset($sqlfileInfo[XOOPS_DB_TYPE])) {
160                         return;
161                 }
162                 
163                 $sqlfile = $sqlfileInfo[XOOPS_DB_TYPE];
164                 $sqlfilepath = XOOPS_MODULE_PATH . "/${dirname}/${sqlfile}";
165                 
166                 if (isset($module->modinfo['cube_style']) && $module->modinfo['cube_style'] == true) {
167                         require_once XOOPS_MODULE_PATH . "/legacy/admin/class/Legacy_SQLScanner.class.php";
168                         $scanner =& new Legacy_SQLScanner();
169                         $scanner->setDB_PREFIX(XOOPS_DB_PREFIX);
170                         $scanner->setDirname($module->get('dirname'));
171                         
172                         if (!$scanner->loadFile($sqlfilepath)) {
173                                 $log->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_SQL_FILE_NOT_FOUND, $sqlfile));
174                                 return false;
175                         }
176         
177                         $scanner->parse();
178                         $sqls = $scanner->getSQL();
179                         
180                         $root =& XCube_Root::getSingleton();
181                         $db =& $root->mController->getDB();
182                         
183                         //
184                         // TODO The following variable exists for rollback, but it is not implemented.
185                         //
186                         foreach ($sqls as $sql) {
187                                 if (!$db->query($sql)) {
188                                         $log->addError($db->error());
189                                         return;
190                                 }
191                         }
192                         
193                         $log->addReport(_AD_LEGACY_MESSAGE_DATABASE_SETUP_FINISHED);
194                 }
195                 else {
196                         require_once XOOPS_ROOT_PATH.'/class/database/sqlutility.php';
197                         
198                         $reservedTables = array('avatar', 'avatar_users_link', 'block_module_link', 'xoopscomments', 'config', 'configcategory', 'configoption', 'image', 'imagebody', 'imagecategory', 'groups','groups_users_link','group_permission', 'priv_msgs', 'ranks', 'session', 'smiles', 'users', 'newblocks', 'modules', 'tplfile', 'tplset', 'tplsource');
199
200                         $root =& XCube_Root::getSingleton();
201                         $db =& $root->mController->mDB;
202                         
203                         $sql_query = fread(fopen($sqlfilepath, 'r'), filesize($sqlfilepath));
204                         $sql_query = trim($sql_query);
205                         SqlUtility::splitMySqlFile($pieces, $sql_query);
206                         $created_tables = array();
207                         foreach ($pieces as $piece) {
208                                 // [0] contains the prefixed query
209                                 // [4] contains unprefixed table name
210                                 $prefixed_query = SqlUtility::prefixQuery($piece, $db->prefix());
211                                 if (!$prefixed_query) {
212                                         $log->addError("${piece} is not a valid SQL!");
213                                         return;
214                                 }
215                                 
216                                 // check if the table name is reserved
217                                 if (!in_array($prefixed_query[4], $reservedTables)) {
218                                         // not reserved, so try to create one
219                                         if (!$db->query($prefixed_query[0])) {
220                                                         $log->addError($db->error());
221                                                 return;
222                                         }
223                                         else {
224                                                 if (!in_array($prefixed_query[4], $created_tables)) {
225                                                         $log->addReport('  Table ' . $db->prefix($prefixed_query[4]) . ' created.');
226                                                         $created_tables[] = $prefixed_query[4];
227                                                 }
228                                                 else {
229                                                         $log->addReport('  Data inserted to table ' . $db->prefix($prefixed_query[4]));
230                                                 }
231                                         }
232                                 }
233                                 else {
234                                         // the table name is reserved, so halt the installation
235                                         $log->addError($prefixed_query[4] . " is a reserved table!");
236                                         return;
237                                 }
238                         }
239                 }
240         }
241         
242         /**
243          * Installs all of module templates $module specify. This function is
244          * usefull for installer and updater. In the case of updater, you should
245          * uninstall all of module templates before this function.
246          * 
247          * This function gets informations about templates from xoops_version.
248          * 
249          * @warning
250          * 
251          * This function depends the specific spec of Legacy_RenderSystem, but this
252          * static function is needed by the 2nd installer of Legacy System.
253          * 
254          * @static
255          * @param XoopsModule $module
256          * @param Legacy_ModuleInstallLog $log
257          * @note FOR THE CUSTOM-INSTALLER
258          * @see Legacy_ModuleInstallUtils::uninstallAllOfModuleTemplates()
259          */     
260         function installAllOfModuleTemplates(&$module, &$log)
261         {
262         $templates = $module->getInfo('templates');
263         if ($templates != false) {
264             foreach ($templates as $template) {
265                 Legacy_ModuleInstallUtils::installModuleTemplate($module, $template, $log);
266             }
267         }
268         }
269         
270         /**
271          * Inserts the specified template to DB.
272          * 
273          * @warning
274          * 
275          * This function depends the specific spec of Legacy_RenderSystem, but this
276          * static function is needed by the 2nd installer of Legacy System.
277          * 
278          * @static
279          * @param XoopsModule $module
280          * @param string[][] $template
281          * @param Legacy_ModuleInstallLog $log
282          * @return bool
283          * 
284          * @note This is not usefull a litte for custom-installers.
285          * @todo We'll need the way to specify the template by identity or others.
286          */
287         function installModuleTemplate($module, $template, &$log)
288         {
289                 $tplHandler =& xoops_gethandler('tplfile');
290
291                 $fileName = trim($template['file']);
292
293                 $tpldata = Legacy_ModuleInstallUtils::readTemplateFile($module->get('dirname'), $fileName);
294                 if ($tpldata == false)
295                         return false;
296
297                 //
298                 // Create template file object, then store it.
299                 //
300                 $tplfile =& $tplHandler->create();
301                 $tplfile->setVar('tpl_refid', $module->getVar('mid'));
302                 $tplfile->setVar('tpl_lastimported', 0);
303                 $tplfile->setVar('tpl_lastmodified', time());
304
305                 if (preg_match("/\.css$/i", $fileName)) {
306                         $tplfile->setVar('tpl_type', 'css');
307                 }
308                 else {
309                         $tplfile->setVar('tpl_type', 'module');
310                 }
311
312                 $tplfile->setVar('tpl_source', $tpldata, true);
313                 $tplfile->setVar('tpl_module', $module->getVar('dirname'));
314                 $tplfile->setVar('tpl_tplset', 'default');
315                 $tplfile->setVar('tpl_file', $fileName, true);
316
317                 $description = isset($template['description']) ? $template['description'] : '';
318                 $tplfile->setVar('tpl_desc', $description, true);
319                 
320                 if ($tplHandler->insert($tplfile)) {
321                         $log->addReport(XCube_Utils::formatMessage(_AD_LEGACY_MESSAGE_TEMPLATE_INSTALLED, $fileName));
322                 }
323                 else {
324                         $log->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_COULD_NOT_INSTALL_TEMPLATE, $fileName));
325                         return false;
326                 }
327         }
328
329         /**
330          * Uninstalls all of module templates $module specify. This function is
331          * usefull for uninstaller and updater. In the case of update, you should
332          * call this function before installAllOfModuleTemplates(). In the case of
333          * uninstall, you must set 'false' to $defaultOnly.
334          * 
335          * This function gets informations about templates from the database.
336          * 
337          * @warning
338          * 
339          * This function depends the specific spec of Legacy_RenderSystem, but this
340          * static function is needed by the 2nd installer of Legacy System.
341          * 
342          * @static
343          * @param XoopsModule $module
344          * @param Legacy_ModuleInstallLog $log
345          * @param bool $defaultOnly Indicates whether this function deletes templates from all of tplsets.
346          * @note FOR THE CUSTOM-INSTALLER
347          * @see Legacy_ModuleInstallUtils::installAllOfModuleTemplates()
348          */     
349         function _uninstallAllOfModuleTemplates(&$module, $tplset, &$log)
350         {
351                 //
352                 // The following processing depends on the structure of Legacy_RenderSystem.
353                 //
354                 $tplHandler =& xoops_gethandler('tplfile');
355                 $delTemplates = null;
356                 
357                 $delTemplates =& $tplHandler->find($tplset, 'module', $module->get('mid'));
358                 
359                 if (is_array($delTemplates) && count($delTemplates) > 0) {
360                         //
361                         // clear cache
362                         //
363                         $xoopsTpl =& new XoopsTpl();
364                         $xoopsTpl->clear_cache(null, "mod_" . $module->get('dirname'));
365                         
366                         foreach ($delTemplates as $tpl) {
367                                 if (!$tplHandler->delete($tpl)) {
368                                         $log->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_TEMPLATE_UNINSTALLED, $tpl->get('tpl_file')));
369                                 }
370                         }
371                 }
372         }
373         
374         function uninstallAllOfModuleTemplates(&$module, &$log)
375         {
376                 Legacy_ModuleInstallUtils::_uninstallAllOfModuleTemplates($module, null, $log);
377         }
378
379         function clearAllOfModuleTemplatesForUpdate(&$module, &$log)
380         {
381                 Legacy_ModuleInstallUtils::_uninstallAllOfModuleTemplates($module, 'default', $log);
382         }
383         
384         /**
385          * Installs all of blocks $module specify.
386          * 
387          * This function gets informations about blocks from xoops_version.
388          * 
389          * @static
390          * @param XoopsModule $module
391          * @param Legacy_ModuleInstallLog $log
392          * @note FOR THE CUSTOM-INSTALLER
393          * @see Legacy_ModuleInstallUtils::uninstallAllOfBlocks()
394          */     
395         function installAllOfBlocks(&$module, &$log)
396         {
397                 $definedBlocks = $module->getInfo('blocks');
398                 if($definedBlocks == false) {
399                         return true;
400                 }
401                 
402                 $func_num = 0;
403                 foreach ($definedBlocks as $block) {
404                         $successFlag = true;
405                         $updateblocks = array();
406                         
407                         // Try (1) --- func_num
408                         foreach ($definedBlocks as $idx => $block) {
409                                 if (isset($block['func_num'])) {
410                                         $updateblocks[$idx] = $block;
411                                 } else {
412                                         $successFlag = false;
413                                         break;
414                                 }
415                         }
416                         
417                         // Try (2) --- index pattern
418                         if ($successFlag == false) {
419                                 $successFlag = true;
420                                 $updateblocks = array();
421                                 foreach ($definedBlocks as $idx => $block) {
422                                         if (is_int($idx)) {
423                                                 $block['func_num'] = $idx;
424                                                 $updateblocks[$idx] = $block;
425                                         } else {
426                                                 $successFlag = false;
427                                                 break;
428                                         }
429                                 }
430                         }
431                         
432                         // Try (3) --- automatic
433                         if ($successFlag == false) {
434                                 $successFlag = true;
435                                 $updateblocks = array();
436
437                                 $func_num = 0;
438                                 foreach ($definedBlocks as $block) {
439                                         $block['func_num'] = $func_num;
440                                         $updateblocks[] = $block;
441                                 }
442                         }
443                 }
444                 
445                 foreach ($updateblocks as $block) {
446                         $newBlock =& Legacy_ModuleInstallUtils::createBlockByInfo($module, $block, $block['func_num']);
447                         Legacy_ModuleInstallUtils::installBlock($module, $newBlock, $block, $log);
448                 }
449         }
450
451         /**
452          * Uninstalls all of blocks which $module specifies, and its permissions.
453          * 
454          * This function gets informations about templates from the database.
455          * 
456          * @static
457          * @param XoopsModule $module
458          * @param Legacy_ModuleInstallLog $log
459          * @return bool
460          * 
461          * @note FOR THE CUSTOM-INSTALLER
462          * @see Legacy_ModuleInstallUtils::installAllOfBlocks()
463          * @see Legacy_ModuleInstallUtils::uninstallBlock()
464          */     
465         function uninstallAllOfBlocks(&$module, &$log)
466         {
467                 $handler =& xoops_gethandler('block');
468                 $criteria = new Criteria('mid', $module->get('mid'));
469
470                 $blockArr =& $handler->getObjectsDirectly($criteria);
471                 
472                 $successFlag = true;
473                 
474                 foreach (array_keys($blockArr) as $idx) {
475                         $successFlag &= Legacy_ModuleInstallUtils::uninstallBlock($blockArr[$idx], $log);
476                 }
477                 
478                 return $successFlag;
479         }
480         
481         /**
482          * Create XoopsBlock object by array that is defined in xoops_version, return it.
483          * @param $module XoopsModule
484          * @param $block array
485          * @return XoopsBlock
486          */
487         function &createBlockByInfo(&$module, $block, $func_num)
488         {
489                 $options = isset($block['options']) ? $block['options'] : null;
490                 $edit_func = isset($block['edit_func']) ? $block['edit_func'] : null;
491                 $template = isset($block['template']) ? $block['template'] : null;
492                 $visible = isset($block['visible']) ? $block['visible'] : (isset($block['visible_any']) ? $block['visible_any']: 0);
493                 $blockHandler =& xoops_gethandler('block');
494                 $blockObj =& $blockHandler->create();
495
496                 $blockObj->set('mid', $module->getVar('mid'));
497                 $blockObj->set('options', $options);
498                 $blockObj->set('name', $block['name']);
499                 $blockObj->set('title', $block['name']);
500                 $blockObj->set('block_type', 'M');
501                 $blockObj->set('c_type', 1);
502                 $blockObj->set('isactive', 1);
503                 $blockObj->set('dirname', $module->getVar('dirname'));
504                 $blockObj->set('func_file', $block['file']);
505                 
506                 //
507                 // IMPORTANT CONVENTION
508                 //
509                 $show_func = "";
510                 if (isset($block['class'])) {
511                         $show_func = "cl::" . $block['class'];
512                 }
513                 else {
514                         $show_func = $block['show_func'];
515                 }
516                 
517                 $blockObj->set('show_func', $show_func);
518                 $blockObj->set('edit_func', $edit_func);
519                 $blockObj->set('template', $template);
520                 $blockObj->set('last_modified', time());
521                 $blockObj->set('visible', $visible);
522                 
523                 $func_num = isset($block['func_num']) ? intval($block['func_num']) : $func_num;
524                 $blockObj->set('func_num', $func_num);
525
526                 return $blockObj;
527         }
528         
529         /**
530          * This function can receive both new and update.
531          * @param $module XoopsModule
532          * @param $blockObj XoopsBlock
533          * @param $block array
534          * @return bool
535          */
536         function installBlock(&$module, &$blockObj, &$block, &$log)
537         {
538                 $isNew = $blockObj->isNew();
539                 $blockHandler =& xoops_gethandler('block');
540
541         if (!empty($block['show_all_module'])) {
542             $autolink = false;
543         } else {
544             $autolink = true;
545         }
546                 if (!$blockHandler->insert($blockObj, $autolink)) {
547                         $log->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_COULD_NOT_INSTALL_BLOCK, $blockObj->getVar('name')));
548
549                         return false;
550                 }
551                 else {
552                         $log->addReport(XCube_Utils::formatMessage(_AD_LEGACY_MESSAGE_BLOCK_INSTALLED, $blockObj->getVar('name')));
553
554                         $tplHandler =& xoops_gethandler('tplfile');
555
556                         Legacy_ModuleInstallUtils::installBlockTemplate($blockObj, $module, $log);
557                         
558                         //
559                         // Process of a permission.
560                         //
561                         if ($isNew) {
562                 if (!empty($block['show_all_module'])) {
563                                 $link_sql = "INSERT INTO " . $blockHandler->db->prefix('block_module_link') . " (block_id, module_id) VALUES (".$blockObj->getVar('bid').", 0)";
564                                 if (!$blockHandler->db->query($link_sql)) {
565                                         $log->addWarning(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_COULD_NOT_SET_LINK, $blockObj->getVar('name')));
566                                 }
567                         }
568                                 $gpermHandler =& xoops_gethandler('groupperm');
569                                 $bperm =& $gpermHandler->create();
570                                 $bperm->setVar('gperm_itemid', $blockObj->getVar('bid'));
571                                 $bperm->setVar('gperm_name', 'block_read');
572                                 $bperm->setVar('gperm_modid', 1);
573                                 
574                                 if (!empty($block['visible_any'])) {
575                                 $memberHandler =& xoops_gethandler('member');
576                                 $groupObjects =& $memberHandler->getGroups();
577                                 foreach($groupObjects as $group) {
578                                         $bperm->setVar('gperm_groupid', $group->getVar('groupid'));
579                                         $bperm->setNew();
580                                         if (!$gpermHandler->insert($bperm)) {
581                                                 $log->addWarning(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_COULD_NOT_SET_BLOCK_PERMISSION, $blockObj->getVar('name')));
582                                         }
583                                 }
584                                 } else {
585                                     $root =& XCube_Root::getSingleton();
586                     $groups = $root->mContext->mXoopsUser->getGroups(true);
587                     foreach ($groups as $mygroup) {
588                                         $bperm->setVar('gperm_groupid', $mygroup);
589                                         $bperm->setNew();
590                                         if (!$gpermHandler->insert($bperm)) {
591                                                 $log->addWarning(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_COULD_NOT_SET_BLOCK_PERMISSION, $blockObj->getVar('name')));
592                                     }
593                                 }
594                                 }
595                         }
596
597                         return true;
598                 }
599         }
600         
601         /**
602          * Uninstalls a block which $block specifies. In the same time, deletes
603          * permissions for the block.
604          * 
605          * @param XoopsBlock $block
606          * @param Legacy_ModuleInstallLog $log
607          * @note FOR THE CUSTOM-INSTALLER
608          * 
609          * @todo error handling & delete the block's template.
610          */
611         function uninstallBlock(&$block, &$log)
612         {
613                 $blockHandler =& xoops_gethandler('block');
614                 $blockHandler->delete($block);
615                 $log->addReport(XCube_Utils::formatMessage(_AD_LEGACY_MESSAGE_UNINSTALLATION_BLOCK_SUCCESSFUL, $block->get('name')));
616                 
617                 //
618                 // Deletes permissions
619                 //
620                 $gpermHandler =& xoops_gethandler('groupperm');
621                 $criteria =& new CriteriaCompo();
622                 $criteria->add(new Criteria('gperm_name', 'block_read'));
623                 $criteria->add(new Criteria('gperm_itemid', $block->get('bid')));
624                 $criteria->add(new Criteria('gperm_modid', 1));
625                 $gpermHandler->deleteAll($criteria);
626     }
627         
628         /**
629          * Save the information of block's template specified and the source code of it
630          * to database.
631          * @return bool
632          */
633         function installBlockTemplate(&$block, &$module, &$log)
634         {
635                 if ($block->get('template') == null) {
636                         return true;
637                 }
638                 
639                 $tplHandler =& xoops_gethandler('tplfile');
640
641                 $criteria =& new CriteriaCompo();
642                 $criteria->add(new Criteria('tpl_type', 'block'));
643                 $criteria->add(new Criteria('tpl_tplset', 'default'));
644                 $criteria->add(new Criteria('tpl_module', $module->get('dirname')));
645                 $criteria->add(new Criteria('tpl_file', $block->get('template')));
646                 $tplfiles =& $tplHandler->getObjects($criteria);
647
648                 if (count($tplfiles) > 0) {
649                         $tplfile =& $tplfiles[0];
650                 }
651                 else {
652                         $tplfile =& $tplHandler->create();
653                         $tplfile->set('tpl_refid', $block->get('bid'));
654                         $tplfile->set('tpl_tplset', 'default');
655                         $tplfile->set('tpl_file', $block->get('template'));
656                         $tplfile->set('tpl_module', $module->get('dirname'));
657                         $tplfile->set('tpl_type', 'block');
658                         // $tplfile->setVar('tpl_desc', $tpl_desc);
659                         $tplfile->set('tpl_lastimported', 0);
660                 }
661                 
662                 $tplSource = Legacy_ModuleInstallUtils::readTemplateFile($module->get('dirname'), $block->get('template'), true);
663                 $tplfile->set('tpl_source', $tplSource);
664                 $tplfile->set('tpl_lastmodified', time());
665
666                 if ($tplHandler->insert($tplfile)) {
667                     $log->addReport(XCube_Utils::formatMessage(_AD_LEGACY_MESSAGE_BLOCK_TEMPLATE_INSTALLED, $block->get('template')));
668                         return true;
669                 }
670                 else {
671                         $log->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_BLOCK_TEMPLATE_INSTALL, $block->get('name')));
672                         return false;
673                 }
674         }
675         
676         /**
677          * Read template file, return it.
678          * 
679          * @note This is must, but it depends on ...
680          */
681         function readTemplateFile($dirname, $fileName, $isblock = false)
682         {
683                 //
684                 // Load template data
685                 //
686                 if ($isblock) {
687                         $filePath = XOOPS_MODULE_PATH . "/" . $dirname . "/templates/blocks/" . $fileName;
688                 }
689                 else {
690                         $filePath = XOOPS_MODULE_PATH . "/" . $dirname . "/templates/" . $fileName;
691                 }
692
693                 if (!file_exists($filePath)) {
694                         return false;
695                 }
696
697                 $lines = file($filePath);
698                 if ($lines == false) {
699                         return false;
700                 }
701
702                 $tpldata = "";
703                 foreach ($lines as $line) {
704                         //
705                         // Unify linefeed to "\r\n" 
706                         //
707                         $tpldata .= str_replace("\n", "\r\n", str_replace("\r\n", "\n", $line));
708                 }
709                 
710                 return $tpldata;
711         }
712
713         function installAllOfConfigs(&$module, &$log)
714         {
715                 $dirname = $module->get('dirname');
716                 
717                 $fileReader =& new Legacy_ModinfoX2FileReader($dirname);
718                 $preferences =& $fileReader->loadPreferenceInformations();
719                 
720                 //
721                 // Preferences
722                 //
723                 foreach (array_keys($preferences->mPreferences) as $idx) {
724                         Legacy_ModuleInstallUtils::installPreferenceByInfo($preferences->mPreferences[$idx], $module, $log);
725                 }
726                 
727                 //
728                 // Comments
729                 //
730                 foreach (array_keys($preferences->mComments) as $idx) {
731                         Legacy_ModuleInstallUtils::installPreferenceByInfo($preferences->mComments[$idx], $module, $log);
732                 }
733         }
734         
735         function installPreferenceByInfo(&$info, &$module, &$log)
736         {
737                 $handler =& xoops_gethandler('config');
738                 $config =& $handler->createConfig();
739                 $config->set('conf_modid', $module->get('mid'));
740                 $config->set('conf_catid', 0);
741                 $config->set('conf_name', $info->mName);
742                 $config->set('conf_title', $info->mTitle);
743                 $config->set('conf_desc', $info->mDescription);
744                 $config->set('conf_formtype', $info->mFormType);
745                 $config->set('conf_valuetype', $info->mValueType);
746                 $config->setConfValueForInput($info->mDefault);
747                 $config->set('conf_order', $info->mOrder);
748                 
749                 if (count($info->mOption->mOptions) > 0) {
750                         foreach (array_keys($info->mOption->mOptions) as $idx) {
751                                 $option =& $handler->createConfigOption();
752                                 $option->set('confop_name', $info->mOption->mOptions[$idx]->mName);
753                                 $option->set('confop_value', $info->mOption->mOptions[$idx]->mValue);
754                                 $config->setConfOptions($option);
755                                 unset($option);
756                         }
757                 }
758                 
759                 if ($handler->insertConfig($config)) {
760                         $log->addReport(XCube_Utils::formatMessage(_AD_LEGACY_MESSAGE_INSERT_CONFIG, $config->get('conf_name')));
761                 }
762                 else {
763                         $log->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_COULD_NOT_INSERT_CONFIG, $config->get('conf_name')));
764                 }
765         }
766         
767         /**
768          * Get & build config items from Manifesto by specific module object.
769          */     
770         function &getConfigInfosFromManifesto(&$module)
771         {
772                 $configInfos = $module->getInfo('config');
773                 
774                 //
775                 // Insert comment config by old style.
776                 //
777                 if ($module->getVar('hascomments') !=0 ) {
778                         require_once XOOPS_ROOT_PATH . "/include/comment_constants.php";
779
780                         $configInfos[] = array('name' => 'com_rule',
781                                                  'title' => '_CM_COMRULES',
782                                                  'description' => '',
783                                                  'formtype' => 'select',
784                                                  'valuetype' => 'int',
785                                                  'default' => 1,
786                                                  'options' => array('_CM_COMNOCOM' => XOOPS_COMMENT_APPROVENONE, '_CM_COMAPPROVEALL' => XOOPS_COMMENT_APPROVEALL, '_CM_COMAPPROVEUSER' => XOOPS_COMMENT_APPROVEUSER, '_CM_COMAPPROVEADMIN' => XOOPS_COMMENT_APPROVEADMIN)
787                                            );
788
789                         $configInfos[] = array('name' => 'com_anonpost',
790                                                  'title' => '_CM_COMANONPOST',
791                                                  'description' => '',
792                                                  'formtype' => 'yesno',
793                                                  'valuetype' => 'int',
794                                                  'default' => 0
795                                            );
796                 }
797                 
798                 return $configInfos;
799         }
800         
801         /**
802          * Delete all configs of $module.
803          *
804          * @param $module XoopsModule
805          */
806         function uninstallAllOfConfigs(&$module, &$log)
807         {
808                 if ($module->get('hasconfig') == 0) {
809                         return;
810                 }
811
812                 $configHandler =& xoops_gethandler('config');
813                 $configs =& $configHandler->getConfigs(new Criteria('conf_modid', $module->get('mid')));
814
815                 if (count($configs) == 0) {
816                         return;
817                 }
818
819                 foreach ($configs as $config) {
820                         $configHandler->deleteConfig($config);
821                 }
822         }
823         
824         function smartUpdateAllOfBlocks(&$module, &$log)
825         {
826                 $dirname = $module->get('dirname');
827                 
828                 $fileReader =& new Legacy_ModinfoX2FileReader($dirname);
829                 $latestBlocks =& $fileReader->loadBlockInformations();
830                 
831                 $dbReader =& new Legacy_ModinfoX2DBReader($dirname);
832                 $currentBlocks =& $dbReader->loadBlockInformations();
833                 
834                 $currentBlocks->update($latestBlocks);
835
836                 foreach (array_keys($currentBlocks->mBlocks) as $idx) {
837                         switch ($currentBlocks->mBlocks[$idx]->mStatus) {
838                                 case LEGACY_INSTALLINFO_STATUS_LOADED:
839                                         Legacy_ModuleInstallUtils::updateBlockTemplateByInfo($currentBlocks->mBlocks[$idx], $module, $log);
840                                         break;
841                                         
842                                 case LEGACY_INSTALLINFO_STATUS_UPDATED:
843                                         Legacy_ModuleInstallUtils::updateBlockByInfo($currentBlocks->mBlocks[$idx], $module, $log);
844                                         break;
845                                         
846                                 case LEGACY_INSTALLINFO_STATUS_NEW:
847                                         Legacy_ModuleInstallUtils::installBlockByInfo($currentBlocks->mBlocks[$idx], $module, $log);
848                                         break;
849                                         
850                                 case LEGACY_INSTALLINFO_STATUS_DELETED:
851                                         Legacy_ModuleInstallUtils::uninstallBlockByFuncNum($currentBlocks->mBlocks[$idx]->mFuncNum, $module, $log);
852                                         break;
853                         }
854                 }
855         }
856         
857         function smartUpdateAllOfPreferences(&$module, &$log)
858         {
859                 $dirname = $module->get('dirname');
860                 
861                 $fileReader =& new Legacy_ModinfoX2FileReader($dirname);
862                 $latestPreferences =& $fileReader->loadPreferenceInformations();
863                 
864                 $dbReader =& new Legacy_ModinfoX2DBReader($dirname);
865                 $currentPreferences =& $dbReader->loadPreferenceInformations();
866                 
867                 $currentPreferences->update($latestPreferences);
868
869                 //
870                 // Preferences
871                 //
872                 foreach (array_keys($currentPreferences->mPreferences) as $idx) {
873                         switch ($currentPreferences->mPreferences[$idx]->mStatus) {
874                                 case LEGACY_INSTALLINFO_STATUS_UPDATED:
875                                         Legacy_ModuleInstallUtils::updatePreferenceByInfo($currentPreferences->mPreferences[$idx], $module, $log);
876                                         break;
877                                         
878                                 case LEGACY_INSTALLINFO_STATUS_ORDER_UPDATED:
879                                         Legacy_ModuleInstallUtils::updatePreferenceOrderByInfo($currentPreferences->mPreferences[$idx], $module, $log);
880                                         break;
881                                         
882                                 case LEGACY_INSTALLINFO_STATUS_NEW:
883                                         Legacy_ModuleInstallUtils::installPreferenceByInfo($currentPreferences->mPreferences[$idx], $module, $log);
884                                         break;
885                                         
886                                 case LEGACY_INSTALLINFO_STATUS_DELETED:
887                                         Legacy_ModuleInstallUtils::uninstallPreferenceByOrder($currentPreferences->mPreferences[$idx]->mOrder, $module, $log);
888                                         break;
889                         }
890                 }
891                 
892                 //
893                 // Comments
894                 //
895                 foreach (array_keys($currentPreferences->mComments) as $idx) {
896                         switch ($currentPreferences->mComments[$idx]->mStatus) {
897                                 case LEGACY_INSTALLINFO_STATUS_UPDATED:
898                                         Legacy_ModuleInstallUtils::updatePreferenceByInfo($currentPreferences->mComments[$idx], $module, $log);
899                                         break;
900                                         
901                                 case LEGACY_INSTALLINFO_STATUS_ORDER_UPDATED:
902                                         Legacy_ModuleInstallUtils::updatePreferenceOrderByInfo($currentPreferences->mComments[$idx], $module, $log);
903                                         break;
904                                         
905                                 case LEGACY_INSTALLINFO_STATUS_NEW:
906                                         Legacy_ModuleInstallUtils::installPreferenceByInfo($currentPreferences->mComments[$idx], $module, $log);
907                                         break;
908                                         
909                                 case LEGACY_INSTALLINFO_STATUS_DELETED:
910                                         Legacy_ModuleInstallUtils::uninstallPreferenceByOrder($currentPreferences->mComments[$idx]->mOrder, $module, $log);
911                                         break;
912                         }
913                 }
914         }
915         
916         function updateBlockTemplateByInfo(&$info, &$module, &$log)
917         {
918                 $handler =& xoops_getmodulehandler('newblocks', 'legacy');
919                 
920                 $criteria =& new CriteriaCompo();
921                 $criteria->add(new Criteria('dirname', $module->get('dirname')));
922                 $criteria->add(new Criteria('func_num', $info->mFuncNum));
923                 
924                 $blockArr =& $handler->getObjects($criteria);
925                 foreach (array_keys($blockArr) as $idx) {
926                         Legacy_ModuleInstallUtils::clearBlockTemplateForUpdate($blockArr[$idx], $module, $log);
927                         Legacy_ModuleInstallUtils::installBlockTemplate($blockArr[$idx], $module, $log);
928                 }
929         }
930         
931         function updateBlockByInfo(&$info, &$module, &$log)
932         {
933                 $handler =& xoops_getmodulehandler('newblocks', 'legacy');
934                 
935                 $criteria =& new CriteriaCompo();
936                 $criteria->add(new Criteria('dirname', $module->get('dirname')));
937                 $criteria->add(new Criteria('func_num', $info->mFuncNum));
938                 
939                 $blockArr =& $handler->getObjects($criteria);
940                 foreach (array_keys($blockArr) as $idx) {
941                         $blockArr[$idx]->set('options', $info->mOptions);
942                         $blockArr[$idx]->set('name', $info->mName);
943                         $blockArr[$idx]->set('func_file', $info->mFuncFile);
944                         $blockArr[$idx]->set('show_func', $info->mShowFunc);
945                         $blockArr[$idx]->set('edit_func', $info->mEditFunc);
946                         $blockArr[$idx]->set('template', $info->mTemplate);
947                         
948                         if ($handler->insert($blockArr[$idx])) {
949                                 $log->addReport(XCube_Utils::formatMessage('Update {0} block successfully.', $blockArr[$idx]->get('name')));
950                         }
951                         else {
952                                 $log->addError(XCube_Utils::formatMessage('Could not update {0} block.', $blockArr[$idx]->get('name')));
953                         }
954                         
955                         Legacy_ModuleInstallUtils::clearBlockTemplateForUpdate($blockArr[$idx], $module, $log);
956                         Legacy_ModuleInstallUtils::installBlockTemplate($blockArr[$idx], $module, $log);
957                 }
958         }
959         
960         function updatePreferenceByInfo(&$info, &$module, &$log)
961         {
962                 $handler =& xoops_gethandler('config');
963
964                 $criteria =& new CriteriaCompo();               
965                 $criteria->add(new Criteria('conf_modid', $module->get('mid')));
966                 $criteria->add(new Criteria('conf_catid', 0));
967                 $criteria->add(new Criteria('conf_name', $info->mName));
968                 
969                 $configArr =& $handler->getConfigs($criteria);
970                 
971                 if (!(count($configArr) > 0 && is_object($configArr[0]))) {
972                         $log->addError('Execption Error: Could not find config.');
973                         return;
974                 }
975                 
976                 $config =& $configArr[0];
977                 
978                 $config->set('conf_title', $info->mTitle);
979                 $config->set('conf_desc', $info->mDescription);
980                 
981                 //
982                 // Decide whether it changes values.
983                 //
984                 if ($config->get('conf_formtype') != $info->mFormType && $config->get('conf_valuetype') != $info->mValueType) {
985                         $config->set('conf_formtype', $info->mFormType);
986                         $config->set('conf_valuetype', $info->mValueType);
987                         $config->setConfValueForInput($info->mDefault);
988                 }
989                 else {
990                         $config->set('conf_formtype', $info->mFormType);
991                         $config->set('conf_valuetype', $info->mValueType);
992                 }
993                 
994                 $config->set('conf_order', $info->mOrder);
995                 
996                 $optionArr =& $handler->getConfigOptions(new Criteria('conf_id', $config->get('conf_id')));
997                 if (is_array($optionArr)) {
998                         foreach (array_keys($optionArr) as $idx) {
999                                 $handler->_oHandler->delete($optionArr[$idx]);
1000                         }
1001                 }
1002                 
1003                 if (count($info->mOption->mOptions) > 0) {
1004                         foreach (array_keys($info->mOption->mOptions) as $idx) {
1005                                 $option =& $handler->createConfigOption();
1006                                 $option->set('confop_name', $info->mOption->mOptions[$idx]->mName);
1007                                 $option->set('confop_value', $info->mOption->mOptions[$idx]->mValue);
1008                                 $option->set('conf_id', $option->get('conf_id'));
1009                                 $config->setConfOptions($option);
1010                                 unset($option);
1011                         }
1012                 }
1013
1014                 if ($handler->insertConfig($config)) {
1015                         $log->addReport(XCube_Utils::formatMessage("Preference '{0}' is updateded.", $config->get('conf_name')));
1016                 }
1017                 else {
1018                         $log->addError(XCube_Utils::formatMessage("Could not update preference '{0}'.", $config->get('conf_name')));
1019                 }
1020         }
1021
1022         function updatePreferenceOrderByInfo(&$info, &$module, &$log)
1023         {
1024                 $handler =& xoops_gethandler('config');
1025
1026                 $criteria =& new CriteriaCompo();               
1027                 $criteria->add(new Criteria('conf_modid', $module->get('mid')));
1028                 $criteria->add(new Criteria('conf_catid', 0));
1029                 $criteria->add(new Criteria('conf_name', $info->mName));
1030                 
1031                 $configArr =& $handler->getConfigs($criteria);
1032                 
1033                 if (!(count($configArr) > 0 && is_object($configArr[0]))) {
1034                         $log->addError('Execption Error: Could not find config.');
1035                         return;
1036                 }
1037                 
1038                 $config =& $configArr[0];
1039                 
1040                 $config->set('conf_order', $info->mOrder);
1041
1042                 if (!$handler->insertConfig($config)) {
1043                         $log->addError(XCube_Utils::formatMessage("Could not update the order of preference '{0}'.", $config->get('conf_name')));
1044                 }
1045         }
1046         
1047     function installBlockByInfo(&$info, &$module, &$log)
1048     {
1049         $handler =& xoops_gethandler('block');
1050         $block =& $handler->create();
1051
1052         $block->set('mid', $module->get('mid'));
1053         $block->set('func_num', $info->mFuncNum);
1054         $block->set('options', $info->mOptions);
1055         $block->set('name', $info->mName);
1056         $block->set('title', $info->mName);
1057         $block->set('dirname', $module->get('dirname'));
1058         $block->set('func_file', $info->mFuncFile);
1059         $block->set('show_func', $info->mShowFunc);
1060         $block->set('edit_func', $info->mEditFunc);
1061         $block->set('template', $info->mTemplate);
1062         $block->set('block_type', 'M');
1063         $block->set('c_type', 1);
1064
1065         if (!$handler->insert($block)) {
1066             $log->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_COULD_NOT_INSTALL_BLOCK, $block->get('name')));
1067             return false;
1068         }
1069         else {
1070             $log->addReport(XCube_Utils::formatMessage(_AD_LEGACY_MESSAGE_BLOCK_INSTALLED, $block->get('name')));
1071
1072             Legacy_ModuleInstallUtils::installBlockTemplate($block, $module, $log);
1073
1074             return true;
1075         }
1076     }
1077         
1078         /**
1079          * @todo Need a message in the fail case.
1080          */
1081         function uninstallBlockByFuncNum($func_num, &$module, &$log)
1082         {
1083                 $handler =& xoops_getmodulehandler('newblocks', 'legacy');
1084                 
1085                 $criteria =& new CriteriaCompo();
1086                 $criteria->add(new Criteria('dirname', $module->get('dirname')));
1087                 $criteria->add(new Criteria('func_num', $func_num));
1088                 
1089                 $blockArr =& $handler->getObjects($criteria);
1090                 foreach (array_keys($blockArr) as $idx) {
1091                         if ($handler->delete($blockArr[$idx])) {
1092                                 $log->addReport(XCube_Utils::formatMessage(_AD_LEGACY_MESSAGE_UNINSTALLATION_BLOCK_SUCCESSFUL, $blockArr[$idx]->get('name')));
1093                         }
1094                         else {
1095                                 // Uninstall fail
1096                         }
1097                         
1098                         Legacy_ModuleInstallUtils::uninstallBlockTemplate($blockArr[$idx], $module, $log);
1099                 }
1100         }
1101         
1102         /**
1103          * @private
1104          * Uninstalls the block template data specified by $block of $module.
1105          * @param XoopsBlock  $block
1106          * @param XoopsModule $module This object is must the module which has $block.
1107          * @param string      $tplset A name of the template set. If this is null, uninstalls
1108          *                            all templates of any template-sets. 
1109          * @param $log
1110          * @remarks
1111          *     This method users template handlers of the kernel. But, if they are hooked,
1112          *     they may not do something. So, abstraction mechanism is possible enough.
1113          */
1114         function _uninstallBlockTemplate(&$block, &$module, $tplset, &$log)
1115         {
1116                 $handler =& xoops_gethandler('tplfile');
1117                 $criteria =& new CriteriaCompo();
1118                 $criteria->add(new Criteria('tpl_refid', $block->get('bid')));
1119                 $criteria->add(new Criteria('tpl_file', $block->get('template')));
1120                 $criteria->add(new Criteria('tpl_module', $module->get('dirname')));
1121                 $criteria->add(new Criteria('tpl_type', 'block'));
1122                 
1123                 if ($tplset != null) {
1124                         // See 'FIXME'
1125                         $criteria->add(new Criteria('tpl_tplset', $tplset));
1126                 }
1127                 
1128                 $handler->deleteAll($criteria);
1129         }
1130         
1131         function uninstallBlockTemplate(&$block, &$module, &$log)
1132         {
1133                 Legacy_ModuleInstallUtils::_uninstallBlockTemplate($block, $module, null, $log);
1134         }
1135         
1136         /**
1137          * @public
1138          * Removes a template data from only default group of some render-system.
1139          */
1140         function clearBlockTemplateForUpdate(&$block, &$module, &$log)
1141         {
1142                 Legacy_ModuleInstallUtils::_uninstallBlockTemplate($block, $module, 'default', $log);
1143         }
1144
1145         function uninstallPreferenceByOrder($order, &$module, &$log)
1146         {
1147                 $handler =& xoops_gethandler('config');
1148
1149                 $criteria =& new CriteriaCompo();               
1150                 $criteria->add(new Criteria('conf_modid', $module->get('mid')));
1151                 $criteria->add(new Criteria('conf_catid', 0));
1152                 $criteria->add(new Criteria('conf_order', $order));
1153                 
1154                 $configArr =& $handler->getConfigs($criteria);
1155                 
1156                 foreach (array_keys($configArr) as $idx) {
1157                         if ($handler->deleteConfig($configArr[$idx])) {
1158                                 $log->addReport(XCube_Utils::formatMessage("Delete preference '{0}'.", $configArr[$idx]->get('conf_name')));
1159                         }
1160                         else {
1161                                 $log->addError(XCube_Utils::formatMessage("Could not delete preference '{0}'.", $configArr[$idx]->get('conf_name')));
1162                         }
1163                 }
1164         }
1165         
1166         /**
1167          * Executes SQL query as cube style.
1168          */
1169         function DBquery($query, &$module, $log)
1170         {
1171                 require_once XOOPS_MODULE_PATH . "/legacy/admin/class/Legacy_SQLScanner.class.php";
1172                 
1173                 $successFlag = true;
1174                 
1175                 $scanner =& new Legacy_SQLScanner();
1176                 $scanner->setDB_PREFIX(XOOPS_DB_PREFIX);
1177                 $scanner->setDirname($module->get('dirname'));
1178                 $scanner->setBuffer($query);
1179                 $scanner->parse();
1180                 $sqlArr = $scanner->getSQL();
1181
1182                 $root =& XCube_Root::getSingleton();
1183                 
1184                 foreach ($sqlArr as $sql) {             
1185                         if ($root->mController->mDB->query($sql)) {
1186                                 $log->addReport("Success: ${sql}");
1187                                 $successFlag &= true;
1188                         }
1189                         else {
1190                                 $log->addError("Failure: ${sql}");
1191                                 $successFlag = false;
1192                         }
1193                 }
1194                 
1195                 return $successFlag;
1196         }
1197
1198         function deleteAllOfComments(&$module, &$log)
1199         {
1200                 $handler =& xoops_gethandler('comment');
1201                 $criteria =& new Criteria('com_modid', $module->get('mid'));
1202                 $handler->deleteAll($criteria);
1203         }
1204 }
1205
1206 ?>