/**
  * Rename module name inside actions
  *
  * @param string $name 
  * @param string $renamed 
  * @param string $place 
  * @param string $type 
  * @return void
  * @author Sergey Startsev
  */
 public static function renameAction($name, $renamed, $place, $type)
 {
     $afConsole = afStudioConsole::getInstance();
     $root = afStudioUtil::getRootDir();
     $dir = "{$root}/{$type}s/{$place}/modules/{$renamed}";
     $actionsPath = "{$dir}/actions/actions.class.php";
     // rename actions class
     if (file_exists($actionsPath)) {
         self::renameActionContent($actionsPath, $name, $renamed);
     }
     // generated lib actions class
     $actionsLibPath = "{$dir}/lib/Base{$name}Actions.class.php";
     if (file_exists($actionsLibPath)) {
         self::renameActionContent($actionsLibPath, $name, $renamed);
         afsFileSystem::create()->rename($actionsLibPath, "{$dir}/lib/Base{$renamed}Actions.class.php");
     }
 }
 /**
  * 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;
 }
 /**
  * Getting pwd command result
  *
  * @return string
  * @author Sergey Startsev
  */
 public function getPwd()
 {
     if (empty($this->pwd)) {
         if (afsConsoleHelper::isUnixLikeOs()) {
             $pwd = afsFileSystem::create()->execute('pwd');
             $this->pwd = strlen($pwd[1]) == 0 ? $pwd[0] : '';
         }
         $session = new Session();
         if ($session->get('pwd')) {
             $this->pwd = $session->get('pwd');
         }
     }
     return $this->pwd;
 }
 /**
  * Adding new module to plugin functionality
  *
  * @param string $plugin - plugin name that will contain new module
  * @param string $name - module name
  * @return afResponse
  * @author Sergey Startsev
  */
 private function addToPlugin($plugin, $module)
 {
     afStudioModuleCommandHelper::load('plugin');
     $response = afResponseHelper::create();
     if (!afStudioPluginCommandHelper::isExists(afStudioPluginCommandHelper::PLUGIN_GENERATE_MODULES)) {
         return $response->success(false)->message("For creating module in plugins should be installed '" . afStudioPluginCommandHelper::PLUGIN_GENERATE_MODULES . "' plugin");
     }
     $afConsole = afStudioConsole::getInstance();
     if (!$plugin || !$module) {
         return $response->success(false)->message("Can't create new module <b>{$module}</b> inside <b>{$plugin}</b> plugin!");
     }
     if (!afStudioPluginCommandHelper::isExists($plugin)) {
         return $response->success(false)->message("Plugin '{$plugin}' doesn't exists");
     }
     $console = $afConsole->execute("sf generate:plugin-module {$plugin} {$module}");
     $isCreated = $afConsole->wasLastCommandSuccessfull();
     if ($isCreated) {
         afsFileSystem::create()->chmod(sfConfig::get('sf_plugins_dir') . "/{$plugin}/modules/{$module}", 0664, 00, true);
         $console .= $afConsole->execute('sf cc');
         $message = "Created module <b>{$module}</b> inside <b>{$plugin}</b> plugin!";
     } else {
         $message = "Could not create module <b>{$module}</b> inside <b>{$plugin}</b> plugin!";
     }
     return $response->success($isCreated)->message($message)->console($console);
 }
 /**
  * Rename model files
  *
  * @param string $native_name 
  * @param string $new_name 
  * @return array - status and message
  * @author Sergey Startsev
  */
 public static function renameModel($native_name, $new_name)
 {
     $lib_path = sfConfig::get("sf_lib_dir");
     $messages = array();
     $files = array('model' => array('path' => "{$lib_path}/model", 'file' => ".php", 'postfix' => "", 'pattern' => "/class {$native_name} extends Base{$native_name}.*?\\{\\s*?(.*?)\\s*?\\}/sim"), 'peer' => array('path' => "{$lib_path}/model", 'file' => ".php", 'postfix' => "Peer", 'pattern' => "/class {$native_name}Peer extends Base{$native_name}Peer.*?\\{\\s*?(.*?)\\s*?\\}/sim"), 'query' => array('path' => "{$lib_path}/model", 'file' => ".php", 'postfix' => "Query", 'pattern' => "/class {$native_name}Query extends Base{$native_name}Query.*?\\{\\s*?(.*?)\\s*?\\}/sim"), 'form' => array('path' => "{$lib_path}/form", 'file' => ".class.php", 'postfix' => "Form", 'pattern' => "/public function configure\\(\\).*?\\{\\s*?(.*?)\\s*?\\}/sim"));
     $filesystem = afsFileSystem::create();
     foreach ($files as $file) {
         if (file_exists("{$file['path']}/{$native_name}{$file['postfix']}{$file['file']}") && self::isModifiedContent("{$file['path']}/{$native_name}{$file['postfix']}{$file['file']}", $file['pattern']) && $filesystem->copy("{$file['path']}/{$native_name}{$file['postfix']}{$file['file']}", "{$file['path']}/{$new_name}{$file['postfix']}{$file['file']}")) {
             self::renameModelContent("{$file['path']}/{$new_name}{$file['postfix']}{$file['file']}", "{$native_name}{$file['postfix']}", "{$new_name}{$file['postfix']}");
             $messages[] = "In {$native_name}{$file['postfix']} has been found custom code, please check {$new_name}{$file['postfix']} for correct work";
         }
     }
     return array(true, implode("\n", $messages));
 }
 /**
  * Checking exists file helper or not
  *
  * @return afResponse
  * @author Sergey Startsev
  */
 protected function processIsHelperExists()
 {
     $result = true;
     $message = "";
     $filesystem = afsFileSystem::create();
     $helper = $this->getParameter('helper');
     $place = $this->getParameter('place', 'frontend');
     $place_type = $this->getParameter('place_type', 'app');
     $helper_folder_path = afStudioUtil::getRootDir() . "/{$place_type}s/{$place}/lib/helper";
     if (!file_exists($helper_folder_path)) {
         $filesystem->mkdirs($helper_folder_path);
         $filesystem->chmod($helper_folder_path, 0777);
     }
     $filePath = "{$helper_folder_path}/{$helper}Helper.php";
     if (!file_exists($filePath)) {
         try {
             $engine_helper = afStudioUtil::getRootDir() . "/plugins/appFlowerStudioPlugin/modules/appFlowerStudio/templates/_{$helper}Helper.php";
             $_helper = file_exists($engine_helper) ? file_get_contents($engine_helper, true) : '';
             $fp = fopen($filePath, "w");
             fWrite($fp, $_helper);
             fclose($fp);
             $filesystem->chmod($filePath, 0777);
         } catch (Exception $e) {
             $result = false;
             $message = 'Error while saving file to disk!';
         }
         $message = 'File created successfully';
     }
     return afResponseHelper::create()->success($result)->message($message);
 }
 /**
  * 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");
 }
 /**
  * Delete page functionality
  *
  * @return afResponse
  * @author Sergey Startsev
  */
 public function delete()
 {
     $response = afResponseHelper::create();
     if ($this->isNew()) {
         return $response->success(false)->message("Page <b>{$this->getName()}</b> doesn't exists");
     }
     $page_path = $this->getPagePath();
     $page_action_path = $this->getPageActionPath();
     $filesystem = afsFileSystem::create();
     if (file_exists($page_path)) {
         $filesystem->remove($page_path);
     }
     if (file_exists($page_action_path)) {
         $filesystem->remove($page_action_path);
     }
     if (!file_exists($page_path)) {
         return $response->success(true)->message("Page <b>{$this->getName()}</b> has been successfully deleted");
     }
     return $response->success(false)->message("Can't delete page <b>{$this->getName()}</b>!");
 }
 /**
  * Loads an Excel document and processes all non-empty worksheets or only the selected ones.
  * This reads data and cell formatting info as well, can open Excel 2007, 2003 and Excel 5 files. 
  * The current reader extracts all values and converts dates / times and hyperlinks automatically.
  * 
  * @see importer/BaseImporter::loadData()
  */
 public function loadData($path)
 {
     $ext = afsFileSystem::create()->getExtension($path);
     switch ($ext) {
         case "xls":
             $type = "Excel5";
             break;
         case "xlsx":
             $type = "Excel2007";
             break;
         case "ods":
             $type = "OOCalc";
             break;
     }
     $allowed_mimes = array("application/zip; charset=binary", "application/vnd.ms-office; charset=binary", "application/octet-stream; charset=binary");
     try {
         $finfo = finfo_open(FILEINFO_MIME);
         if (!in_array(finfo_file($finfo, $path), $allowed_mimes)) {
             throw new ImporterException("Not a Spreadsheet document!");
         }
         $method = $this->properties->raw ? "getValue" : "getCalculatedValue";
         $objReader = PHPExcel_IOFactory::createReader($type);
         $first_sheet = null;
         if ($this->properties->worksheet) {
             $sheets = explode(",", str_replace(" ", "", $this->properties->worksheet));
             if ($this->properties->has_header && !$this->properties->worksheets_as_models) {
                 $all_sheets = $objReader->listWorksheetNames($path);
                 $objReader->setLoadSheetsOnly(array((string) $all_sheets[0]));
                 $objPHPExcel = @$objReader->load($path);
                 $first_sheet = $objPHPExcel->getSheet(0);
                 foreach ($first_sheet->getRowIterator() as $row) {
                     $cellIterator = $row->getCellIterator();
                     $cellIterator->setIterateOnlyExistingCells(true);
                     foreach ($cellIterator as $cell) {
                         $this->data[$first_sheet->getTitle()][$row->getRowIndex() - 1][] = $cell->getValue();
                     }
                     break;
                 }
             }
             $objReader->setLoadSheetsOnly($sheets);
             if ($this->properties->worksheets_as_models) {
                 foreach ($sheets as $sheet) {
                     if (!class_exists($sheet)) {
                         throw new ImporterException("Model '" . $sheet . "' does not exist!");
                     }
                 }
             }
         } else {
             $objReader->setLoadAllSheets();
         }
         $objPHPExcel = @$objReader->load($path);
         $worksheets = $objPHPExcel->getAllSheets();
         foreach ($worksheets as $k => $worksheet) {
             if (is_null($worksheet->getCellByColumnAndRow(0, 1)->getValue())) {
                 unset($worksheets[$k]);
             }
         }
         if (sizeof($worksheets) == 0) {
             throw new ImporterException("There is no data to import in file! Did you type worksheet names correctly?");
         }
         foreach ($worksheets as $worksheet) {
             $lineno = 1;
             foreach ($worksheet->getRowIterator() as $rk => $row) {
                 if ($rk == 1 && $first_sheet && $worksheet->getTitle() == $first_sheet->getTitle()) {
                     continue;
                 }
                 $cellIterator = $row->getCellIterator();
                 $cellIterator->setIterateOnlyExistingCells(true);
                 $lineno++;
                 $this->properties->lines = $worksheet->getTitle() . ":" . $lineno;
                 if ($this->properties->worksheets_as_models && $this->isInvalidModel($worksheet->getTitle())) {
                     throw new ImporterException("Model '" . $worksheet->getTitle() . "' does not exist!");
                 }
                 foreach ($cellIterator as $cell) {
                     if (!is_null($cell) && $cell->getValue()) {
                         if (PHPExcel_Shared_Date::isDateTime($cell)) {
                             $value = $cell->getCalculatedValue();
                             if ($value instanceof PHPExcel_RichText) {
                                 $value = $value->getPlainText();
                             }
                             $this->data[$worksheet->getTitle()][$row->getRowIndex() - 1][] = date("Y-m-d H:i:s", PHPExcel_Shared_Date::ExcelToPHP($value));
                         } else {
                             if ($cell->hasHyperlink()) {
                                 $this->data[$worksheet->getTitle()][$row->getRowIndex() - 1][] = '<a href="' . $cell->getHyperlink()->getUrl() . '" title="' . $cell->getHyperlink()->getTooltip() . '">' . $cell->{$method}() . '</a>';
                             } else {
                                 $this->data[$worksheet->getTitle()][$row->getRowIndex() - 1][] = $cell->{$method}();
                             }
                         }
                     }
                 }
             }
         }
     } catch (Exception $e) {
         throw new ImporterException("<b>File</b>: " . $path . "<br /><br /><b>Error</b>: " . $e->getMessage() . "<br/>");
     }
 }
 /**
  * Saving yml helper definition
  *
  * @return afResponse
  * @author Sergey Startsev
  */
 protected function processSaveHelper()
 {
     $response = afResponseHelper::create();
     $filesystem = afsFileSystem::create();
     $place = $this->getParameter('place', 'frontend');
     $place_type = $this->getParameter('place_type', 'app');
     $content = preg_replace(array('/\\<\\?php/', '/\\<\\?/', '/\\?\\>/'), array('', '', ''), $this->getParameter('content'));
     $content = json_decode($content, true);
     $key = $this->getParameter('key', '');
     $permissions = new Permissions();
     $is_writable = $permissions->isWritable(sfConfig::get('sf_apps_dir') . '/' . $place . '/config/helper.yml');
     if ($is_writable !== true) {
         return $is_writable;
     }
     $helper_path = afExtjsBuilderParser::getHelperPath($place, $place_type);
     if (file_exists($helper_path)) {
         if (!is_writable($helper_path)) {
             return $response->success(false)->message("Please check permissions on helper file");
         }
         $definition = afExtjsBuilderParser::create($helper_path)->parse()->get();
     } else {
         if (!is_writable(dirname($helper_path))) {
             return $response->success(false)->message("Please check permissions on folder for helper file");
         }
         $definition = array();
         $filesystem->touch($helper_path);
         $filesystem->chmod($helper_path, 0777);
     }
     !empty($key) ? $definition[$key] = (array) $content : ($definition = (array) $content);
     $status = file_put_contents($helper_path, sfYaml::dump($definition, 8));
     return $response->success($status)->message($status ? "Helper has been successfully saved" : "Some problems occured while save processing");
 }
 /**
  * Imports various data files from fixtures (YAML) directory or via file upload (CSV,YAML,Spreadsheets).
  * 
  * @throws Exception
  * @return afResponse
  * @author Tamas Geshitz
  */
 protected function processImportData()
 {
     $remote_files = json_decode($this->getParameter("remote_files", '{}'), true);
     sort($remote_files);
     $formats = array("yml" => "yml", "yaml" => "yml", "csv" => "csv", "xlsx" => "xls", "xls" => "xls", "ods" => "xls");
     foreach (array("has_headers", "append", "model", "name", "tmp", "code", "delimeter", "enclosure", "raw", "worksheet", "worksheets_as_models") as $item) {
         $params[$item] = $this->getParameter($item);
     }
     $params["append"] = $params["append"] === "true" || $params["append"] === "on" ? true : false;
     $params["delimeter"] = $params["delimeter"] ? $params["delimeter"] : ",";
     $params["enclosure"] = $params["enclosure"] ? $params["enclosure"] : '"';
     try {
         if (!$params["name"]) {
             foreach ($remote_files as $file) {
                 $files[] = afStudioUtil::getFixturesDir() . "/" . $file;
             }
             $class = "YmlImporter";
         } else {
             $ext = afsFileSystem::create()->getExtension($params["name"]);
             if (!array_key_exists($ext, $formats)) {
                 throw new Exception("Unsupported file: " . $params["name"]);
             }
             $class = ucfirst($formats[$ext] . "Importer");
             if ($params["code"] !== 0) {
                 throw new Exception("Failed to upload file: " . $params["name"]);
             }
             $uploaded_file = afStudioUtil::getUploadsDir() . "/" . $params["name"];
             if (!@move_uploaded_file($params["tmp"], $uploaded_file)) {
                 throw new Exception("Couldn't process uploaded file: " . $params["name"]);
             }
             $files = array($uploaded_file);
         }
         $importer = new $class($params);
         $importer->setProperty("all", $files);
         foreach ($files as $k => &$file) {
             $importer->setProperty("current", $file);
             $importer->loadData($file);
             if (!$importer instanceof CsvImporter) {
                 $importer->insertData($file);
             }
         }
         if ($params["name"]) {
             if (!@unlink($uploaded_file)) {
                 throw new Exception("Couldn't delete tmp file: " . $params["name"]);
             }
         }
     } catch (Exception $e) {
         return afResponseHelper::create()->success(false)->message("An error has been occured!<br/><br/>" . $e->getMessage());
     }
     $errors = $importer->getProperty("errors");
     if ($class == "YmlImporter" && $errors) {
         return afResponseHelper::create()->success(false)->message("Error(s) have been occured:<br/><br/>" . implode("<br />", $errors));
     }
     return afResponseHelper::create()->success(true)->message("Data has been successfully inserted!");
 }
 /**
  * Export db by propel generates sql's
  *
  * @param string $source 
  * @param string $destination 
  * @param string $project_name 
  * @param Array $options 
  * @return void
  * @author Sergey Startsev
  */
 private function exportDbByPropel($source, $destination, $project_name, array $options)
 {
     $properties = $this->getProperties(sfConfig::get('sf_config_dir') . '/propel.ini');
     $sql_dir = str_replace('${propel.output.dir}', $properties['propel.output.dir'], $properties['propel.sql.dir']);
     // build task
     $this->schemaToXML(self::DO_NOT_CHECK_SCHEMA, 'generated-');
     $this->copyXmlSchemaFromPlugins('generated-');
     $ret = $this->callPhing('sql', self::CHECK_SCHEMA);
     $this->cleanup();
     $main_sql = 'lib.model.schema.sql';
     $export_sql = "{$project_name}.sql";
     $export_path = "{$destination}{$export_sql}";
     $this->log("Building sql files.");
     if (!file_exists("{$sql_dir}/{$main_sql}")) {
         throw sfCommandException("Oops, please check credentials to data and right propel output dir.");
     }
     $this->logSection('main-sql', "{$sql_dir}/{$main_sql}");
     afsFileSystem::create()->copy("{$sql_dir}/{$main_sql}", $export_path);
     $schemas = sfFinder::type('file')->name('*schema.yml')->prune('doctrine')->in($this->configuration->getPluginSubPaths('/config'));
     foreach ($schemas as &$schema) {
         $pattern = sfConfig::get('sf_plugins_dir') . "/(.*?)/";
         if (preg_match("#{$pattern}#si", $schema, $match)) {
             $schema = $match[1];
         }
         $plugin_sql_path = "{$sql_dir}/plugins.{$schema}.lib.model.schema.sql";
         if (file_exists($plugin_sql_path)) {
             file_put_contents($export_path, file_get_contents($plugin_sql_path), FILE_APPEND);
         }
         $this->logSection('plugin-sql', $plugin_sql_path);
     }
     $this->log("Created 1 file for import.");
     $this->logSection('exported', $export_path);
 }
 /**
  * Ensure that folder exists 
  *
  * @param string $folder 
  * @param int $mode - octal
  * @return boolean
  * @author Sergey Startsev
  */
 private function ensureFolderExists($folder, $mode = 0775)
 {
     if (!file_exists($folder)) {
         afsFileSystem::create()->mkdirs($folder, $mode);
     }
     return file_exists($folder);
 }