public function run($args = null) { $theme = $args[0]; $themePath = realpath(dirname(__FILE__) . '/../../themes') . '/' . $theme; if (!file_exists($themePath)) { mkdir($themePath); mkdir($themePath . '/views'); } // Find all modules views and copy to theme directory $files = glob(realpath(dirname(__FILE__) . '/../') . '/modules/*', GLOB_ONLYDIR); foreach ($files as $file) { $parts = explode('/', $file); $module = end($parts); // Don't copy next modules to theme dir. if (in_array($module, array('admin', 'install', 'rights'))) { continue; } $moduleThemePath = $themePath . '/views/' . $module; $moduleViews = glob($file . '/views/*', GLOB_ONLYDIR); foreach ($moduleViews as $viewsDirPath) { $parts = explode('/', $viewsDirPath); if (end($parts) != 'admin') { if (!file_exists($moduleThemePath)) { mkdir($moduleThemePath, 0777, true); } CFileHelper::copyDirectory($viewsDirPath, $moduleThemePath . '/' . end($parts)); } } } }
public function run($args = null) { $theme = $args[0]; $themePath = realpath(dirname(__FILE__) . '/../../themes') . DIRECTORY_SEPARATOR . $theme; if (!file_exists($themePath)) { mkdir($themePath); mkdir($themePath . '/views'); } // Find all modules views and copy to theme directory $files = glob(realpath(dirname(__FILE__) . '/../') . '/modules/*', GLOB_ONLYDIR); foreach ($files as $file) { $parts = explode('/', $file); $module = end($parts); $moduleThemePath = $themePath . '/views/' . $module; $moduleViews = glob($file . '/views/*', GLOB_ONLYDIR); foreach ($moduleViews as $viewsDirPath) { $parts = explode('/', $viewsDirPath); if (end($parts) != 'admin') { if (!file_exists($moduleThemePath)) { mkdir($moduleThemePath); } CFileHelper::copyDirectory($viewsDirPath, $moduleThemePath . '/' . end($parts)); } } } }
/** * Install templates * * @return void */ private function _installExampleTemplates() { try { $fileHelper = new \CFileHelper(); @mkdir(craft()->path->getSiteTemplatesPath() . 'sproutemail'); $fileHelper->copyDirectory(craft()->path->getPluginsPath() . 'sproutemail/templates/_special/examples/emails', craft()->path->getSiteTemplatesPath() . 'sproutemail'); } catch (\Exception $e) { $this->_handleError($e); } }
function run($args) { if (empty($args[1])) { echo $this->getHelp(); return; } $path = $args[0]; $version = $args[1]; echo "Preparing {$path} release.\n"; require dirname(__FILE__) . '/GenerateDocsCommand.php'; $docProcessor = new GenerateDocsCommand($this->getName(), $this->getCommandRunner()); $outFiles = $docProcessor->processDocuments($path); // copy extension dir to temp $extPath = Yii::getPathOfAlias('ext') . '/' . $path; $copiedExtRoot = Yii::getPathOfAlias('application.runtime.extension'); echo "Removing {$copiedExtRoot}.\n"; if (file_exists($copiedExtRoot)) { $this->recursiveDelete($copiedExtRoot); } $copiedExtPath = $copiedExtRoot . '/' . $path; if (!file_exists($copiedExtPath)) { mkdir($copiedExtPath, 0777, true); } echo "Copying extension files from {$extPath} to {$copiedExtPath}.\n"; CFileHelper::copyDirectory($extPath, $copiedExtPath, array('exclude' => array('.svn', 'readme_en.txt', 'readme_ru.txt'))); echo "Copying documentation to {$copiedExtPath}.\n"; foreach ($outFiles as $file) { copy($file, $copiedExtPath . '/' . basename($file)); } $pathExp = explode('/', $path); $zipName = end($pathExp) . '_' . $version . '.zip'; $releasePath = Yii::getPathOfAlias('application.releases'); if (!file_exists($releasePath)) { mkdir($releasePath, 0777, true); } $zipPath = "{$releasePath}/{$zipName}"; if (file_exists($zipPath)) { unlink($zipPath); } //touch($zipPath); echo "Creating Zip {$zipPath}.\n"; require dirname(__FILE__) . '/Zip.php'; $zip = new Zip(); if ($zip->open($zipPath, ZipArchive::OVERWRITE | ZipArchive::CREATE) !== TRUE) { die("Failed to open Zip {$zipPath}.\n"); } if (!$zip->addDir($copiedExtRoot)) { die("Failed adding {$copiedExtRoot} to Zip.\n"); } if ($zip->close()) { echo "Done.\n"; } else { die("Failed to write Zip {$zipPath}.\n"); } }
public function testCopyDirectory_subDir_modeShoudBe0777() { if (substr(PHP_OS, 0, 3) == 'WIN') { $this->markTestSkipped("Can't reliably test it on Windows because fileperms() always return 0777."); } $this->createTestStruct($this->testDir); $src = $this->testDir . DIRECTORY_SEPARATOR . $this->rootDir1; $dst = $this->testDir . DIRECTORY_SEPARATOR . $this->rootDir2; CFileHelper::copyDirectory($src, $dst); $subDir2Mode = $this->getMode($dst . DIRECTORY_SEPARATOR . $this->subDir); $expectedMode = sprintf('%o', 0777); $this->assertEquals($expectedMode, $subDir2Mode, "Subdir mode is not {$expectedMode}"); }
public function generateMessagesModules($locale) { $modules = ModulesModel::getModules(); $t = new yandexTranslate(); $result = array(); $num = -1; $params = array(); foreach ($modules as $key => $mod) { $pathDefault = Yii::getPathOfAlias(self::PATH_MOD . '.' . $key . '.messages.ru'); $listfile = CFileHelper::findFiles($pathDefault, array('fileTypes' => array('php'), 'absolutePaths' => false)); $path = Yii::getPathOfAlias(self::PATH_MOD . '.' . $key . '.messages' . DS . $locale); //CFileHelper::createDirectory($path, 0777); CFileHelper::copyDirectory($pathDefault, $path, array('fileTypes' => array('php'), 'level' => 1)); foreach ($listfile as $file) { // $file = str_replace('.php', '', $file); $openFileContent = self::PATH_MOD . ".{$key}.messages.{$locale}"; $contentList = (include Yii::getPathOfAlias($openFileContent) . DS . $file); // foreach($contentList as $pkey=>$value){ foreach ($contentList as $pkey => $val) { $params[] = $val; $num++; $spec[$num] = $pkey; } $response = $t->translate(array('ru', $locale), $contentList); foreach ($response['text'] as $k => $v) { $result[$spec[$k]] = $v; } if (!@file_put_contents($path . DS . $file, '<?php /** * Message translations. (auto translate) * * Each array element represents the translation (value) of a message (key). * If the value is empty, the message is considered as not translated. * Messages that no longer need translation will have their translations * enclosed between a pair of \'@@\' marks. * * @author Andrew (Panix) Semenov <*****@*****.**> * @package modules.messages.' . $locale . ' */ return ' . var_export($result, true) . ';')) { throw new CException(Yii::t('admin', 'Error write modules setting in {file}...', array('{file}' => $file))); } } die('finish ' . $key); } die('Complate'); // $locale }
public function publish($path, $hashByName = false, $level = -1, $forceCopy = false) { if (isset($this->_published[$path])) { return $this->_published[$path]; } else { if (($src = realpath($path)) !== false) { if (is_file($src)) { $dir = $this->hash($hashByName ? basename($src) : dirname($src)); $fileName = basename($src); $dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir; $dstFile = $dstDir . '_' . $fileName; if ($this->linkAssets) { if (!is_file($dstFile)) { symlink($src, $dstFile); } } else { if (@filemtime($dstFile) < @filemtime($src) || $forceCopy) { copy($src, $dstFile); } } return $this->_published[$path] = $this->getBaseUrl() . '/' . $dir . '_' . $fileName; } else { if (is_dir($src)) { $dir = $this->hash($hashByName ? basename($src) : $src); $dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir; if ($this->linkAssets) { if (!is_dir($dstDir)) { symlink($src, $dstDir); } } else { if (!is_dir($dstDir) || $forceCopy) { CFileHelper::copyDirectory($src, $dstDir, array('exclude' => $this->excludeFiles, 'level' => $level)); } } return $this->_published[$path] = $this->getBaseUrl() . '/' . $dir; } } } } throw new CException(Yii::t('yii', 'The asset "{asset}" to be published does not exist.', array('{asset}' => $path))); }
public function publish($path, $hashByName = false, $level = -1, $forceCopy = null) { if ($forceCopy === null) { $forceCopy = $this->forceCopy; } if ($forceCopy && $this->linkAssets) { throw new CException(Yii::t('yii', 'The "forceCopy" and "linkAssets" cannot be both true.')); } if (isset($this->_published[$path])) { return $this->_published[$path]; } else { if (($src = realpath($path)) !== false) { $dir = $this->generatePath($src, $hashByName); $dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir; if (is_file($src)) { $fileName = basename($src); $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName; if (!is_dir($dstDir)) { mkdir($dstDir, $this->newDirMode, true); chmod($dstDir, $this->newDirMode); } if ($this->linkAssets && !is_file($dstFile)) { symlink($src, $dstFile); } elseif (@filemtime($dstFile) < @filemtime($src)) { copy($src, $dstFile); chmod($dstFile, $this->newFileMode); } return $this->_published[$path] = $this->getBaseUrl() . "/{$dir}/{$fileName}"; } elseif (is_dir($src)) { if ($this->linkAssets && !is_dir($dstDir)) { symlink($src, $dstDir); } elseif (!is_dir($dstDir) || $forceCopy) { CFileHelper::copyDirectory($src, $dstDir, array('exclude' => $this->excludeFiles, 'level' => $level, 'newDirMode' => $this->newDirMode, 'newFileMode' => $this->newFileMode)); } return $this->_published[$path] = $this->getBaseUrl() . '/' . $dir; } } } throw new CException(Yii::t('yii', 'The asset "{asset}" to be published does not exist.', array('{asset}' => $path))); }
public function publish($path,$hashByName=false,$level=-1,$forceCopy=false) { if(isset($this->_published[$path])) { return $this->_published[$path]; } else if(($src=realpath($path))!==false) { if(is_file($src)) { $dir=$this->hash($hashByName ? basename($src) : dirname($src)); $fileName=basename($src); $suffix=substr(strrchr($fileName, '.'), 1); $dstDir=$this->getBasePath().DIRECTORY_SEPARATOR.$dir; if (array_key_exists($suffix, $this->parsers)) { $fileName=basename($src, $suffix).$this->parsers[$suffix]['output']; } $dstFile=$dstDir.DIRECTORY_SEPARATOR.$fileName; if($this->force || @filemtime($dstFile)<@filemtime($src)) { if(!is_dir($dstDir)) { mkdir($dstDir); @chmod($dstDir,0777); } if (array_key_exists($suffix, $this->parsers)) { $parserClass = Yii::import($this->parsers[$suffix]['class']); $parser = new $parserClass($this->parsers[$suffix]['options']); file_put_contents($dstFile, $parser->parse($src)); } else { copy($src,$dstFile); } } return $this->_published[$path]=$this->getBaseUrl()."/$dir/$fileName"; } else if(is_dir($src)) { $dir=$this->hash($hashByName ? basename($src) : $src); $dstDir=$this->getBasePath().DIRECTORY_SEPARATOR.$dir; if($this->linkAssets) { if(!is_dir($dstDir)) symlink($src,$dstDir); } else if(!is_dir($dstDir) || $forceCopy) { CFileHelper::copyDirectory($src,$dstDir,array( 'exclude'=>$this->excludeFiles, 'level'=>$level, 'newDirMode'=>$this->newDirMode, 'newFileMode'=>$this->newFileMode )); } return $this->_published[$path]=$this->getBaseUrl().'/'.$dir; } } }
protected function buildOfflinePages($docPath, $themePath) { $this->themePath = $themePath; @mkdir($docPath); $content = $this->render('index', null, true); $content = preg_replace_callback(self::URL_PATTERN, array($this, 'fixOfflineLink'), $content); file_put_contents($docPath . '/index.html', $content); foreach ($this->classes as $name => $class) { $this->currentClass = $name; $this->pageTitle = $name; $content = $this->render('class', array('class' => $class), true); $content = preg_replace_callback(self::URL_PATTERN, array($this, 'fixOfflineLink'), $content); file_put_contents($docPath . '/' . $name . '.html', $content); } CFileHelper::copyDirectory($this->themePath . '/assets', $docPath); $content = $this->renderPartial('chmProject', null, true); file_put_contents($docPath . '/manual.hhp', $content); $content = $this->renderPartial('chmIndex', null, true); file_put_contents($docPath . '/manual.hhk', $content); $content = $this->renderPartial('chmContents', null, true); file_put_contents($docPath . '/manual.hhc', $content); }
/** * This function imports a LimeSurvey .lss survey XML file * * @param mixed $sFullFilePath The full filepath of the uploaded file */ function XMLImportSurvey($sFullFilePath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true, $bConvertInvalidQuestionCodes = true) { Yii::app()->loadHelper('database'); $clang = Yii::app()->lang; $aGIDReplacements = array(); if ($sXMLdata == NULL) { $sXMLdata = file_get_contents($sFullFilePath); } $xml = @simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET); if (!$xml || $xml->LimeSurveyDocType != 'Survey') { $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file."); return $results; } $pre_personal_characteristics = ""; $question_groups['R'] = array(); $question_groups['I'] = array(); $question_groups['O'] = array(); $iDBVersion = (int) $xml->DBVersion; $aQIDReplacements = array(); $aQuestionCodeReplacements = array(); $aQuotaReplacements = array(); $results['defaultvalues'] = 0; $results['answers'] = 0; $results['surveys'] = 0; $results['questions'] = 0; $results['subquestions'] = 0; $results['question_attributes'] = 0; $results['groups'] = 0; $results['assessments'] = 0; $results['quota'] = 0; $results['quotals'] = 0; $results['quotamembers'] = 0; $results['survey_url_parameters'] = 0; $results['importwarnings'] = array(); $aLanguagesSupported = array(); foreach ($xml->languages->language as $language) { $aLanguagesSupported[] = (string) $language; } $results['languages'] = count($aLanguagesSupported); // Import surveys table ==================================================== foreach ($xml->surveys->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $iOldSID = $results['oldsid'] = $insertdata['sid']; if ($iDesiredSurveyId != NULL) { $insertdata['wishSID'] = GetNewSurveyID($iDesiredSurveyId); } else { $insertdata['wishSID'] = $iOldSID; } if ($iDBVersion < 145) { if (isset($insertdata['private'])) { $insertdata['anonymized'] = $insertdata['private']; } unset($insertdata['private']); unset($insertdata['notification']); } //Make sure it is not set active $insertdata['active'] = 'N'; //Set current user to be the owner $insertdata['owner_id'] = Yii::app()->session['loginID']; if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') { $insertdata['bouncetime'] = NULL; } if (isset($insertdata['showXquestions'])) { $insertdata['showxquestions'] = $insertdata['showXquestions']; unset($insertdata['showXquestions']); } // Special code to set javascript in Yii::app()->loadHelper('admin/template'); $newname = "watson_" . time(); $newdirname = Yii::app()->getConfig('usertemplaterootdir') . "/" . $newname; $copydirname = getTemplatePath("watson_personal_constructs_copy_me"); $oFileHelper = new CFileHelper(); $mkdirresult = mkdir_p($newdirname); if ($mkdirresult == 1) { $oFileHelper->copyDirectory($copydirname, $newdirname); $templatename = $newname; //$this->index("startpage.pstpl", "welcome", $templatename); } elseif ($mkdirresult == 2) { $results['Error'] = sprintf($clang->gT("Directory with the name `%s` already exists - choose another name", "js"), $newname); } else { $results['Error'] = sprintf($clang->gT("Unable to create directory `%s`.", "js"), $newname) . " " . $clang->gT("Please check the directory permissions.", "js"); } $insertdata['template'] = $newname; // End special copy code (taken from templates.php templatecopy() method if (isset($insertdata['googleAnalyticsStyle'])) { $insertdata['googleanalyticsstyle'] = $insertdata['googleAnalyticsStyle']; unset($insertdata['googleAnalyticsStyle']); } if (isset($insertdata['googleAnalyticsAPIKey'])) { $insertdata['googleanalyticsapikey'] = $insertdata['googleAnalyticsAPIKey']; unset($insertdata['googleAnalyticsAPIKey']); } if (isset($insertdata['allowjumps'])) { $insertdata['questionindex'] = $insertdata['allowjumps'] == "Y" ? 1 : 0; unset($insertdata['allowjumps']); } /* Remove unknow column */ $aSurveyModelsColumns = Survey::model()->attributes; $aSurveyModelsColumns['wishSID'] = null; // To force a sid surely $aBadData = array_diff_key($insertdata, $aSurveyModelsColumns); $insertdata = array_intersect_key($insertdata, $aSurveyModelsColumns); // Fill a optionnal array of error foreach ($aBadData as $key => $value) { $results['importwarnings'][] = sprintf($clang->gT("This survey setting has not been imported: %s => %s"), $key, $value); } $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />"); $pre_personal_characteristics = file_get_contents($newdirname . "/question.pstpl"); $results['surveys']++; } // Import survey languagesettings table =================================================================================== foreach ($xml->surveys_languagesettings->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!in_array($insertdata['surveyls_language'], $aLanguagesSupported)) { continue; } // Assign new survey ID $insertdata['surveyls_survey_id'] = $iNewSID; // Assign new survey name (if a copy) if ($sNewSurveyName != NULL) { $insertdata['surveyls_title'] = $sNewSurveyName; } if ($bTranslateInsertansTags) { $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']); if (isset($insertdata['surveyls_description'])) { $insertdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_description']); } if (isset($insertdata['surveyls_welcometext'])) { $insertdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_welcometext']); } if (isset($insertdata['surveyls_urldescription'])) { $insertdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_urldescription']); } if (isset($insertdata['surveyls_email_invite'])) { $insertdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_invite']); } if (isset($insertdata['surveyls_email_remind'])) { $insertdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_remind']); } if (isset($insertdata['surveyls_email_register'])) { $insertdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_register']); } if (isset($insertdata['surveyls_email_confirm'])) { $insertdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_confirm']); } } if (isset($insertdata['surveyls_attributecaptions']) && substr($insertdata['surveyls_attributecaptions'], 0, 1) != '{') { unset($insertdata['surveyls_attributecaptions']); } $result = SurveyLanguageSetting::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [2]<br />"); } // Import groups table =================================================================================== if (isset($xml->groups->rows->row)) { foreach ($xml->groups->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!in_array($insertdata['language'], $aLanguagesSupported)) { continue; } $iOldSID = $insertdata['sid']; $insertdata['sid'] = $iNewSID; $oldgid = $insertdata['gid']; unset($insertdata['gid']); // save the old qid // now translate any links if ($bTranslateInsertansTags) { $insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']); $insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']); } // Insert the new group if (isset($aGIDReplacements[$oldgid])) { switchMSSQLIdentityInsert('groups', true); $insertdata['gid'] = $aGIDReplacements[$oldgid]; } $newgid = QuestionGroup::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />"); if ($insertdata['group_name'] == 'Real Characteristics' || $insertdata['group_name'] == 'PC - Real Characteristics') { $question_groups['R'][] = $newgid; } else { if ($insertdata['group_name'] == 'Ideal Characteristics' || $insertdata['group_name'] == 'PC - Ideal Characteristics') { $question_groups['I'][] = $newgid; } else { if ($insertdata['group_name'] == 'Ought Characteristics' || $insertdata['group_name'] == 'PC - Ought Characteristics') { $question_groups['O'][] = $newgid; } } } $results['groups']++; if (!isset($aGIDReplacements[$oldgid])) { $aGIDReplacements[$oldgid] = $newgid; // add old and new qid to the mapping array } else { switchMSSQLIdentityInsert('groups', false); } } } // Import questions table =================================================================================== // We have to run the question table data two times - first to find all main questions // then for subquestions (because we need to determine the new qids for the main questions first) if (isset($xml->questions)) { foreach ($xml->questions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) { continue; } $iOldSID = $insertdata['sid']; $insertdata['sid'] = $iNewSID; $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']]; $oldqid = $insertdata['qid']; unset($insertdata['qid']); // save the old qid // now translate any links if ($bTranslateInsertansTags) { $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']); $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']); } // Insert the new question if (isset($aQIDReplacements[$oldqid])) { $insertdata['qid'] = $aQIDReplacements[$oldqid]; switchMSSQLIdentityInsert('questions', true); } if ($insertdata) { XSSFilterArray($insertdata); } if (!$bConvertInvalidQuestionCodes) { $sScenario = 'archiveimport'; } else { $sScenario = 'import'; } $oQuestion = new Question($sScenario); $oQuestion->setAttributes($insertdata, false); // Try to fix question title for valid question code enforcement if (!$oQuestion->validate(array('title'))) { $sOldTitle = $oQuestion->title; $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle); if (is_numeric(substr($sNewTitle, 0, 1))) { $sNewTitle = 'q' . $sNewTitle; } $oQuestion->title = $sNewTitle; } $attempts = 0; // Try to fix question title for unique question code enforcement while (!$oQuestion->validate(array('title'))) { if (!isset($index)) { $index = 0; $rand = mt_rand(0, 1024); } else { $index++; } $sNewTitle = 'r' . $rand . 'q' . $index; $oQuestion->title = $sNewTitle; $attempts++; if ($attempts > 10) { safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />"); } } if (!$oQuestion->save()) { // safeDie($clang->gT("Error while saving: "). print_r($oQuestion->errors, true)); // // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use) // For this reason we ignore insertion errors (because it is most likely a duplicate) // and continue with the next one continue; } // Set a warning if question title was updated if (isset($sNewTitle)) { $results['importwarnings'][] = sprintf($clang->gT("Question code %s was updated to %s."), $sOldTitle, $sNewTitle); $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle; unset($sNewTitle); unset($sOldTitle); } $newqid = $oQuestion->qid; if (!isset($aQIDReplacements[$oldqid])) { $aQIDReplacements[$oldqid] = $newqid; $results['questions']++; } else { switchMSSQLIdentityInsert('questions', false); } } } // Import subquestions ------------------------------------------------------- if (isset($xml->subquestions)) { foreach ($xml->subquestions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) { continue; } if (!isset($insertdata['mandatory']) || trim($insertdata['mandatory']) == '') { $insertdata['mandatory'] = 'N'; } $insertdata['sid'] = $iNewSID; $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']]; $oldsqid = (int) $insertdata['qid']; unset($insertdata['qid']); // save the old qid $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']]; // remap the parent_qid // now translate any links if ($bTranslateInsertansTags) { $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']); if (isset($insertdata['help'])) { $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']); } } if (isset($aQIDReplacements[$oldsqid])) { $insertdata['qid'] = $aQIDReplacements[$oldsqid]; switchMSSQLIdentityInsert('questions', true); } if ($insertdata) { XSSFilterArray($insertdata); } if (!$bConvertInvalidQuestionCodes) { $sScenario = 'archiveimport'; } else { $sScenario = 'import'; } $question = new Question($sScenario); $question->setAttributes($insertdata, false); // Try to fix question title for valid question code enforcement if (!$question->validate(array('title'))) { $sOldTitle = $question->title; $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle); if (is_numeric(substr($sNewTitle, 0, 1))) { $sNewTitle = 'sq' . $sNewTitle; } $question->title = $sNewTitle; } $attempts = 0; // Try to fix question title for unique question code enforcement while (!$question->validate(array('title'))) { if (!isset($index)) { $index = 0; $rand = mt_rand(0, 1024); } else { $index++; } $sNewTitle = 'r' . $rand . 'sq' . $index; $question->title = $sNewTitle; $attempts++; if ($attempts > 10) { safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />"); } } if (!$question->save()) { // safeDie($clang->gT("Error while saving: "). print_r($question->errors, true)); // // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use) // For this reason we ignore insertion errors (because it is most likely a duplicate) // and continue with the next one continue; } // Set a warning if question title was updated if (isset($sNewTitle)) { $results['importwarnings'][] = sprintf($clang->gT("Title of subquestion %s was updated to %s."), $sOldTitle, $sNewTitle); // Maybe add the question title ? $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle; unset($sNewTitle); unset($sOldTitle); } $newsqid = $question->qid; if (!isset($insertdata['qid'])) { $aQIDReplacements[$oldsqid] = $newsqid; // add old and new qid to the mapping array } else { switchMSSQLIdentityInsert('questions', false); } $results['subquestions']++; } } // Import answers ------------------------------------------------------------ if (isset($xml->answers)) { foreach ($xml->answers->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!in_array($insertdata['language'], $aLanguagesSupported) || !isset($aQIDReplacements[(int) $insertdata['qid']])) { continue; } $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid // now translate any links if ($bTranslateInsertansTags) { $insertdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['answer']); } if ($insertdata) { XSSFilterArray($insertdata); } if (Answer::model()->insertRecords($insertdata)) { $results['answers']++; } } } // Import questionattributes ------------------------------------------------- if (isset($xml->question_attributes)) { $aAllAttributes = questionAttributes(true); foreach ($xml->question_attributes->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } // take care of renaming of date min/max adv. attributes fields if ($iDBVersion < 170) { if (isset($insertdata['attribute'])) { if ($insertdata['attribute'] == 'dropdown_dates_year_max') { $insertdata['attribute'] = 'date_max'; } if ($insertdata['attribute'] == 'dropdown_dates_year_min') { $insertdata['attribute'] = 'date_min'; } } } unset($insertdata['qaid']); if (!isset($aQIDReplacements[(int) $insertdata['qid']])) { continue; } $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid if ($iDBVersion < 156 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) { foreach ($aLanguagesSupported as $sLanguage) { $insertdata['language'] = $sLanguage; if ($insertdata) { XSSFilterArray($insertdata); } $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[7]<br />"); } } else { $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[8]<br />"); } $results['question_attributes']++; } } // Import defaultvalues ------------------------------------------------------ if (isset($xml->defaultvalues)) { $results['defaultvalues'] = 0; foreach ($xml->defaultvalues->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid if (isset($aQIDReplacements[(int) $insertdata['sqid']])) { $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']]; } // remap the subquestion id if ($insertdata) { XSSFilterArray($insertdata); } // now translate any links $result = DefaultValue::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[9]<br />"); $results['defaultvalues']++; } } $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements); // Import conditions --------------------------------------------------------- if (isset($xml->conditions)) { $results['conditions'] = 0; foreach ($xml->conditions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record) if (isset($aQIDReplacements[$insertdata['qid']])) { $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']]; // remap the qid } else { continue; } // a problem with this answer record -> don't consider if ($insertdata['cqid'] != 0) { if (isset($aQIDReplacements[$insertdata['cqid']])) { $oldcqid = $insertdata['cqid']; //Save for cfield transformation $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']]; // remap the qid } else { continue; } // a problem with this answer record -> don't consider list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3); // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record) if (!isset($aGIDReplacements[$oldcgid])) { continue; } } unset($insertdata["cid"]); // recreate the cfieldname with the new IDs if ($insertdata['cqid'] != 0) { if (preg_match("/^\\+/", $oldcsid)) { $newcfieldname = '+' . $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid)); } else { $newcfieldname = $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid)); } } else { // The cfieldname is a not a previous question cfield but a {XXXX} replacement field $newcfieldname = $insertdata["cfieldname"]; } $insertdata["cfieldname"] = $newcfieldname; if (trim($insertdata["method"]) == '') { $insertdata["method"] = '=='; } // Now process the value and replace @sgqa@ codes if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) { if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) { $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@'; $insertdata["value"] = $newvalue; } } // now translate any links $result = Condition::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[10]<br />"); $results['conditions']++; } } // TMSW Condition->Relevance: Call LEM->ConvertConditionsToRelevance // Import assessments -------------------------------------------------------- if (isset($xml->assessments)) { foreach ($xml->assessments->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if ($insertdata['gid'] > 0) { $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']]; // remap the qid } $insertdata['sid'] = $iNewSID; // remap the survey id unset($insertdata['id']); // now translate any links $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[11]<br />"); $results['assessments']++; } } // Import quota -------------------------------------------------------------- if (isset($xml->quota)) { foreach ($xml->quota->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $iNewSID; // remap the survey id $oldid = $insertdata['id']; unset($insertdata['id']); // now translate any links $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[12]<br />"); $aQuotaReplacements[$oldid] = getLastInsertID('{{quota}}'); $results['quota']++; } } // Import quota_members ------------------------------------------------------ if (isset($xml->quota_members)) { foreach ($xml->quota_members->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $iNewSID; // remap the survey id $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']]; // remap the qid unset($insertdata['id']); // now translate any links $result = QuotaMember::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[13]<br />"); $results['quotamembers']++; } } // Import quota_languagesettings---------------------------------------------- if (isset($xml->quota_languagesettings)) { foreach ($xml->quota_languagesettings->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']]; // remap the qid unset($insertdata['quotals_id']); $result = QuotaLanguageSetting::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />"); $results['quotals']++; } } // Import survey_url_parameters ---------------------------------------------- if (isset($xml->survey_url_parameters)) { foreach ($xml->survey_url_parameters->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $iNewSID; // remap the survey id if (isset($insertdata['targetsqid']) && $insertdata['targetsqid'] != '') { $insertdata['targetsqid'] = $aQIDReplacements[(int) $insertdata['targetsqid']]; // remap the qid } if (isset($insertdata['targetqid']) && $insertdata['targetqid'] != '') { $insertdata['targetqid'] = $aQIDReplacements[(int) $insertdata['targetqid']]; // remap the qid } unset($insertdata['id']); $result = SurveyURLParameter::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[14]<br />"); $results['survey_url_parameters']++; } } // Set survey rights Permission::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID); $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements); $results['FieldReMap'] = $aOldNewFieldmap; LimeExpressionManager::SetSurveyId($iNewSID); translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap); replaceExpressionCodes($iNewSID, $aQuestionCodeReplacements); if (count($aQuestionCodeReplacements)) { array_unshift($results['importwarnings'], "<span class='warningtitle'>" . $clang->gT('Attention: Several question codes were updated. Please check these carefully as the update may not be perfect with customized expressions.') . '</span)>'); } LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID); LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID); $js_variables = array(); if (!empty($question_groups['R'])) { $real_count = 1; $ideal_count = 1; $ought_count = 1; foreach ($results['FieldReMap'] as $code) { $value = explode('X', $code); if (isset($value[1]) && in_array($value[1], $question_groups['R'])) { if (!array_key_exists((int) $value[1], $js_variables)) { $int = substr($value[2], 0, strpos($value[2], 'PC')); $js_variables[$value[1]] = "var realGroupId" . $real_count . " = " . $value[1] . ";"; $js_variables[$value[1] . "-q"] = "var realQuestionId" . $real_count . " = " . $int . ";"; $real_count++; } } else { if (isset($value[1]) && in_array($value[1], $question_groups['I'])) { if (!array_key_exists((int) $value[1], $js_variables)) { $int = substr($value[2], 0, strpos($value[2], 'PC')); $js_variables[$value[1]] = "var idealGroupId" . $ideal_count . " = " . $value[1] . ";"; $js_variables[$value[1] . "-q"] = "var idealQuestionId" . $ideal_count . " = " . $int . ";"; $ideal_count++; } } else { if (isset($value[1]) && in_array($value[1], $question_groups['O'])) { if (!array_key_exists((int) $value[1], $js_variables)) { $int = substr($value[2], 0, strpos($value[2], 'PC')); $js_variables[$value[1]] = "var oughtGroupId" . $ought_count . " = " . $value[1] . ";"; $js_variables[$value[1] . "-q"] = "var oughtQuestionId" . $ought_count . " = " . $int . ";"; $ought_count++; } } } } } $js_variables[] = "var surveyId = " . $value[0] . ";"; } if (!empty($js_variables)) { $pre_personal_characteristics = str_replace("[REPLACE_ME]", implode(PHP_EOL, $js_variables), $pre_personal_characteristics); } else { $pre_personal_characteristics = '<div {QUESTION_ESSENTIALS} class="{QUESTION_CLASS}{QUESTION_MAN_CLASS}{QUESTION_INPUT_ERROR_CLASS}"> <div class="survey-question"> <div class="survey-question-text"> <span class="asterisk">{QUESTION_MANDATORY}</span><span class="qnumcode"> {QUESTION_NUMBER} {QUESTION_CODE} </span>{QUESTION_TEXT}<br /><span class="questionhelp">{QUESTION_HELP}</span> {QUESTION_MAN_MESSAGE} {QUESTION_VALID_MESSAGE} {QUESTION_FILE_VALID_MESSAGE} </div> <div class="survey-question-answer">{ANSWER}</div> <div class="survey-question-help">{QUESTIONHELP}</div> </div> <div class="survey-question-space"></div> </div>'; } file_put_contents($newdirname . "/question.pstpl", $pre_personal_characteristics); return $results; }
/** * Function responsible to copy a template. * * @access public * @return void */ public function templatecopy() { if (!Permission::model()->hasGlobalPermission('templates', 'create')) { die('No permission'); } $clang = $this->getController()->lang; $newname = sanitize_dirname(Yii::app()->request->getPost("newname")); $copydir = sanitize_dirname(Yii::app()->request->getPost("copydir")); $action = Yii::app()->request->getPost("action"); if ($newname && $copydir) { // Copies all the files from one template directory to a new one Yii::app()->loadHelper('admin/template'); $newdirname = Yii::app()->getConfig('usertemplaterootdir') . "/" . $newname; $copydirname = getTemplatePath($copydir); $oFileHelper = new CFileHelper(); $mkdirresult = mkdir_p($newdirname); if ($mkdirresult == 1) { $oFileHelper->copyDirectory($copydirname, $newdirname); $templatename = $newname; $this->getController()->redirect(array("admin/templates/sa/view", 'templatename' => $newname)); } elseif ($mkdirresult == 2) { Yii::app()->setFlashMessage(sprintf($clang->gT("Directory with the name `%s` already exists - choose another name"), $newname), 'error'); $this->getController()->redirect(array("admin/templates/sa/view", 'templatename' => $copydir)); } else { Yii::app()->setFlashMessage(sprintf($clang->gT("Unable to create directory `%s`."), $newname), 'error'); Yii::app()->setFlashMessage($clang->gT("Please check the directory permissions.")); $this->getController()->redirect(array("admin/templates/sa/view")); } } else { $this->getController()->redirect(array("admin/templates/sa/view")); } }
/** * Run this action like this: yiic myAction uploadIronWorker * * This command can be integrated to your deployment system. When you have committed your code you can * run this command to deploy the code to the iron.io servers. * * This command zips all the code needed to be uploaded to the Iron Workers * Upload the zipped file to Iron Workers. This will create a new version of the code for the current project * * It will also create a task in the iron.io hud named after the command file. All the actions in this command file * will run as this task on iron.io. * * It prepares all the files in the runtoime directory and cleans up when finished. * TODO: Test in Windows environment */ public function actionUploadIronWorker() { /** * The EYiiron class instance. It is our gateway to all iron.io services * @var EYiiron $yiiron */ $yiiron = Yii::app()->yiiron; //This is where we store the files before deploying them on iron.io $tmpDir = Yii::app()->getRuntimePath() . DIRECTORY_SEPARATOR . 'ironworkers' . DIRECTORY_SEPARATOR; echo "Using PHP Stack :" . $yiiron->stack . "\n"; //Clean up in the directory. We do this before we start in case the old code was not fully removed. EIronWorkersCommand::deleteDir($tmpDir); //Make sure we have a clean environment before preparing the runtime environment for iron.io. //THis is crucial so we know that the code we deploy is exactly the same as we run locally. if (!file_exists($tmpDir)) { echo $tmpDir . " doesn't exist creating it now...\n"; if (!mkdir($tmpDir)) { echo "**Error**: Creation failed. Please check your permissions!\n"; exit(0); } } else { echo "**Error**: " . $tmpDir . " existed even though we tried to fully remove it.\n" . "It could be a permission problem please remove " . $tmpDir . " manually before running this command again.\n"; exit(0); } echo "Copying Yii Framework to tmp dir...\n"; /** * The Framework path * @var string $yiiPath */ $yiiPath = Yii::getFrameworkPath() . "/../"; /** * The path of your Yii app. Usually the protected folder * @var string $appPath */ $appPath = Yii::app()->getBasePath() . "/"; echo "Yii path: " . $yiiPath . "\n"; CFileHelper::copyDirectory($yiiPath, $tmpDir . 'yii'); echo "Copying app from " . $appPath . " to the tmp dir " . $tmpDir . 'app/' . basename($appPath) . "\n"; //Exclude as much as we can to get a slim file to upload CFileHelper::copyDirectory($appPath, $tmpDir . 'app/' . basename($appPath), Yii::app()->yiiron->workerFileCopyOptions); echo "Zipping code to " . $tmpDir . "iron_worker.zip\n"; IronWorker::zipDirectory($tmpDir, $tmpDir . 'iron_worker.zip', true); echo "Uploading the code for the worker " . $this->name . "...\n"; //This is so we can handle custom extension paths $ironWorkerExtensionPath = str_replace($appPath, "app/" . basename($appPath) . "/", Yii::app()->getExtensionPath()); //Read the config array into an array $configFile = json_encode(require $appPath . $yiiron->configFile); //Posting the code and the initial php file to execute. This on the Iron Worker platform, not locally $res = $yiiron->workerPostCode($ironWorkerExtensionPath . "/yiiron/yiic-yiiron.php", $tmpDir . 'iron_worker.zip', $this->getName(), array('config' => $configFile, 'stack' => $yiiron->stack)); echo "Finished uploading iron_worker.zip (" . EIronWorkersCommand::format_bytes(filesize($tmpDir . 'iron_worker.zip')) . ")\n"; //Remove all files echo "Remove all temp files...\n"; //EIronWorkersCommand::deleteDir($tmpDir); echo "Done!\n"; echo "Find the worker here http://hud.iron.io/tq/projects/" . Yii::app()->yiiron->projectId . "/tasks/" . $res->id . "/activity\n"; echo "Now run your command like this: './yiic " . $this->name . " myAction --ironWorker=true' to execute it as an Iron Worker.\n"; }
protected function copyImagesToTmp($path) { if (is_dir($path)) { echo " Copying images to tmpdir [" . $path . "].\n"; CFileHelper::copyDirectory($path, $this->tmpPath, array('fileTypes' => array('jpg', 'jpeg', 'png', 'gif', 'css'), 'level' => 0)); } }
public function publish($path,$hashByName=false,$level=-1,$forceCopy=false) { if($forceCopy===null) $forceCopy=$this->forceCopy; if(isset($this->_published[$path])) return $this->_published[$path]; else if(($src=realpath($path))!==false) { if(is_file($src)) { $dir=$this->hash($hashByName ? basename($src) : dirname($src).filemtime($src)); $fileName=basename($src); $dstDir=$this->getBasePath().DIRECTORY_SEPARATOR.$dir; $suffix=pathinfo($src, PATHINFO_EXTENSION); if (array_key_exists($suffix, $this->parsers)) { $fileName=basename($src, $suffix).$this->parsers[$suffix]['output']; } $dstFile=$dstDir.DIRECTORY_SEPARATOR.$fileName; if ($this->linkAssets) { if(!is_file($dstFile)) { if(!is_dir($dstDir)) { mkdir($dstDir); @chmod($dstDir, $this->newDirMode); } symlink($src,$dstFile); } } else if(@filemtime($dstFile)<@filemtime($src)) { if(!is_dir($dstDir)) { mkdir($dstDir); @chmod($dstDir, $this->newDirMode); } if (array_key_exists($suffix, $this->parsers)) { $parserClass = Yii::import($this->parsers[$suffix]['class']); $parser = new $parserClass($this->parsers[$suffix]['options']); file_put_contents($dstFile, $parser->parse($src)); } else { copy($src,$dstFile); } @chmod($dstFile, $this->newFileMode); } return $this->_published[$path]=$this->getBaseUrl()."/$dir/$fileName"; } else if(is_dir($src)) { $dir=$this->hash($hashByName ? basename($src) : $src.filemtime($src)); $dstDir=$this->getBasePath().DIRECTORY_SEPARATOR.$dir; if($this->linkAssets) { if(!is_dir($dstDir)) symlink($src,$dstDir); } else if(!is_dir($dstDir) || $forceCopy) { CFileHelper::copyDirectory($src,$dstDir,array( 'exclude'=>$this->excludeFiles, 'level'=>$level, 'newDirMode'=>$this->newDirMode, 'newFileMode'=>$this->newFileMode, )); } return $this->_published[$path]=$this->getBaseUrl().'/'.$dir; } } throw new CException(Yii::t('yii','The asset "{asset}" to be published does not exist.', array('{asset}'=>$path))); }
/** * Function responsible to copy a template. * * @access public * @return void */ public function templatecopy() { $clang = $this->getController()->lang; if (returnGlobal('action') == "templatecopy" && returnGlobal('newname') && returnGlobal('copydir')) { // Copies all the files from one template directory to a new one // This is a security issue because it is allowing copying from get variables... Yii::app()->loadHelper('admin/template'); $newname = sanitize_paranoid_string(returnGlobal('newname')); $newdirname = Yii::app()->getConfig('usertemplaterootdir') . "/" . $newname; $copydirname = getTemplatePath(returnGlobal('copydir')); $oFileHelper = new CFileHelper(); $mkdirresult = mkdir_p($newdirname); if ($mkdirresult == 1) { $oFileHelper->copyDirectory($copydirname, $newdirname); $templatename = $newname; $this->index("startpage.pstpl", "welcome", $templatename); } elseif ($mkdirresult == 2) { $this->getController()->error(sprintf($clang->gT("Directory with the name `%s` already exists - choose another name", "js"), $newname)); } else { $this->getController()->error(sprintf($clang->gT("Unable to create directory `%s`.", "js"), $newname) . " " . $clang->gT("Please check the directory permissions.", "js")); } } }
/** * Publishes a file or a directory. * This method will copy the specified asset to a web accessible directory * and return the URL for accessing the published asset. * <ul> * <li>If the asset is a file, its file modification time will be checked * to avoid unnecessary file copying;</li> * <li>If the asset is a directory, all files and subdirectories under it will * be published recursively. Note, in this case the method only checks the * existence of the target directory to avoid repetitive copying.</li> * </ul> * @param string the asset (file or directory) to be published * @param boolean whether the published directory should be named as the hashed basename. * If false, the name will be the hashed dirname of the path being published. * Defaults to false. Set true if the path being published is shared among * different suffixs. * @param integer level of recursive copying when the asset is a directory. * Level -1 means publishing all subdirectories and files; * Level 0 means publishing only the files DIRECTLY under the directory; * level N means copying those directories that are within N levels. * @return string an absolute URL to the published asset * @throws CException if the asset to be published does not exist. */ public function publish($path, $hashByName = false, $level = -1) { if (isset($this->_published[$path])) { return $this->_published[$path]; } else { if (($src = realpath($path)) !== false) { if (is_file($src)) { $dir = $this->hash($hashByName ? basename($src) : dirname($src)); $fileName = basename($src); $suffix = substr(strrchr($fileName, '.'), 1); $dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir; if (array_key_exists($suffix, $this->parsers)) { $fileName = basename($src, $suffix); $fileName = basename($src, $suffix) . $this->parsers[$suffix]['output']; } $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName; if ($this->force || @filemtime($dstFile) < @filemtime($src)) { if (!is_dir($dstDir)) { mkdir($dstDir); @chmod($dstDir, 0777); } if (array_key_exists($suffix, $this->parsers)) { $parserClass = Yii::import($this->parsers[$suffix]['class']); $parser = new $parserClass($this->parsers[$suffix]['options']); file_put_contents($dstFile, $parser->parse($src)); } else { copy($src, $dstFile); } } return $this->_published[$path] = $this->getBaseUrl() . "/{$dir}/{$fileName}"; } else { if (is_dir($src)) { $dir = $this->hash($hashByName ? basename($src) : $src); $dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir; if (!is_dir($dstDir)) { CFileHelper::copyDirectory($src, $dstDir, array('exclude' => array('.svn'), 'level' => $level)); } return $this->_published[$path] = $this->getBaseUrl() . '/' . $dir; } } } } throw new CException(Yii::t('yii', 'The asset "{asset}" to be published does not exist.', array('{asset}' => $path))); }
/** * Publishes a file or a directory. * This method will copy the specified asset to a web accessible directory * and return the URL for accessing the published asset. * <ul> * <li>If the asset is a file, its file modification time will be checked * to avoid unnecessary file copying;</li> * <li>If the asset is a directory, all files and subdirectories under it will * be published recursively. Note, in this case the method only checks the * existence of the target directory to avoid repetitive copying.</li> * </ul> * @param string the asset (file or directory) to be published * @param boolean whether the published directory should be named as the hashed basename. * If false, the name will be the hashed dirname of the path being published. * Defaults to false. Set true if the path being published is shared among * different extensions. * @param integer level of recursive copying when the asset is a directory. * Level -1 means publishing all subdirectories and files; * Level 0 means publishing only the files DIRECTLY under the directory; * level N means copying those directories that are within N levels. * @return string an absolute URL to the published asset * @throws CException if the asset to be published does not exist. */ public function publish($path, $hashByName = false, $level = -1) { if (isset($this->_published[$path])) { return $this->_published[$path]; } else { if (($src = realpath($path)) !== false) { if (is_file($src)) { $dir = $this->hash($hashByName ? basename($src) : dirname($src)); $fileName = basename($src); $dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir; $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName; if (@filemtime($dstFile) < @filemtime($src)) { if (!is_dir($dstDir)) { mkdir($dstDir); @chmod($dstDir, 0777); } copy($src, $dstFile); } return $this->_published[$path] = $this->getBaseUrl() . "/{$dir}/{$fileName}"; } else { if (is_dir($src)) { $dir = $this->hash($hashByName ? basename($src) : $src); $dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir; if (!is_dir($dstDir)) { CFileHelper::copyDirectory($src, $dstDir, array('exclude' => array('.svn'), 'level' => $level)); } return $this->_published[$path] = $this->getBaseUrl() . '/' . $dir; } } } } throw new CException(Yii::t('yii', 'The asset "{asset}" to be published does not exist.', array('{asset}' => $path))); }
protected function buildOfflinePages($docPath, $themePath) { $this->themePath = $themePath; @mkdir($docPath); $content = $this->render('index', null, true); $content = preg_replace_callback(self::URL_PATTERN, array($this, 'fixOfflineLink'), $content); file_put_contents($docPath . '/index.html', $content); foreach ($this->classes as $name => $class) { $this->currentClass = $name; $this->pageTitle = $name . ' « API « ' . Yii::app()->name; $content = $this->render('class', array('class' => $class), true); $content = preg_replace_callback(self::URL_PATTERN, array($this, 'fixOfflineLink'), $content); file_put_contents($docPath . '/' . $name . '.html', $content); } if ($this->enableViews) { foreach ($this->views as $path => $view) { $this->currentView = $path; $this->pageTitle = $view->name; $content = $this->render('view', array('view' => $view), true); $content = preg_replace_callback(self::URL_PATTERN, array($this, 'fixOfflineLink'), $content); file_put_contents($docPath . '/' . $view->package . "." . $view->name . '.html', $content); } } CFileHelper::copyDirectory($this->themePath . '/assets', $docPath, array('exclude' => array('.svn'))); $content = $this->renderPartial('chmProject', null, true); file_put_contents($docPath . '/manual.hhp', $content); $content = $this->renderPartial('chmIndex', null, true); file_put_contents($docPath . '/manual.hhk', $content); $content = $this->renderPartial('chmContents', null, true); file_put_contents($docPath . '/manual.hhc', $content); }