ここの情報は古いです。ご理解頂いた上でお取り扱いください。

source: OpenPNE3/branches/fukamachi/db-convert-from-2.x/lib/task/openpneUpgradeFrom2Task.class.php @ 12837

Last change on this file since 12837 was 12837, checked in by fukamachi, 14 years ago

db converter - did refactoring for abstraction

File size: 42.5 KB
Line 
1<?php
2
3/**
4 * This file is part of the OpenPNE package.
5 * (c) OpenPNE Project (http://www.openpne.jp/)
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file and the NOTICE file that were distributed with this source code.
9 */
10
11class openpneUpgradeFrom2Task extends sfDoctrineBaseTask
12{
13  private $dsn3                 = '';
14  private $dsn2                 = '';
15  private $username             = '';
16  private $password             = '';
17  private $encryptKey           = '';
18  private $date                 = '0000-00-00 00:00:00';
19  private $mapCategoryIds       = array();
20  private $birthdayProfileId    = null;
21  private $validatorFile        = null;
22  private $unreadDiaryIds       = array();
23
24  private $memoryBuf            = 0;
25
26  protected function configure()
27  {
28    $this->namespace        = 'openpne';
29    $this->name             = 'upgrade-from-2';
30    $this->briefDescription = 'Upgrade from OpenPNE 2.x';
31    $this->detailedDescription = <<<EOF
32The [openpne:upgrade-from-2|INFO] task does things.
33Call it with:
34
35  [php symfony openpne:upgrade-from-2|INFO]
36EOF;
37  }
38
39  protected function execute($arguments = array(), $options = array())
40  {
41    ini_set('memory_limit', '512M');
42
43    // install needed plugins
44    $pluginInstall = new opPluginInstallTask($this->dispatcher, $this->formatter);
45    $pluginInstall->run(array('opDiaryPlugin'), array('--stability=beta'));
46    $pluginInstall->run(array('opCommunityTopicPlugin'), array('--stability=beta'));
47    //$pluginInstall->run(array('opMessagePlugin'), array('--stability=beta'));
48    //$pluginInstall->run(array('opAshiatoPlugin'), array('--stability=beta'));
49
50    // install OpenPNE3
51    $openpneInstall = new openpneInstallTask($this->dispatcher, $this->formatter);
52    $openpneInstall->run();
53
54    // ask OpenPNE2 database
55    while (
56      !($dbname2 = $this->ask('Type old (OpenPNE2) database name'))
57    );
58
59    // ask encrypt key used in OpenPNE2
60    while (
61      !($this->encryptKey = $this->ask('Type encrypt key used in OpenPNE2 (under 56 bytes)'))
62      || (strlen($this->encryptKey) > 56)
63    );
64
65    // get database configuration
66    $file = sfConfig::get('sf_config_dir').'/databases.yml';
67    $config = array();
68    if (file_exists($file))
69    {
70      $config = sfYaml::load($file);
71    }
72    $this->dsn3 = $config['all']['doctrine']['param']['dsn'];
73    $this->dsn2 = preg_replace('/dbname=[^ ;]+/', 'dbname='.$dbname2, $this->dsn3);
74    $this->username = $config['all']['doctrine']['param']['username'];
75    $this->password = $config['all']['doctrine']['param']['password'];
76
77    // create temporary directory
78    $tmpdir = sfConfig::get('sf_cache_dir').'/models_tmp';
79    $this->getFilesystem()->mkdirs($tmpdir);
80
81    // configure Doctrine
82    $manager = Doctrine_Manager::getInstance();
83    $manager->setAttribute(Doctrine::ATTR_QUERY_CLASS, 'Doctrine_Query');
84
85    // generate OpenPNE2 models
86    $this->connectTo2();
87    Doctrine::generateModelsFromDb($tmpdir, array('OpenPNE2'), array('generateBaseClasses' => false, 'baseClassName' => 'sfDoctrineRecord'));
88    $this->connectTo3();
89
90    // generate OpenPNE3 models
91    $this->generateTemporaryBaseModels($tmpdir, $this->getBaseModels());
92
93    // load temporary models
94    Doctrine::loadModels($tmpdir, Doctrine::MODEL_LOADING_AGGRESSIVE);
95
96    $this->date = date('Y-m-d H:i:s');
97
98    // clear db records
99    $tables = array('Blacklist', /*'File', 'FileBin',*/ 'CommunityCategory', 'Community', 'CommunityConfig', 'CommunityMember', 'Member', 'MemberConfig', 'MemberImage', 'Profile', 'ProfileTranslation', 'ProfileOption', 'ProfileOptionTranslation', 'MemberProfile', 'MemberRelationship', 'CommunityTopic', 'CommunityEvent', 'Diary', 'DiaryImage', 'DiaryComment', 'DiaryCommentImage', 'DiaryCommentUnread', /*'Message', 'MessageSendList', 'DeletedMessage', 'MessageFile'*/);
100
101    foreach ($tables as $table)
102    {
103      Doctrine::getTable($table)->createQuery()->delete()->execute();
104    }
105
106    // TODO:convert every tables
107    print "converting AdminUser : ".memory_get_usage()."\n";
108    $this->convertAdminUser();
109    print "converting Blacklist : ".memory_get_usage()."\n";
110    $this->convertBlacklist();
111    //print "converting File and FileBin : ".memory_get_usage()."\n";
112    //$this->convertFileAndFileBin();
113    print "converting CommunityCategory : ".memory_get_usage()."\n";
114    $this->convertCommunityCategory();
115    print "converting Community and CommunityConfig : ".memory_get_usage()."\n";
116    $this->convertCommunityAndCommunityConfig();
117    print "converting Member : ".memory_get_usage()."\n";
118    $this->convertMember();
119    print "converting CommunityMember : ".memory_get_usage()."\n";
120    $this->convertCommunityMember();
121    print "converting MemberConfig : ".memory_get_usage()."\n";
122    $this->convertMemberConfig();
123    print "converting MemberImage : ".memory_get_usage()."\n";
124    $this->convertMemberImage();
125    print "converting Profile : ".memory_get_usage()."\n";
126    $this->convertProfile();
127    print "converting ProfileOption : ".memory_get_usage()."\n";
128    $this->convertProfileOption();
129    //print "converting MemberProfile : ".memory_get_usage()."\n";
130    //$this->convertMemberProfile();
131    print "converting MemberRelationship : ".memory_get_usage()."\n";
132    $this->convertMemberRelationship();
133    print "converting CommunityTopicAndComment : ".memory_get_usage()."\n";
134    $this->convertCommunityTopicAndComment();
135    print "converting CommunityEventAndComment : ".memory_get_usage()."\n";
136    $this->convertCommunityEventAndComment();
137    print "converting DiaryAndImage : ".memory_get_usage()."\n";
138    $this->convertDiaryAndImage();
139    print "converting DiaryCommentAndImage : ".memory_get_usage()."\n";
140    $this->convertDiaryCommentAndImage();
141    //print "converting MessageTables : ".memory_get_usage()."\n";
142    //$this->convertMessageTables();
143
144    // delete models' cache
145    $this->clearCache();
146  }
147
148  /**
149   * Convert Methods
150   */
151  protected function convertAdminUser()
152  {
153    $this->connectTo2();
154    $cAdminUser = Doctrine::getTable('CAdminUser')->find(1);
155    $this->connectTo3();
156    $adminUser = Doctrine::getTable('AdminUser')->find(1);
157
158    $this->update($adminUser, array(
159      'username'   => $cAdminUser->getUsername(),
160      'password'   => $cAdminUser->getPassword(),
161      'created_at' => $this->date,
162      'updated_at' => $this->date,
163    ));
164    $cAdminUser->free();
165  }
166
167  protected function convertBlacklist()
168  {
169    $this->connectTo2();
170    $cBlacklists = Doctrine::getTable('CBlacklist')->findAll();
171    $this->connectTo3();
172
173    foreach ($cBlacklists as $cBlacklist)
174    {
175      $this->insertInto('Blacklist', array(
176        'id'         => $cBlacklist->getCBlacklistId(),
177        'uid'        => $cBlacklist->getEasyAccessId(),
178        'memo'       => $cBlacklist->getInfo(),
179        'created_at' => $this->date,
180        'updated_at' => $this->date,
181      ));
182      $cBlacklist->free();
183    }
184  }
185
186  protected function convertFileAndFileBin()
187  {
188    $this->connectTo3();
189
190    $maxFileId = 0;
191
192    $offset = 0;
193    while ($cFiles = $this->getModelsIterator('CFile', 100, $offset))
194    {
195      foreach ($cFiles as $cFile)
196      {
197        $this->_createFile(array(
198          'id'            => $cFile->getCFileId(),
199          'name'          => $cFile->getFilename(),
200          'original_name' => $cFile->getOriginalFilename(),
201          'date'          => $cFile->getRDatetime(),
202          'bin'           => $cFile->getBin(),
203        ));
204
205        if ($maxFileId < $cFile->getCFileId())
206        {
207          $maxFileId = $cFile->getCFileId();
208        }
209
210        $cFile->free();
211      }
212      $offset += 100;
213    }
214
215    $offset = 0;
216    while ($cImages = $this->getModelsIterator('CImage', 100, $offset))
217    {
218      foreach ($cImages as $cImage)
219      {
220        $this->_createFile(array(
221          'id'   => $maxFileId + $cImage->getCImageId(),
222          'name' => $cImage->getFilename(),
223          'date' => $cImage->getRDatetime(),
224          'bin'  => $cImage->getBin(),
225        ));
226
227        $cImage->free();
228      }
229      $offset += 100;
230    }
231  }
232
233  protected function _createFile($param = array())
234  {
235    // NOTICE: ignore if the file with same name had saved
236    if ($this->getFileByName($param['name']))
237    {
238      return;
239    }
240
241    $paramFile = $param;
242    unset($paramFile['bin']);
243    $file = $this->insertInto('File', $paramFile, true);
244
245    unset($param['name']);
246    unset($param['original_name']);
247    $fileBin = $this->insertInto('FileBin', $param, true);
248
249    $file->setFileBin($fileBin);
250
251    $tmpFilePath = sfConfig::get('sf_cache_dir').'/'.$file->getName();
252    $fh = fopen($tmpFilePath, 'w');
253    fwrite($fh, $param['bin']);
254    fclose($fh);
255    $tmpFile = $this->getValidatorFile()->clean(array('tmp_name' => $tmpFilePath));
256
257    $file->setType($tmpFile->getType());
258
259    $file->save();
260
261    $file->free();
262    $fileBin->free();
263  }
264
265  protected function convertCommunityCategory()
266  {
267    $this->connectTo2();
268    $cCommuCategoryParents = Doctrine::getTable('CCommuCategoryParent')->createQuery()
269      ->orderBy('sort_order')
270      ->execute();
271    $this->connectTo3();
272    $treeCategory = Doctrine::getTable('CommunityCategory')->getTree();
273
274    foreach ($cCommuCategoryParents as $cCategoryParent)
275    {
276      $categoryRoot = $this->insertInto('CommunityCategory', array(
277        'tree_key' => $cCategoryParent->getCCommuCategoryParentId(),
278        'name'     => $cCategoryParent->getName(),
279        'sort_order' => $cCategoryParent->getSortOrder(),
280      ), true);
281
282      $treeCategory->createRoot($categoryRoot);
283
284      $this->connectTo2();
285      $cCategories = Doctrine::getTable('CCommuCategory')->createQuery()
286        ->where('c_commu_category_parent_id = ?', $cCategoryParent->getCCommuCategoryParentId())
287        ->orderBy('sort_order')
288        ->execute();
289      $this->connectTo3();
290
291      foreach ($cCategories as $cCategory)
292      {
293        $category = new TempCommunityCategory();
294        $category->setName($cCategory->getName());
295        if (method_exists($cCategory, 'getIsCreateCommu'))
296        {
297          $category->setIsAllowMemberCommunity($cCategory->getIsCreateCommu());
298        }
299        $category->setSortOrder($cCategory->getSortOrder());
300        $category->getNode()->insertAsLastChildOf($categoryRoot);
301
302        $this->mapCategoryIds[$cCategory->getCCommuCategoryId()] = $category->getId();
303
304        $cCategory->free();
305        $category->free();
306      }
307
308      $categoryRoot->free();
309      $cCategoryParent->free();
310    }
311  }
312
313  protected function convertCommunityAndCommunityConfig()
314  {
315    $this->connectTo3();
316
317    $offset = 0;
318    while ($cCommus = $this->getModelsIterator('CCommu', 100, $offset, 'c_commu_id'))
319    {
320      foreach ($cCommus as $cCommu)
321      {
322        // NOTICE: ignore if already created same name community
323        if ($this->isExist('Community', array('name' => $cCommu->getName())))
324        {
325          $cCommu->free();
326          continue;
327        }
328
329        $param = array(
330            'id'         => $cCommu->getCCommuId(),
331            'name'       => $cCommu->getName(),
332            'created_at' => $cCommu->getRDate(),
333            'updated_at' => $cCommu->getUDatetime(),
334            );
335        if ($file = $this->getFileByName($cCommu->getImageFilename()))
336        {
337          $param['file_id'] = $file->getId();
338          $file->free();
339        }
340        if (array_key_exists($cCommu->getCCommuCategoryId(), $this->mapCategoryIds))
341        {
342          $param['community_category_id'] = $this->mapCategoryIds[$cCommu->getCCommuCategoryId()];
343        }
344        $this->insertInto('Community', $param);
345
346        // CommunityConfigs
347        $param = array(
348            'community_id' => $cCommu->getCCommuId(),
349            'created_at'   => $this->date,
350            'updated_at'   => $this->date,
351            );
352
353        $configs = array();
354        $configs['description'] = $cCommu->getInfo();
355        if (method_exists($cCommu, 'getIsOpen'))
356        {
357          $configs['public_flag'] = $cCommu->getIsOpen();
358        }
359        if (method_exists($cCommu, 'getIsTopic'))
360        {
361          $configs['topic_authority'] = $cCommu->getIsTopic();
362        }
363
364        $this->createConfigs('CommunityConfig', $param, $configs);
365
366        $cCommu->free();
367      }
368      $offset += 100;
369    }
370  }
371
372  protected function convertCommunityMember()
373  {
374    $this->connectTo3();
375
376    $offset = 0;
377    while ($cCommuMembers = $this->getModelsIterator('CCommuMember', 100, $offset))
378    {
379      foreach ($cCommuMembers as $cCommuMember)
380      {
381        // NOTICE: ignore if the community this member joins is not exist
382        if (!$this->isExist('Community', array('id' => $cCommuMember->getCCommuId())))
383        {
384          $cCommuMember->free();
385          continue;
386        }
387
388        $param = array(
389            'id'           => $cCommuMember->getCCommuMemberId(),
390            'community_id' => $cCommuMember->getCCommuId(),
391            'member_id'    => $cCommuMember->getCMemberId(),
392            'created_at'   => $cCommuMember->getRDatetime(),
393            'updated_at'   => $cCommuMember->getRDatetime(),
394            );
395        $this->connectTo2();
396        if (
397            $this->isExist('CCommu', array(
398                'c_commu_id' => $cCommuMember->getCCommuId(),
399                'c_member_id_admin' => $cCommuMember->getCCommuMemberId()
400                ))
401           )
402        {
403          $param['position'] = 'admin';
404        }
405        $this->connectTo3();
406        $this->insertInto('CommunityMember', $param);
407
408        $cCommuMember->free();
409      }
410      $offset += 100;
411    }
412  }
413
414  protected function convertMember()
415  {
416    $this->connectTo3();
417
418    $offset = 0;
419    while ($cMembers = $this->getModelsIterator('CMember', 100, $offset, 'c_member_id'))
420    {
421      foreach ($cMembers as $cMember)
422      {
423        $param = array(
424            'id'         => $cMember->getCMemberId(),
425            'name'       => $cMember->getNickname(),
426            'created_at' => $cMember->getRDate(),
427            'updated_at' => $cMember->getUDatetime(),
428            'is_active'  => !$cMember->getIsLoginRejected(),
429            );
430        if ($cMember->getCMemberIdInvite() && Doctrine::getTable('Member')->find($cMember->getCMemberIdInvite()))
431        {
432          $param['invite_member_id'] = $cMember->getCMemberIdInvite();
433        }
434
435        $this->insertInto('Member', $param);
436        $cMember->free();
437      }
438      $offset += 100;
439    }
440  }
441
442  protected function convertMemberConfig()
443  {
444    $this->connectTo3();
445
446    $offset = 0;
447    while ($cMemberSecures = $this->getModelsIterator('CMemberSecure', 100, $offset))
448    {
449      foreach ($cMemberSecures as $cMemberSecure)
450      {
451        // NOTICE: ignore if the member isn't exist
452        $this->connectTo2();
453        if (!$this->isExist('CMember', array('c_member_id' => $cMemberSecure->getCMemberId())))
454        {
455          $cMemberSecure->free();
456          continue;
457        }
458        $this->connectTo3();
459
460        // common parameters
461        $param = array(
462            'member_id' => $cMemberSecure->getCMemberId(),
463            'created_at' => $this->date,
464            'updated_at' => $this->date,
465            );
466
467        // MemberConfig records
468        $configs = array(
469            'pc_address'     => $this->decrypt($cMemberSecure->getPcAddress()),
470            'password'       => $cMemberSecure->getHashedPassword(),
471            'mobile_address' => $cMemberSecure->getKtaiAddress(),
472            'mobile_uid'     => $cMemberSecure->getEasyAccessId(),
473            'lastLogin'      => $cMember->getAccessDate(),
474            );
475
476        $this->createConfigs('MemberConfig', $param, $configs);
477
478        $cMemberSecure->free();
479        $cMember->free();
480      }
481      $offset += 100;
482    }
483  }
484
485  protected function convertMemberImage()
486  {
487    $this->connectTo3();
488
489    $offset = 0;
490    while ($cMembers = $this->getModelsIterator('CMember', 100, $offset))
491    {
492      foreach ($cMembers as $cMember)
493      {
494        for ($i = 1; $i <= 3; ++$i)
495        {
496          $getImageFilename = 'getImageFilename_'.$i;
497
498          if ($file = $this->getFileByName($cMember->$getImageFilename()))
499          {
500            $this->insertInto('MemberImage', array(
501              'member_id'      => $cMember->getCMemberId(),
502              'file_id'        => $file->getId(),
503              'image_filename' => $cMember->$getImageFilename(),
504              'is_primary'     => $cMember->getImageFilename() === $cMember->$getImageFilename(),
505              'created_at'     => $this->date,
506              'updated_at'     => $this->date,
507            ));
508            $file->free();
509          }
510        }
511
512        $cMember->free();
513      }
514      $offset += 100;
515    }
516  }
517
518  protected function convertProfile()
519  {
520    $this->connectTo3();
521
522    $offset = 0;
523    while ($cProfiles = $this->getModelsIterator('CProfile', 100, $offset))
524    {
525      foreach ($cProfiles as $cProfile)
526      {
527        $this->insertInto('Profile', array(
528              'id'                  => $cProfile->getCProfileId(),
529              'name'                => $cProfile->getName(),
530              'is_required'         => $cProfile->getIsRequired(),
531              'is_edit_public_flag' => $cProfile->getPublicFlagEdit(),
532              'default_public_flag' => $cProfile->getPublicFlagDefault(),
533              'form_type'           => $cProfile->getFormType(),
534              'value_type'          => $cProfile->getValType(),
535              'is_disp_regist'      => $cProfile->getDispRegist(),
536              'is_disp_config'      => $cProfile->getDispConfig(),
537              'is_disp_search'      => $cProfile->getDispSearch(),
538              'value_regexp'        => $cProfile->getValRegexp(),
539              'value_min'           => $cProfile->getValMin(),
540              'value_max'           => $cProfile->getValMax(),
541              'sort_order'          => $cProfile->getSortOrder(),
542              'created_at'          => $this->date,
543              'updated_at'          => $this->date,
544              ));
545
546        $profileTranslation = Doctrine::getTable('Profile')->createQuery('p')
547          ->leftJoin('p.Translation t WITH t.lang = "ja_JP"')
548          ->where('p.id = ?', $cProfile->getCProfileId())
549          ->fetchOne();
550
551        $param = array(
552            'caption' => $cProfile->getCaption(),
553            'lang'    => 'ja_JP',
554            );
555        $param['info'] = $cProfile->getInfo();
556
557        $this->update($profileTranslation, $param);
558
559        $cProfile->free();
560        $profileTranslation->free();
561      }
562      $offset += 100;
563    }
564
565    $this->insertInto('Profile', array(
566      'name'                => 'birthday',
567      'is_required'         => true,
568      'is_edit_public_flag' => false,
569      'default_public_flag' => true,
570      'form_type'           => 'date',
571      'value_type'          => 'string',
572      'is_disp_regist'      => true,
573      'is_disp_config'      => true,
574      'is_disp_search'      => true,
575      'value_min'           => '-100years',
576      'value_max'           => 'now',
577      'sort_order'          => 1,
578      'created_at'          => $this->date,
579      'updated_at'          => $this->date,
580    ));
581
582    $profileBirthdayTranslation = Doctrine::getTable('Profile')->createQuery('p')
583      ->leftJoin('p.Translation t WITH t.lang = "ja_JP"')
584      ->orderBy('id desc')
585      ->fetchOne();
586
587    $this->birthdayProfileId = $profileBirthdayTranslation->getId();
588
589    $this->update($profileBirthdayTranslation, array(
590      'caption' => '誕生日',
591      'lang'    => 'ja_JP',
592    ));
593  }
594
595  protected function convertProfileOption()
596  {
597    $this->connectTo2();
598    $cProfileOptions = Doctrine::getTable('CProfileOption')->findAll();
599    $this->connectTo3();
600
601    $offset = 0;
602    while ($cProfileOptions = $this->getModelsIterator('CProfileOption', 100, $offset))
603    {
604      foreach ($cProfileOptions as $cProfileOption)
605      {
606        $this->_createProfileOption(array(
607              'id'         => $cProfileOption->getCProfileOptionId(),
608              'profile_id' => $cProfileOption->getCProfileId(),
609              'sort_order' => $cProfileOption->getSortOrder(),
610              ), $cProfileOption->getValue());
611        $cProfileOption->free();
612      }
613      $offset += 100;
614    }
615
616    $this->_createProfileOption(array(
617          'profile_id' => $this->birthdayProfileId,
618          'sort_order' => 0,
619          ));
620  }
621
622  protected function _createProfileOption($param = array(), $translation = null)
623  {
624    $profileOption = $this->insertInto('ProfileOption', $param, true); 
625
626    if (!is_null($translation))
627    {
628      $profileOptionTranslation = Doctrine::getTable('ProfileOption')->createQuery('p')
629        ->leftJoin('p.Translation t WITH t.lang = "ja_JP"')
630        ->where('p.id = ?', $profileOption->getId())
631        ->fetchOne();
632
633      $profileOptionTranslation->setValue($translation);
634      $profileOptionTranslation->save();
635
636      $profileOptionTranslation->free();
637    }
638
639    $profileOption->free();
640  }
641
642  protected function convertMemberProfile()
643  {
644    $this->connectTo3();
645    $treeProfile = Doctrine::getTable('MemberProfile')->getTree();
646
647    $offset = 0;
648    while ($cMemberProfiles = $this->getModelsIterator('CMemberProfile', 100, $offset))
649    {
650      foreach ($cMemberProfiles as $cMemberProfile)
651      {
652        // NOTICE: ignore if the member isn't exist
653        if (!$this->isExist('Member', array('id' => $cMemberProfile->getCMemberId())))
654        {
655          $cMemberProfile->free();
656          continue;
657        }
658
659        $memberProfile = $this->_createAndGetMemberProfile(array(
660          'member_id'         => $cMemberProfile->getCMemberId(),
661          'profile_id'        => $cMemberProfile->getCProfileId(),
662          'profile_option_id' => $cMemberProfile->getCProfileOptionId(),
663          'value'             => $cMemberProfile->getValue(),
664          'public_flag'       => $cMemberProfile->getPublicFlag(),
665        ));
666
667        if ($memberProfile)
668        {
669          $memberProfile->save();
670          $memberProfile->free();
671        }
672
673        $cMemberProfile->free();
674      }
675      $offset += 100;
676    }
677
678    unset($cMemberProfiles);
679    $this->connectTo2()->clear();
680    $this->connectTo3()->clear();
681
682    $offset = 0;
683    while ($cMembers = $this->getModelsIterator('CMember', 100, $offset))
684    {
685      foreach ($cMembers as $cMember)
686      {
687        $birthdayRoot = $this->_createAndGetMemberProfile(array(
688          'member_id'   => $cMember->getCMemberId(),
689          'profile_id'  => $this->birthdayProfileId,
690        ));
691
692        $treeProfile->createRoot($birthdayRoot);
693
694        $birthdayYear = $this->_createAndGetMemberProfile(array(
695          'member_id'   => $cMember->getCMemberId(),
696          'profile_id'  => $this->birthdayProfileId,
697          'value'       => $cMember->getBirthYear(),
698          'public_flag' => $cMember->getPublicFlagBirthYear(),
699        ));
700        $birthdayMonth = $this->_createAndGetMemberProfile(array(
701          'member_id'    => $cMember->getCMemberId(),
702          'profile_id'   => $this->birthdayProfileId,
703          'value'        => $cMember->getBirthMonth(),
704          'public_flag'  => $cMember->getPublicFlagBirthMonthDay(),
705        ));
706        $birthdayDay = $this->_createAndGetMemberProfile(array(
707          'member_id'    => $cMember->getCMemberId(),
708          'profile_id'   => $this->birthdayProfileId,
709          'value'        => $cMember->getBirthDay(),
710          'public_flag'  => $cMember->getPublicFlagBirthMonthDay(),
711        ));
712
713        $birthdayDay->getNode()->insertAsLastChildOf($birthdayRoot);
714        $birthdayMonth->getNode()->insertAsLastChildOf($birthdayRoot);
715        $birthdayYear->getNode()->insertAsLastChildOf($birthdayRoot);
716
717        $birthdayYear->free();
718        $birthdayMonth->free();
719        $birthdayDay->free();
720        $cMember->free();
721        $birthdayRoot->free();
722      }
723      $offset += 100;
724    }
725  }
726
727  protected function _createAndGetMemberProfile($param = array())
728  {
729    // NOTICE: ignore if c_member_profile.c_profile_id = 0
730    if (!array_key_exists('profile_id', $param) || !$param['profile_id'])
731    {
732      return;
733    }
734
735    $param['created_at'] = $this->date;
736    $param['updated_at'] = $this->date;
737
738    return $this->insertInto('MemberProfile', $param, true);
739  }
740
741  protected function convertMemberRelationship()
742  {
743    $this->connectTo3();
744
745    $offset = 0;
746    while ($cFriends = $this->getModelsIterator('CFriend', 100, $offset))
747    {
748      foreach ($cFriends as $cFriend)
749      {
750        $this->_updateMemberRelationship(array(
751              'member_id_from' => $cFriend->getCMemberIdFrom(),
752              'member_id_to'   => $cFriend->getCMemberIdTo(),
753              'datetime'       => $cFriend->getRDatetime(),
754              'is_friend'      => true,
755              ));
756        $cFriend->free();
757      }
758      $offset += 100;
759    }
760
761    $offset = 0;
762    while ($cFriendConfirms = $this->getModelsIterator('CFriendConfirm', 100, $offset))
763    {
764      foreach ($cFriendConfirms as $cFriendConfirm)
765      {
766        $this->_updateMemberRelationship(array(
767              'member_id_from' => $cFriendConfirm->getCMemberIdFrom(),
768              'member_id_to'   => $cFriendConfirm->getCMemberIdTo(),
769              'datetime'       => $cFriendConfirm->getRDatetime(),
770              'is_friend_pre'  => true,
771              ));
772        $cFriendConfirm->free();
773      }
774      $offset += 100;
775    }
776
777    $offset = 0;
778    while ($cAccessBlocks = $this->getModelsIterator('CAccessBlock', 100, $offset))
779    {
780      foreach ($cAccessBlocks as $cAccessBlock)
781      {
782        $this->_updateMemberRelationship(array(
783              'member_id_from'  => $cAccessBlock->getCMemberId(),
784              'member_id_to'    => $cAccessBlock->getCMemberIdBlock(),
785              'datetime'        => $cAccessBlock->getRDatetime(),
786              'is_access_block' => true,
787              ));
788        $cAccessBlock->free();
789      }
790      $offset += 100;
791    }
792  }
793
794  protected function _updateMemberRelationship($param = array())
795  {
796    // NOTICE: ignore if member_id_from is equal to member_id_to
797    if ($param['member_id_from'] === $param['member_id_to'])
798    {
799      return;
800    }
801
802    $memberIds = array(
803      'member_id_from' => $param['member_id_from'],
804      'member_id_to'   => $param['member_id_to'],
805    );
806    if ($memberRelationship = $this->selectOne('MemberRelationship', $memberIds))
807    {
808      unset($param['member_id_from']);
809      unset($param['member_id_to']);
810      $this->update($memberRelationship, $param);
811      $memberRelationship->free();
812    }
813    else
814    {
815      $this->insertInto('MemberRelationship', $param);
816    }
817  }
818
819  protected function convertCommunityTopicAndComment()
820  {
821    $this->connectTo2();
822    $cCommuTopics = Doctrine::getTable('CCommuTopic')->createQuery()
823      ->where('event_flag = 0')
824      ->execute();
825    $this->connectTo3();
826
827    foreach ($cCommuTopics as $cCommuTopic)
828    {
829      $param = array(
830        'id'           => $cCommuTopic->getCCommuTopicId(),
831        'community_id' => $cCommuTopic->getCCommuId(),
832        'name'         => $cCommuTopic->getName(),
833        'topic_updated_at' => $cCommuTopic->getUDatetime(),
834        'created_at'   => $cCommuTopic->getRDatetime(),
835        'updated_at'   => $cCommuTopic->getUDatetime(),
836      );
837      if (Doctrine::getTable('Member')->find($cCommuTopic->getCMemberId()))
838      {
839        $param['member_id'] = $cCommuTopic->getCMemberId();
840      }
841
842      $communityTopic = $this->insertInto('CommunityTopic', $param, true);
843
844      $this->connectTo2();
845      $comments = Doctrine::getTable('CCommuTopicComment')->createQuery()
846        ->where('c_commu_topic_id = ?', $cCommuTopic->getCCommuTopicId())
847        ->orderBy('number')
848        ->execute();
849      $this->connectTo3();
850
851      foreach ($comments as $comment)
852      {
853        if (0 === $comment->getNumber())
854        {
855          $communityTopic->setBody($comment->getBody());
856        }
857        else
858        {
859          $this->insertInto('CommunityTopicComment', array(
860            'community_topic_id' => $comment->getCCommuTopicId(),
861            'member_id'          => $comment->getCMemberId(),
862            'body'               => $comment->getBody(),
863            'created_at'         => $comment->getRDatetime(),
864            'updated_at'         => $comment->getRDatetime(),
865          ));
866        }
867        $comment->free();
868      }
869
870      $communityTopic->save();
871      $cCommuTopic->free();
872      $communityTopic->free();
873    }
874  }
875
876  protected function convertCommunityEventAndComment()
877  {
878    $this->connectTo2();
879    $cCommuEvents = Doctrine::getTable('CCommuTopic')->createQuery()
880      ->where('event_flag = 1')
881      ->execute();
882    $this->connectTo3();
883
884    foreach ($cCommuEvents as $cCommuEvent)
885    {
886      $param = array(
887        'id'           => $cCommuEvent->getCCommuTopicId(),
888        'community_id' => $cCommuEvent->getCCommuId(),
889        'name'         => $cCommuEvent->getName(),
890        'event_updated_at' => $cCommuEvent->getUDatetime(),
891        'open_date'    => $cCommuEvent->getOpenDate(),
892        'open_date_comment' => $cCommuEvent->getOpenDateComment(),
893        'application_deadline' => $cCommuEvent->getInvitePeriod(),
894        'capacity'         => $cCommuEvent->getCapacity(),
895        'created_at'       => $cCommuEvent->getRDatetime(),
896        'updated_at'       => $cCommuEvent->getUDatetime(),
897      );
898      if (Doctrine::getTable('Member')->find($cCommuEvent->getCMemberId()))
899      {
900        $param['member_id'] = $cCommuEvent->getCMemberId();
901      }
902
903      $communityEvent = $this->insertInto('CommunityEvent', $param, true);
904
905      $this->connectTo2();
906      $comments = Doctrine::getTable('CCommuTopicComment')->createQuery()
907        ->where('c_commu_topic_id = ?', $cCommuEvent->getCCommuTopicId())
908        ->orderBy('number')
909        ->execute();
910      $this->connectTo3();
911
912      foreach ($comments as $comment)
913      {
914        if (0 === $comment->getNumber())
915        {
916          $communityEvent->setBody($comment->getBody());
917        }
918        else
919        {
920          $this->insertInto('CommunityEventComment', array(
921            'community_event_id' => $comment->getCCommuTopicId(),
922            'member_id'          => $comment->getCMemberId(),
923            'body'               => $comment->getBody(),
924            'created_at'         => $comment->getRDatetime(),
925            'updated_at'         => $comment->getRDatetime(),
926          ));
927        }
928        $comment->free();
929      }
930
931      if ($cCommuEvent->getOpenPrefId())
932      {
933        $this->connectTo2();
934        $pref = Doctrine::getTable('CProfilePref')->find($cCommuEvent->getOpenPrefId())->getPref();
935        $this->connectTo3();
936        if ($cCommuEvent->getOpenPrefComment())
937        {
938          $pref .= sprintf(' (%s)', $cCommuEvent->getOpenPrefComment());
939        }
940        $communityEvent->setArea($pref);
941      }
942
943      $communityEvent->save();
944      $cCommuEvent->free();
945      $communityEvent->free();
946    }
947  }
948
949  protected function convertDiaryAndImage()
950  {
951    $this->connectTo3();
952
953    $offset = 0;
954    while ($cDiaries = $this->getModelsIterator('CDiary', 100, $offset))
955    {
956      foreach ($cDiaries as $cDiary)
957      {
958        $this->connectTo2();
959        // NOTICE: ignore if the member isn't exist
960        if (!$this->isExist('CMember', array('c_member_id' => $cDiary->getCMemberId())))
961        {
962          $cDiary->free();
963          continue;
964        }
965        $this->connectTo3();
966
967        $diary = $this->insertInto('Diary', array(
968          'id'          => $cDiary->getCDiaryId(),
969          'member_id'   => $cDiary->getCMemberId(),
970          'title'       => $cDiary->getSubject(),
971          'body'        => $cDiary->getBody(),
972          'public_flag' => $cDiary->getPublicFlag(),
973          'created_at'  => $cDiary->getPublicFlag(),
974          'updated_at'  => $cDiary->getUDatetime(),
975        ), true);
976
977        for ($i = 1; $i <= 3; ++$i)
978        {
979          $getImageFilename = 'getImageFilename_'.$i;
980          if ($file = $this->getFileByName($cDiary->$getImageFilename()))
981          {
982            $diary->setHasImages(true);
983            $this->insertInto('DiaryImage', array(
984              'diary_id' => $diary->getId(),
985              'number'   => $i,
986              'file_id'  => $file->getId(),
987            ));
988            $file->free();
989          }
990        }
991
992        if (method_exists($diary, 'getIsChecked') && !$diary->getIsChecked())
993        {
994          array_push($this->unreadDiaryIds, $diary->getId());
995        }
996
997        $diary->save();
998        $cDiary->free();
999        $diary->free();
1000      }
1001      $offset += 100;
1002    }
1003  }
1004
1005  protected function convertDiaryCommentAndImage()
1006  {
1007    $this->connectTo2();
1008    $cDiaryComments = Doctrine::getTable('CDiaryComment')->findAll();
1009    $this->connectTo3();
1010
1011    $offset = 0;
1012    while ($cDiaryComments = $this->getModelsIterator('CDiaryComment', 100, $offset))
1013    {
1014      foreach ($cDiaryComments as $cDiaryComment)
1015      {
1016        // NOTICE: ignore if that's diary isn't exist
1017        if (!Doctrine::getTable('Diary')->find($cDiaryComment->getCDiaryId()))
1018        {
1019          continue;
1020        }
1021
1022        // NOTICE: ignore if that's member isn't exist
1023        if (!Doctrine::getTable('Member')->find($cDiaryComment->getCMemberId()))
1024        {
1025          continue;
1026        }
1027
1028        $this->insertInto('DiaryComment', array(
1029          'id'         => $cDiaryComment->getCDiaryCommentId(),
1030          'diary_id'   => $cDiaryComment->getCDiaryId(),
1031          'member_id'  => $cDiaryComment->getCMemberId(),
1032          'number'     => $cDiaryComment->getNumber(),
1033          'body'       => $cDiaryComment->getBody(),
1034          'created_at' => $cDiaryComment->getRDatetime(),
1035          'updated_at' => $cDiaryComment->getRDatetime(),
1036        ));
1037
1038        for ($i = 1; $i <= 3; ++$i)
1039        {
1040          $getImageFilename = 'getImageFilename_'.$i;
1041          if ($file = $this->getFileByName($cDiaryComment->$getImageFilename()))
1042          {
1043            $this->insertInto('DiaryCommentImage', array(
1044              'diary_comment_id' => $cDiaryComment->getCDiaryCommentId(),
1045              'file_id'          => $file->getId(),
1046            ));
1047            $file->free();
1048          }
1049        }
1050
1051        if (array_search($cDiaryComment->getCDiaryCommentId(), $this->unreadDiaryIds))
1052        {
1053          $this->insertInto('DiaryCommentUnread', array(
1054            'diary_id'  => $cDiaryComment->getCDiaryId(),
1055            'member_id' => $cDiaryComment->getCMemberId(),
1056          ));
1057        }
1058
1059        $cDiaryComment->free();
1060      }
1061      $offset += 100;
1062    }
1063  }
1064
1065  protected function convertMessageTables()
1066  {
1067    $this->connectTo3();
1068
1069    $offset = 0;
1070    while ($cMessages = $this->getModelsIterator('CMessage', 100, $offset))
1071    {
1072      foreach ($cMessages as $cMessage)
1073      {
1074        $this->insertInto('Message', array(
1075          'id'                => $cMessage->getCMessageId(),
1076          'member_id'         => $cMessage->getCMemberIdFrom(),
1077          'subject'           => $cMessage->getSubject(),
1078          'body'              => $cMessage->getBody(),
1079          'is_deleted'        => $cMessage->getIsDeletedFrom(),
1080          'is_send'           => $cMessage->getIsSend(),
1081          'return_message_id' => $cMessage->getHensinmotoCMessageId(),
1082          'message_type_id'   => $cMessage->getIsSyoudaku() ? 2 : 1,
1083          'created_at'        => $cMessage->getRDatetime(),
1084          'updated_at'        => $cMessage->getRDatetime(),
1085        ));
1086
1087        // create MessageSendList
1088        $messageSendList = $this->insertInto('MessageSendList', array(
1089          'member_id'  => $cMessage->getCMemberIdTo(),
1090          'message_id' => $cMessage->getCMessageId(),
1091          'is_read'    => $cMessage->getIsRead(),
1092          'is_deleted' => $cMessage->getIsDeletedTo(),
1093          'created_at' => $cMessage->getRDatetime(),
1094          'updated_at' => $cMessage->getRDatetime(),
1095        ), true);
1096
1097        // create DeletedMessage
1098        if ($cMessage->getIsDeletedTo())
1099        {
1100          $this->insertInto('DeletedMessage', array(
1101            'member_id'            => $cMessage->getCMemberIdTo(),
1102            'message_id'           => $cMessage->getCMessageId(),
1103            'message_send_list_id' => $messageSendList->getId(),
1104            'is_deleted'           => $cMessage->getIsKanzenSakujoTo(),
1105            'datetime'             => $cMessage->getRDatetime(),
1106          ));
1107        }
1108        if ($cMessage->getIsDeletedFrom())
1109        {
1110          $this->insertInto('DeletedMessage', array(
1111            'member_id'            => $cMessage->getCMemberIdFrom(),
1112            'message_id'           => $cMessage->getCMessageId(),
1113            'message_send_list_id' => $messageSendList->getId(),
1114            'is_deleted'           => $cMessage->getIsKanzenSakujoFrom(),
1115            'datetime'             => $cMessage->getRDatetime(),
1116          ));
1117        }
1118
1119        // create MessageFile
1120        $param = array(
1121          'message_id' => $cMessage->getCMessageId(),
1122          'created_at' => $this->date,
1123          'updated_at' => $this->date,
1124        );
1125        for ($i = 1; $i <= 3; ++$i)
1126        {
1127          $getImageFilename = 'getImageFilename_'.$i;
1128          if ($file = $this->getFileByName($cMessage->$getImageFilename()))
1129          {
1130            $this->insertInto('MessageFile', array_merge($param, array('file_id' => $file->getId())));
1131            $file->free();
1132          }
1133        }
1134        if ($file = $this->getFileByName($cMessage->getFilename()))
1135        {
1136          $this->insertInto('MessageFile', array_merge($param, array('file_id' => $file->getId())));
1137          $file->free();
1138        }
1139
1140        $messageSendList->free();
1141      }
1142
1143      foreach ($cMessages as $cMessage)
1144      {
1145        $message = Doctrine::getTable('Message')->find($cMessage->getCMessageId());
1146        $message->setThreadMessageId($this->_getThreadMessageId($cMessage->getCMessageId()));
1147        $message->save();
1148        $message->free();
1149        $cMessage->free();
1150      }
1151      $offset += 100;
1152    }
1153  }
1154
1155  protected function _getThreadMessageId($messageId)
1156  {
1157    if (!$messageId)
1158    {
1159      return;
1160    }
1161
1162    $message = Doctrine::getTable('Message')->find($messageId);
1163    $returnMessageId = $message->getReturnMessageId();
1164    $message->free();
1165
1166    return $returnMessageId
1167      ? $this->_getThreadMessageId($returnMessageId)
1168      : $messageId;
1169  }
1170
1171  /**
1172   * Functions
1173   */
1174  protected function clearCache()
1175  {
1176    $cc = new sfCacheClearTask($this->dispatcher, $this->formatter);
1177    $cc->run();
1178  }
1179
1180  protected function connectTo3()
1181  {
1182    return Doctrine_Manager::connection(new PDO($this->dsn3, $this->username, $this->password), 'doctrine');
1183  }
1184
1185  protected function connectTo2()
1186  {
1187    return Doctrine_Manager::connection(new PDO($this->dsn2, $this->username, $this->password), 'OpenPNE2');
1188  }
1189
1190  protected function getFileByName($name = null)
1191  {
1192    if ($name)
1193    {
1194      return $this->selectOne('File', array('name' => $name));
1195    }
1196  }
1197
1198  protected function getModelsIterator($table, $limit = 100, $offset = 0, $orderBy = null)
1199  {
1200    $this->connectTo2();
1201    $q = Doctrine::getTable($table)->createQuery()
1202      ->limit($limit)
1203      ->offset($offset);
1204    if (!is_null($orderBy))
1205    {
1206      $q->orderBy($orderBy);
1207    }
1208    $cModels = $q->execute();
1209    $this->connectTo3();
1210
1211    return $cModels->count() ? $cModels : false;
1212  }
1213
1214  protected function createConfigs($tableName, $param, $configs)
1215  {
1216    foreach ($configs as $name => $value)
1217    {
1218      if (!$value)
1219      {
1220        continue;
1221      }
1222
1223      $this->insertInto($tableName, array_merge($param, array(
1224        'name'  => $name,
1225        'value' => $value,
1226      )));
1227    }
1228  }
1229
1230  /**
1231   * Initialize
1232   */
1233  protected function getBaseModelsDirectories($dir)
1234  {
1235    if (!is_dir($dir) || '.' === basename($dir))
1236    {
1237      return;
1238    }
1239    elseif ('base' === basename($dir))
1240    {
1241      return array($dir);
1242    }
1243 
1244    $baseDirs = array();
1245    foreach (scandir($dir) as $file)
1246    {
1247      if (0 === strpos($file, '.'))
1248      {
1249        continue;
1250      }
1251      if ($base = $this->getBaseModelsDirectories($dir.'/'.$file))
1252      {
1253        $baseDirs = array_merge($baseDirs, $base);
1254      }
1255    }
1256 
1257    return $baseDirs;
1258  }
1259
1260  protected function getBaseModels()
1261  {
1262    $baseDirs = $this->getBaseModelsDirectories(sfConfig::get('sf_lib_dir').'/model/doctrine');
1263    $baseModels = array();
1264    foreach ($baseDirs as $dir)
1265    {
1266      foreach (scandir($dir) as $file)
1267      {
1268        if (!is_dir($file) && 0 !== strpos($file, '.'))
1269        {
1270          array_push($baseModels, $dir.'/'.$file);
1271        }
1272      }
1273    }
1274
1275    return $baseModels;
1276  }
1277
1278  protected function generateTemporaryBaseModels($tmpdir, $baseModels = array())
1279  {
1280    foreach ($baseModels as $model)
1281    {
1282      $className = basename($model, '.class.php');
1283      $className = preg_replace('/^Base/', 'Temp', $className);
1284      $contents = file_get_contents($model);
1285      $contents
1286        = preg_replace(
1287          '/\nabstract class Base.+? extends opDoctrineRecord\n/',
1288          "\nclass ".$className." extends sfDoctrineRecord\n",
1289          $contents
1290        );
1291
1292      $fp = fopen($tmpdir.'/'.$className.'.php', 'w');
1293      fwrite($fp, $contents);
1294      fclose($fp);
1295    }
1296  }
1297
1298  /**
1299   * Utilities
1300   */
1301  protected function getValidatorFile()
1302  {
1303    if ($this->validatorFile === null)
1304    {
1305      $this->validatorFile = new sfValidatorFile();
1306    }
1307
1308    return $this->validatorFile;
1309  }
1310
1311  protected function makeCamelCase($string = '')
1312  {
1313    $camel = '';
1314    $words = explode('_', $string);
1315    $camel .= array_shift($words);
1316    foreach ($words as $word)
1317    {
1318      $camel .= ucfirst($word);
1319    }
1320
1321    return $camel;
1322  }
1323
1324  protected function decrypt($str)
1325  {
1326    if (!$str)
1327    {
1328      return '';
1329    }
1330
1331    $str = base64_decode($str);
1332    $bf =& $this->get_crypt_blowfish();
1333
1334    return rtrim($bf->decrypt($str));
1335  }
1336
1337  // FIXME : Cannot use old blowfish library
1338  protected function &get_crypt_blowfish()
1339  {
1340    static $singleton;
1341    if (empty($singleton))
1342    {
1343      include_once 'Crypt/Blowfish.php';
1344      $singleton = new Crypt_Blowfish($this->encryptKey);
1345    }
1346
1347    return $singleton;
1348  }
1349
1350  protected function printMemoryUsage($msg = 'point')
1351  {
1352    $memory = memory_get_usage();
1353    $diff = $memory - $this->memoryBuf;
1354    printf(
1355      "%s: %d (%s)\n",
1356      $msg, $memory, $diff > 0 ? '+'.$diff : $diff
1357    );
1358    $this->memoryBuf = $memory;
1359  }
1360
1361  /**
1362   * SQL like operations
1363   */
1364  protected function selectOne($tableName, $where = array())
1365  {
1366    $q = Doctrine::getTable($tableName)->createQuery();
1367
1368    foreach ($where as $key => $value)
1369    {
1370      $q->andWhere($key.' = ?', $value);
1371    }
1372
1373    return $q->fetchOne();
1374  }
1375
1376  protected function isExist($tableName, $where = array())
1377  {
1378    return (boolean) $this->selectOne($tableName, $where);
1379  }
1380
1381  protected function insertInto($tableName, $param = array(), $returnRecord = false)
1382  {
1383    $className = 'Temp'.$tableName;
1384    $record = new $className();
1385
1386    return $this->update($record, $param, $returnRecord);
1387  }
1388
1389  protected function update(&$record, $param = array(), $returnRecord = false)
1390  {
1391    foreach ($param as $field => $value)
1392    {
1393      $methodName = $this->makeCamelCase('set'.$field);
1394      $record->{$this->makeCamelCase('set'.$field)}($value);
1395    }
1396
1397    if ($returnRecord)
1398    {
1399      return $record;
1400    }
1401    $record->save();
1402    $record->free();
1403  }
1404}
Note: See TracBrowser for help on using the repository browser.