/**
  * Rename action content
  *
  * @param string $path 
  * @param string $name 
  * @param string $renamed 
  * @return boolean
  * @author Sergey Startsev
  */
 public static function renameActionContent($path, $name, $renamed)
 {
     $actions = file_get_contents($path);
     $actions = str_ireplace("{$name}Actions", "{$renamed}Actions", $actions);
     $actions = str_ireplace("@subpackage {$name}", "@subpackage {$renamed}", $actions);
     $actions = str_ireplace("{$name} actions", "{$renamed} actions", $actions);
     $actions = str_ireplace("{$name} module", "{$renamed} module", $actions);
     return afStudioUtil::writeFile($path, $actions);
 }
 public function save()
 {
     $confData = $this->databaseConfTemplate;
     $param =& $confData['all']['propel']['param'];
     $param['dsn'] = $this->buildDsn($confData['all']['propel']['param']['dsn']);
     $param['username'] = $this->params['username'];
     $param['password'] = $this->params['password'];
     $param['persistent'] = isset($this->params['persistent']) ? true : false;
     $param['pooling'] = isset($this->params['pooling']) ? true : false;
     afStudioUtil::writeFile($this->databaseConfFilePath, $this->dumpYaml($confData));
     afsNotificationPeer::log('Database Settings have been modified', 'afStudioConf');
     if (is_readable($this->databaseConfFilePath)) {
         $result = true;
     } else {
         $result = false;
     }
     return $result;
 }
 public function build()
 {
     if ($this->request->hasParameter('type') && $this->request->getParameter('type') == 'save') {
         $params = $this->request->getPostParameters();
         unset($params['type']);
         $params['autodeploy'] = !isset($params['autodeploy']) ? false : true;
         $params['url'] = afStudioUtil::getHost();
         $this->setProjectParams($params);
         afStudioUtil::writeFile($this->projectConfFilePath, $this->dumpYaml($this->projectConfTemplate));
         $result['success'] = true;
         $result['message'] = 'Project Settings saved successfully';
         afsNotificationPeer::log('Project Settings have been modified', 'afStudioConf');
     } else {
         $result['success'] = true;
         $result['data'] = $this->getProjectParams();
     }
     return json_encode($result);
 }
 /**
  * Rename action name inside module
  *
  * @param string $name 
  * @param string $renamed 
  * @param string $module
  * @param string $place 
  * @param string $type 
  * @return boolean
  * @author Sergey Startsev
  */
 public static function renameAction($name, $renamed, $module, $place, $type)
 {
     $root = afStudioUtil::getRootDir();
     $afConsole = afStudioConsole::getInstance();
     $console = '';
     $module_dir = "{$root}/{$type}s/{$place}/modules/{$module}";
     $action_dir = "{$module_dir}/actions";
     $predictActions = "{$name}Action.class.php";
     $predictActionsPath = "{$module_dir}/actions/{$predictActions}";
     $oldName = "{$name}Action.class.php";
     $newName = "{$renamed}Action.class.php";
     $oldPath = "{$action_dir}/{$oldName}";
     $newPath = "{$action_dir}/{$newName}";
     if (file_exists($oldPath)) {
         $action = file_get_contents($oldPath);
         $action = str_ireplace("{$name}Action", "{$renamed}Action", $action);
         afStudioUtil::writeFile($oldPath, $action);
         return afsFileSystem::create()->rename($oldPath, $newPath);
     }
     return true;
 }
 /**
  * Updating template
  *
  * @return afResponse
  * @author Radu Topala
  * @author Sergey Startsev
  */
 public function processUpdate()
 {
     $response = afResponseHelper::create();
     if (!$this->hasParameter('template')) {
         return $response->success(false)->message("You should define template name");
     }
     $templateName = strtolower($this->getParameter('template'));
     $projectPath = sfConfig::get('sf_root_dir');
     $projectYmlName = '/config/project.yml';
     $projectYmlPath = $projectPath . $projectYmlName;
     $appFlowerPluginPath = $projectPath . '/plugins/appFlowerPlugin/';
     $appFlowerStudioPluginPath = $projectPath . '/plugins/appFlowerStudioPlugin/';
     $projectYml = sfYaml::load($projectYmlPath);
     $pluginTemplateYml = sfYaml::load(sfConfig::get('sf_root_dir') . '/plugins/appFlowerStudioPlugin/config/template.yml');
     if (file_exists($appFlowerPluginPath) && file_exists($appFlowerStudioPluginPath)) {
         $projectYml['project']['template'] = in_array($templateName, $pluginTemplateYml['template']['types']) ? $templateName : $pluginTemplateYml['template']['default'];
         if (afStudioUtil::writeFile($projectYmlPath, sfYaml::dump($projectYml, 4))) {
             return $response->success(true)->message('Template was set to ' . ucfirst($templateName));
         } else {
             return $response->success(false)->message('File ' . $projectYmlName . ' is not writable!');
         }
     }
     return $response->success(false)->message("The selected path doesn't contain any valid AppFlower project!");
 }
 /**
  * Setting user collection
  * 
  * @param   array $definition 
  * @author Sergey Startsev
  */
 public static function setCollection(array $definition, $filePath = false)
 {
     afStudioUtil::writeFile(self::getCollectionPath($filePath), sfYaml::dump($definition));
 }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connections = $this->getConnections($databaseManager);
     //$connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     $i = new afsDbInfo();
     $this->logSection('propel', 'Reading databases structure...');
     $ad = new AppData();
     $totalNbTables = 0;
     foreach ($connections as $name => $params) {
         $pdo = $databaseManager->getDatabase($name)->getConnection();
         $database = new Database($name);
         $platform = $this->getPlatform($databaseManager, $name);
         $database->setPlatform($platform);
         $database->setDefaultIdMethod(IDMethod::NATIVE);
         $parser = $this->getParser($databaseManager, $name, $pdo);
         //$parser->setMigrationTable($options['migration-table']);
         $parser->setPlatform($platform);
         $nbTables = $parser->parse($database);
         $ad->addDatabase($database);
         $totalNbTables += $nbTables;
         $this->logSection('propel', sprintf('  %d tables imported from database "%s"', $nbTables, $name), null, 'COMMENT');
     }
     if ($totalNbTables) {
         $this->logSection('propel', sprintf('%d tables imported from databases.', $totalNbTables));
     } else {
         $this->logSection('propel', 'Database is empty');
     }
     $this->logSection('propel', 'Loading XML schema files...');
     Phing::startup();
     // required to locate behavior classes...
     $this->schemaToXML(self::DO_NOT_CHECK_SCHEMA, 'generated-');
     $this->copyXmlSchemaFromPlugins('generated-');
     $appData = $this->getModels($databaseManager, true);
     $this->logSection('propel', sprintf('%d tables defined in the schema files.', $appData->countTables()));
     $this->cleanup(true);
     $this->logSection('sql-diff', 'Comparing databases and schemas...');
     $manager = new PropelMigrationManager();
     $manager->setConnections($connections);
     foreach ($ad->getDatabases() as $database) {
         $name = $database->getName();
         $filenameDiff = sfConfig::get('sf_data_dir') . "/sql/{$name}." . time() . ".diff.sql";
         $this->logSection('sql-diff', sprintf('  Comparing database "%s"', $name), null, 'COMMENT');
         if (!$appData->hasDatabase($name)) {
             // FIXME: tables present in database but not in XML
             continue;
         }
         $databaseDiff = PropelDatabaseComparator::computeDiff($database, $appData->getDatabase($name));
         if (!$databaseDiff) {
             //no diff
         }
         $this->logSection('sql-diff', sprintf('Structure of database was modified in datasource "%s": %s', $name, $databaseDiff->getDescription()));
         $platform = $this->getPlatform($databaseManager, $name);
         //up sql
         $upDiff = $platform->getModifyDatabaseDDL($databaseDiff);
         //down sql
         $downDiff = $platform->getModifyDatabaseDDL($databaseDiff->getReverseDiff());
         if ($databaseDiff) {
             $this->logSection('sql-diff', "Writing file {$filenameDiff}");
             afStudioUtil::writeFile($filenameDiff, $upDiff);
             if ($options['insert'] === true || $options['insert'] === 'true') {
                 $this->logSection('sql-diff', "Inserting sql diff");
                 $i->executeSql($upDiff, Propel::getConnection($name));
             }
             if ($options['build'] === true || $options['build'] === 'true') {
                 $this->logSection('sql-diff', 'Creating models from current schema');
                 $this->createTask('propel:build-model')->run();
                 $this->logSection('sql-diff', 'Creating forms from current schema');
                 $this->createTask('propel:build-forms')->run();
                 $this->logSection('sql-diff', 'Setting AppFlower project permissions');
                 $this->createTask('afs:fix-perms')->run();
                 $this->logSection('sql-diff', 'Creating AppFlower validator cache');
                 $this->createTask('appflower:validator-cache')->run(array('frontend', 'cache', 'yes'));
                 $this->logSection('sql-diff', 'Clearing Symfony cache');
                 $this->createTask('cc')->run();
             }
         }
     }
 }
 /**
  * Replaces tokens in an array of files.
  *
  * @param array  $files       An array of filenames
  * @param string $beginToken  The begin token delimiter
  * @param string $endToken    The end token delimiter
  * @param array  $tokens      An array of token/value pairs
  */
 public function replaceTokens($files, $beginToken, $endToken, array $tokens)
 {
     if (!is_array($files)) {
         $files = array($files);
     }
     foreach ($files as $file) {
         $content = file_get_contents($file);
         foreach ($tokens as $key => $value) {
             $content = str_replace($beginToken . $key . $endToken, $value, $content, $count);
         }
         afStudioUtil::writeFile($file, $content);
     }
 }
 /**
  * Saving schema
  * 
  * @param string $schema 
  * @return boolean
  */
 private function saveSchema($schema = '')
 {
     if (empty($schema)) {
         $schema = $this->getSchemaFile();
     }
     if (!array_key_exists($schema, $this->originalSchemaArray)) {
         return false;
     }
     return afStudioUtil::writeFile($schema, sfYaml::dump($this->originalSchemaArray[$schema], 3));
 }
 /**
  * Rename model content
  *
  * @param string $path 
  * @param string $name 
  * @param string $renamed 
  * @return bool
  * @author Sergey Startsev
  */
 public static function renameModelContent($path, $name, $renamed)
 {
     $content = file_get_contents($path);
     $content = str_ireplace($name, $renamed, $content);
     return afStudioUtil::writeFile($path, $content);
 }
 /**
  * Getting file content
  *
  * @return afResponse
  * @author Sergey Startsev
  */
 protected function processContent()
 {
     $file = $this->getParameter('file', false);
     $code = $this->getParameter('code', false);
     $is_post = $this->getParameter('is_post', false);
     $file = substr($file, 0, 4) == 'root' ? afStudioUtil::getRootDir() . substr($file, 4) : $file;
     $response = afResponseHelper::create();
     if ($is_post) {
         if ($file && is_string($code) && is_writable($file) && afStudioUtil::writeFile($file, $code) !== false) {
             return $response->success(true);
         }
         return $response->success(false);
     }
     if ($file && is_string($file_content = @file_get_contents($file))) {
         return $response->success(true)->data(array(), $file_content, 0);
     }
     return $response->success(false);
 }
 /**
  * Validate definition
  *
  * @param string $definition 
  * @return mixed - success: boolean, unsuccess: string - message error
  * @author Sergey Startsev
  */
 protected function doValidatePacked()
 {
     $definition = $this->getDefinition();
     $tempPath = tempnam(sys_get_temp_dir(), 'studio_wi_wb') . '.xml';
     afStudioUtil::writeFile($tempPath, $definition);
     $validator = new XmlValidator($tempPath);
     $status = $validator->validateXmlDocument();
     unlink($tempPath);
     $status = $validator->validateXmlDocument(true);
     if ($status[0] == self::IDENTIFICATOR_ERROR) {
         $return = trim($status[1]->getMessage());
     } else {
         $return = true;
     }
     return $return;
 }
 /**
  * Add plugin functionality
  * 
  * @return afResponse
  * @author Sergey Startsev
  */
 protected function processAdd()
 {
     $name = $this->getParameter('name');
     $root = sfConfig::get('sf_root_dir');
     $console = afStudioConsole::getInstance();
     $response = afResponseHelper::create();
     $filesystem = afsFileSystem::create();
     $permissions = new Permissions();
     $are_writable = $permissions->areWritable(array($root . "/plugins/"));
     if ($are_writable !== true) {
         return $are_writable;
     }
     $dir = "{$root}/plugins/{$name}";
     if (empty($name)) {
         return $response->success(false)->message('Please enter plugin name');
     }
     if (substr($name, -6) != 'Plugin') {
         return $response->success(false)->message("Plugin '{$name}' should Contains 'Plugin' in the end");
     }
     if (file_exists($dir)) {
         return $response->success(false)->message("Plugin '{$name}' already exists");
     }
     $dirs = array($dir, "{$dir}/config", "{$dir}/modules");
     foreach ($dirs as $dir) {
         $filesystem->mkdirs($dir);
     }
     if (file_exists($dir)) {
         // create config file with auto enable all modules in current plugin
         $created = afStudioUtil::writeFile("{$dir}/config/config.php", afStudioPluginCommandTemplate::config($name));
         $console_result = $console->execute(array('afs fix-perms', 'sf cc'));
         return $response->success(true)->message("Plugin '{$name}' successfully created")->console($console_result);
     }
     return $response->success(false)->message("Some problems to create dirs, please check permissions, and run fix-perms task");
 }
 /**
  * Creating new action
  *
  * @param string $module 
  * @return afResponse
  * @author Sergey Startsev
  */
 private function createAction($module = self::MODULE)
 {
     $response = afResponseHelper::create();
     if ($this->isNew()) {
         return $response->success(false)->message("can't create action for new page. Please first create and save definition");
     }
     $name = $this->getName();
     $path = $this->getPageActionPath();
     $definition = afsPageModelTemplate::create()->action($name);
     if (file_exists($path)) {
         return $response->success(true)->message("Action for '{$name}' already exists");
     }
     if (afStudioUtil::writeFile($path, $definition)) {
         return $response->success(true)->message("Action has been successfully created");
     }
     return $response->success(false)->message("Can't create action file");
 }
 /**
  * @author radu
  */
 public static function getTemplateConfig()
 {
     $pluginTemplateYml = sfYaml::load(sfConfig::get('sf_root_dir') . '/plugins/appFlowerStudioPlugin/config/template.yml');
     $projectYmlPath = sfConfig::get('sf_root_dir') . '/config/project.yml';
     $projectYml = sfYaml::load($projectYmlPath);
     if (isset($projectYml['project']['template'])) {
         $pluginTemplateYml['template']['current'] = $projectYml['project']['template'];
     } else {
         $pluginTemplateYml['template']['current'] = $pluginTemplateYml['template']['default'];
         $projectYml['project']['template'] = $pluginTemplateYml['template']['default'];
         afStudioUtil::writeFile($projectYmlPath, sfYaml::dump($projectYml, 4));
     }
     return $pluginTemplateYml;
 }
 /**
  * checks if action file exists
  * if not - we are createing new action file
  * 
  * @return boolean
  * @author Lukasz Wojciechowski
  * @author Sergey Startsev
  * @author Radu Topala
  */
 private function ensureActionExists()
 {
     if (!$this->ensureFolderExists($this->getPlaceActionsPath())) {
         return false;
     }
     $action_file_name = "{$this->getAction()}Action.class.php";
     $action_file_path = $this->getPlaceActionsPath() . DIRECTORY_SEPARATOR . $action_file_name;
     if (!file_exists($action_file_path)) {
         afStudioUtil::writeFile($action_file_path, afsWidgetModelTemplate::create()->action($this->getAction(), $this->getType(), $this->getModel()));
     }
     //if list action is generated, then also generate delete action
     if ($this->getType() == 'list') {
         $modelProcessed = lcfirst(sfInflector::camelize($this->getModel()));
         $delete_action_file_name = "{$modelProcessed}DeleteAction.class.php";
         $delete_action_file_path = $this->getPlaceActionsPath() . DIRECTORY_SEPARATOR . $delete_action_file_name;
         if (!file_exists($delete_action_file_path)) {
             afStudioUtil::writeFile($delete_action_file_path, afsWidgetModelTemplate::create()->action($modelProcessed . 'Delete', 'delete', $this->getModel()));
         }
     }
     return file_exists($action_file_path);
 }