/** * Copy a module directory structure from the tests/data directory */ protected function setupModule($moduleName) { $baseDir = Yii::app()->basePath; $src = implode(DIRECTORY_SEPARATOR, array($baseDir, 'tests', 'data', 'testModules', $moduleName)); $dest = implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, 'modules', $moduleName)); $this->assertTrue(FileUtil::ccopy($src, $dest)); }
public function setUp() { $baseDir = Yii::app()->basePath; $src = implode(DIRECTORY_SEPARATOR, array($baseDir, 'tests', 'data', 'mediaMigration')); $this->mediaSrc = $src; $dest = implode(DIRECTORY_SEPARATOR, array($baseDir, '..', 'uploads')); $this->mediaDest = $dest; $this->migrationDest = $dest . DIRECTORY_SEPARATOR . 'protected'; $this->testMediaCount = count(array_diff(scandir($this->mediaSrc), $this->exclude)); $this->mediaCount = count(array_diff(scandir($this->mediaDest), $this->exclude)); $this->migrationCount = count(array_diff(scandir($this->migrationDest), $this->exclude)); $this->assertTrue(FileUtil::ccopy($src, $dest)); }
/** * Save uploaded file and add associated media object */ public function saveAssociatedMedia($file) { if (!$file instanceof CUploadedFile) { return; } $fileAttribute = $this->fileAttribute; $media = new Media(); $username = Yii::app()->user->getName(); // file uploaded through form $tempName = $file->getTempName(); $media->setAttributes(array('associationType' => $this->associationType, 'associationId' => $this->getAssociationId(), 'uploadedBy' => $username, 'createDate' => time(), 'lastUpdated' => time(), 'fileName' => preg_replace('/ /', '_', $file->getName()), 'mimetype' => $file->type), false); $media->resolveNameConflicts(); if (!$media->save()) { throw new CException(implode(';', $media->getAllErrorMessages())); } if (!FileUtil::ccopy($tempName, "uploads/protected/media/{$username}/{$media->fileName}")) { throw new CException(); } }
/** * Create file system for a custom module * * This method is called by {@link AdminController::actionCreateModule} as a * part of creating a new module. This method copies all the proper files to * their new directories, renames them, and replaces the contents to fit the * new module name. * * @param string $moduleName The name of the module being created */ private function createSkeletonDirectories($moduleName) { $errors = array(); $templateFolderPath = 'protected/modules/template/'; $moduleFolderPath = 'protected/modules/' . $moduleName . '/'; $moduleFolder = Yii::app()->file->set($moduleFolderPath); if (!$moduleFolder->exists && $moduleFolder->createDir() === false) { throw new Exception('Error creating module folder "' . $moduleFolderPath . '".'); } if (Yii::app()->file->set($templateFolderPath)->copy($moduleName) === false) { throw new Exception('Error copying Template folder "' . $templateFolderPath . '".'); } // list of files to process $fileNames = array('register.php', 'templatesConfig.php', 'TemplatesModule.php', 'controllers/TemplatesController.php', 'data/install.sql', 'data/uninstall.sql', 'models/Templates.php', 'views/templates/_search.php', 'views/templates/_view.php', 'views/templates/admin.php', 'views/templates/create.php', 'views/templates/index.php', 'views/templates/update.php', 'views/templates/view.php'); foreach ($fileNames as $fileName) { // calculate proper file name $fileName = $moduleFolderPath . $fileName; $file = Yii::app()->file->set($fileName); if (!$file->exists) { throw new Exception('Unable to find template file "' . $fileName . '".'); } // rename files $newFileName = str_replace(array('templates', 'Templates'), array($moduleName, ucfirst($moduleName)), $file->filename); if ($file->setFileName($newFileName) === false) { throw new Exception('Error renaming template file "' . $fileName . '" to "' . $newFileName . '".'); } // chmod($file->filename, 0755); // $file->setPermissions(0755); // replace "template", "Templates", etc within the file $contents = $file->getContents(); $contents = str_replace(array('templates', 'Templates'), array($moduleName, ucfirst($moduleName)), $contents); if ($file->setContents($contents) === false) { throw new Exception('Error modifying template file "' . $newFileName . '".'); } } if (!is_dir('protected/modules/' . $moduleName . '/views/' . $moduleName)) { rename('protected/modules/' . $moduleName . '/views/templates', 'protected/modules/' . $moduleName . '/views/' . $moduleName); } else { FileUtil::ccopy('protected/modules/' . $moduleName . '/views/templates', 'protected/modules/' . $moduleName . '/views/' . $moduleName); } }
/** * Copies a file or directory recursively. * * If the local filesystem directory to where the file will be copied does * not exist yet, it will be created automatically. Furthermore, if a remote * URL is being accessed and allow_url_fopen isn't set, it will attempt to * use CURL instead. * * @param string $source The source file. * @param string $target The destination path. * @param boolean $relTarget Transform the target to a relative path. This * option must be false unless the target is an absolute path. * @param boolean $contents If true, and the source is a directory, its * contents will be copied to the destination; otherwise, the whole directory * will be copied into the destination directory. * @return boolean */ public static function ccopy($source, $target, $relTarget = false, $contents = true) { $ds = DIRECTORY_SEPARATOR; $remote = (bool) preg_match('%^https?://%', $source); // Normalize target to the form where if it's a directory it doesn't have // a trailing slash, and is platform-agnostic: $target = rtrim(self::rpath($target), $ds); // Make the target into a relative path: if ($relTarget && self::$fileOper !== 'ftp') { $target = self::relpath($target); } // Safeguard against overwriting files: if (!$remote && is_dir($source) && !is_dir($target) && is_file($target)) { throw new Exception("Cannot copy a directory ({$source}) into a file ({$target})."); } // Create parent directories if they don't exist already. // // If a file is being copied: the path to examine for directory creation // is one lower than the target (the bottom-level parent). // If a directory is being copied: the same is true (to not create the // top level node) even though it's a directory, because the target // directory will be created anyway if necessary // If a directory is being copied and $contents is false: it's assumed // that the target is a destination directory and not part of the tree // to be copied. $pathNodes = explode($ds, self::ftpStripChroot($target)); if ($contents) { array_pop($pathNodes); } for ($i = 0; $i <= count($pathNodes); $i++) { $parent = implode($ds, array_slice($pathNodes, 0, $i)); // If we are using an FTP chroot, prepend the $parent path with the chroot dir // so that is_dir() is accurate. if (self::$fileOper === 'ftp' && self::$ftpChroot !== false && !self::isRelative($parent)) { $verifyDir = self::$ftpChroot . $parent; } else { $verifyDir = $parent; } if ($parent != '' && !is_dir($verifyDir)) { switch (self::$fileOper) { case 'ftp': if (!@ftp_mkdir(self::$_ftpStream, self::ftpStripChroot($parent))) { throw new Exception("Failed to create directory {$parent}", self::ERR_FTPOPER); } break; case 'php': default: if (!@mkdir($parent)) { throw new Exception("Failed to create directory {$parent}"); } } } } if ($remote) { if (self::tryCurl($source)) { // Fall back on the getContents method, which will try using CURL $ch = self::curlInit($source); $contents = curl_exec($ch); if ((bool) $contents) { return @file_put_contents($target, $contents) !== false; } else { return false; } } else { $context = stream_context_create(array('http' => array('timeout' => 15))); return @copy($source, $target, $context) !== false; } } else { // Recursively copy a whole folder $source = self::rpath($source); if (!is_dir($source) && !file_exists($source)) { throw new Exception("Source file/directory to be copied ({$source}) not found."); } if (is_dir($source)) { if (!$contents) { // Append the bottom level node in the source path to the // target path. // // This ensures that we copy in the aptly-named target // directory instead of dumping the contents of the source // into the designated target. $source = rtrim($source, $ds); $sourceNodes = explode($ds, $source); $target = $target . $ds . array_pop($sourceNodes); } if (!is_dir($target)) { switch (self::$fileOper) { case 'ftp': if (!@ftp_mkdir(self::$_ftpStream, self::ftpStripChroot($target))) { throw new Exception("Unable to create directory {$target}", self::ERR_FTPOPER); } break; case 'php': default: mkdir($target); } } $return = true; $files = scandir($source); foreach ($files as $file) { if ($file != '.' && $file != '..') { // Must be recursively called with $relTarget = false // because if ccopy is called with $relTarget = true, // then at this stage "$target" is already relative, // and the argument passed to relpath must be absolute. // It also must be called with contents=true because // that option, if enabled at lower levels, will create // the parent directory twice. $return = $return && FileUtil::ccopy($source . $ds . $file, $target . $ds . $file); } } return $return; } else { switch (self::$fileOper) { case 'ftp': return @ftp_put(self::$_ftpStream, self::ftpStripChroot($target), $source, FTP_BINARY); case 'php': default: $retVal = @copy($source, $target) !== false; self::caseInsensitiveCopyFix($source, $target); return $retVal; } } } }
public function save($runValidation = true, $attributes = null) { if ($this->photo) { // save related photo record $transaction = Yii::app()->db->beginTransaction(); try { // save the event $ret = parent::save($runValidation, $attributes); if (!$ret) { throw new CException(implode(';', $this->getAllErrorMessages())); } // add media record for file $media = new Media(); $media->setAttributes(array('fileName' => $this->photo->getName(), 'mimetype' => $this->photo->type), false); $media->resolveNameConflicts(); if (!$media->save()) { throw new CException(implode(';', $media->getAllErrorMessages())); } // save the file $tempName = $this->photo->getTempName(); $username = Yii::app()->user->getName(); if (!FileUtil::ccopy($tempName, "uploads/protected/media/{$username}/{$media->fileName}")) { throw new CException(); } // relate file to event $join = new RelationshipsJoin('insert', 'x2_events_to_media'); $join->eventsId = $this->id; $join->mediaId = $media->id; if (!$join->save()) { throw new CException(implode(';', $join->getAllErrorMessages())); } $transaction->commit(); return $ret; } catch (CException $e) { $transaction->rollback(); return false; } } else { return parent::save($runValidation, $attributes); } }
/** * Test copying the requirements checker script. * * NOTE: the requirements checker (which gets deleted) will need to be copied back first. */ public function testRemoteCopy() { $outdir = implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, 'tests', 'data', 'output', 'remoteCopy')); $copy = $outdir . DIRECTORY_SEPARATOR . 'index-copy.php'; $curl = $outdir . DIRECTORY_SEPARATOR . 'index-curl.php'; $file = 'index.php'; $live = implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, '..', $file)); // Using "copy": FileUtil::ccopy("http://x2planet.com/updates/x2engine/{$file}", $copy); // Using cURL: FileUtil::$alwaysCurl = true; FileUtil::ccopy("http://x2planet.com/updates/x2engine/{$file}", $curl); FileUtil::$alwaysCurl = false; // Test that the files are identical: $this->assertFileEquals($copy, $curl); // Test that the first 4 bytes of the file are identical to the locally-stored file: $afh = fopen($live, 'rb'); $cfh = fopen($copy, 'rb'); $ufh = fopen($curl, 'rb'); $aread = fread($afh, 4); $this->assertEquals($aread, fread($cfh, 4)); $this->assertEquals($aread, fread($ufh, 4)); fclose($afh); fclose($cfh); fclose($ufh); unlink($copy); unlink($curl); }
public function testDeleteUpload() { $source = implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, 'tests', 'data', 'media', 'testfile.txt')); $dest = implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, '..', 'uploads', 'media', 'admin', 'testfile.txt')); FileUtil::ccopy($source, $dest); $dest = realpath($dest); $testfile = $this->media("testfile"); $this->assertFileExists($dest); $testfile->delete(); $this->assertFileNotExists($dest); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Topics(); $fileCreation = false; if (isset($_FILES['upload']) || isset($_POST['Topics'])) { $data = array(); $topicText = null; if (isset($_FILES['upload'])) { $fileCreation = true; $data = array('name' => $_POST['topicName']); $topicText = $_POST['topicText']; } else { if (isset($_POST['Topics'])) { $data = $_POST['Topics']; $topicText = $_POST['TopicReplies']['text']; } } $data['text'] = $topicText; $model->setX2Fields($data, false, true); if (isset($_POST['x2ajax'])) { $ajaxErrors = $this->quickCreate($model); } else { if ($model->save()) { if ($fileCreation) { $media = new Media(); $username = Yii::app()->user->getName(); // file uploaded through form $temp = CUploadedFile::getInstanceByName('upload'); if ($temp && ($tempName = $temp->getTempName()) && !empty($tempName)) { $name = $temp->getName(); $name = str_replace(' ', '_', $name); $check = Media::model()->findAllByAttributes(array('fileName' => $name)); // rename file if there name conflicts by suffixing "(n)" if (count($check) != 0) { $count = 1; $newName = $name; $arr = explode('.', $name); $name = $arr[0]; while (count($check) != 0) { $newName = $name . '(' . $count . ').' . $temp->getExtensionName(); $check = Media::model()->findAllByAttributes(array('fileName' => $newName)); $count++; } $name = $newName; } } if (FileUtil::ccopy($tempName, "uploads/protected/media/{$username}/{$name}")) { $media->associationType = 'topicReply'; $media->associationId = $model->originalPost->id; $media->uploadedBy = $username; $media->createDate = time(); $media->lastUpdated = time(); $media->fileName = $name; $media->mimetype = $temp->type; if ($media->save()) { echo $model->id; Yii::app()->end(); } } } else { $this->redirect(array('view', 'id' => $model->id)); } } elseif ($model->hasErrors('text')) { Yii::app()->user->setFlash('error', 'Original post text cannot be blank.'); } } } if (isset($_POST['x2ajax']) || isset($_FILES['upload'])) { $this->renderInlineForm($model); } else { $this->render('create', array('model' => $model)); } }
/** * Retrieves a file from the update server. It will be stored in a temporary * directory, "tmp", in the web root. To copy it into the live install, use * restoreBackup on target "tmp". * * @param string $route Route relative to the web root of the web root path in the X2Engine source code * @param string $file Path relative to the X2Engine web root of the file to be downloaded * @param integer $maxAttempts Maximum times to attempt to download the file before giving up and throwing an exception. * @return boolean * @throws Exception */ public function downloadSourceFile($file, $route = null, $maxAttempts = 5) { if (empty($route)) { // Auto-construct a route based on ID & edition info: $route = $this->sourceFileRoute; } $fileUrl = "{$this->updateServer}/{$route}/" . strtr($file, array(' ' => '%20')); $i = 0; if ($file != "") { $target = FileUtil::relpath(implode(DIRECTORY_SEPARATOR, array($this->webRoot, self::TMP_DIR, FileUtil::rpath($file))), $this->thisPath . DIRECTORY_SEPARATOR); while (!FileUtil::ccopy($fileUrl, $target) && $i < $maxAttempts) { $i++; } } if ($i >= $maxAttempts) { throw new CException(Yii::t('admin', "Failed to download source file {file}. Check that the file is available on the update server at {fileUrl}, and that x2planet.com can be accessed from this web server.", array('{file}' => $file, '{fileUrl}' => $fileUrl)), self::ERR_UPSERVER); } return true; }
/** * Upload contact profile picture from Facebook. */ public function actionUploadProfilePicture() { if (isset($_POST['photourl'])) { $photourl = $_POST['photourl']; $name = 'profile_picture_' . $_POST['associationId'] . '.jpg'; $model = new Media(); $check = Media::model()->findAllByAttributes(array('fileName' => $name)); if (count($check) != 0) { $count = 1; $newName = $name; $arr = explode('.', $name); $name = $arr[0]; while (count($check) != 0) { $newName = $name . '(' . $count . ').jpg'; $check = Media::model()->findAllByAttributes(array('fileName' => $newName)); $count++; } $name = $newName; } $model->associationId = $_POST['associationId']; $model->associationType = $_POST['type']; $model->createDate = time(); $model->fileName = $name; // download and save picture $img = FileUtil::ccopy($photourl, "uploads/{$name}"); $model->save(); // put picture into new action $note = new Actions(); $note->createDate = time(); $note->dueDate = time(); $note->completeDate = time(); $note->complete = 'Yes'; $note->visibility = '1'; $note->completedBy = "Web Lead"; $note->assignedTo = 'Anyone'; $note->type = 'attachment'; $note->associationId = $_POST['associationId']; $note->associationType = $_POST['type']; $association = $this->getAssociation($note->associationType, $note->associationId); if ($association != null) { $note->associationName = $association->name; } $note->actionDescription = $model->fileName . ':' . $model->id; if ($note->save()) { } else { unlink('uploads/' . $name); } $this->redirect(array($model->associationType . '/' . $model->associationId)); } }
public function convertToMedia(array $attributes = array()) { $username = Yii::app()->user->getName(); $name = $this->name; $tempFilename = 'uploads/protected/media/temp/' . $this->folder . '/' . $this->name; if (FileUtil::ccopy($tempFilename, "uploads/protected/media/{$username}/{$name}")) { $model = new Media(); $model->name = $model->fileName = $name; $model->uploadedBy = $username; $model->createDate = time(); $model->lastUpdated = time(); $model->resolveType(); $model->resolveSize(); $model->setAttributes($attributes, false); if ($model->save()) { return $model; } } return false; }