/** * Function that unassigns a media file from an object. Since it is not * possible to put a controller in an action, you have to wrap this * function in one of your own actions. * @param id the id of the parent model * @param mediafile the id of the media file */ public function unassignMediafile($id, $mediafile) { $class = $this->modelClass; $model = $class::findOne($id); if (null === $model) { throw new NotFoundHttpException(MediafileModule::t('mediafile', 'No such model.')); } $mediafile = Mediafile::findOne($mediafile); if (null !== $mediafile) { $model->removeMediafile($mediafile); } }
public function actionUpdate($id) { $model = Mediafile::findOne($id); if (!$model) { throw new NotFoundHttpException(Yii::t('mediafile', 'File not found.')); } if (Yii::$app->request->isPost) { $model->attributes = Yii::$app->request->post('Mediafile'); $model->file = UploadedFile::getInstance($model, 'file'); // First figure out the mime type. We need to do this before // validating the model. if ($model->file) { $mediafileType = Mediafiletype::findOne(['mimetype' => $model->file->type]); if ($mediafileType) { $model->mediafiletypeid = $mediafileType->id; } } // Save file contents to disk. if ($model->file && $model->validate()) { // Create the directory if it does not exist yet. $directory = preg_replace('/\\/[^\\/]+$/', '', $model->filePath); if (!file_exists($directory)) { $success = @mkdir($directory, 0755, true); if (!$success) { Yii::error("Unable to create directory {$directory}"); throw new HttpException(500, "Unable to create directory for file upload."); } } // Convert all images to PNG and save the data to disk. if (preg_match('/^image\\//', $model->file->type)) { $converter = new ImageToPngConverter(); $converter->setPath($model->file->tempName); $converter->setType($model->file->type); $converter->convert(); $fileHandle = @fopen($model->filePath, 'w'); if (!$fileHandle) { throw new Exception("Unable to save file data to " . $this->filePath); } if (false === fwrite($fileHandle, $converter->getPngData())) { throw new Exception("Unable to write file data to " . $this->filePath); } } else { if (!copy($model->file->tempName, $model->filePath)) { Yii::error("Unable to write to file " . $model->getFilePath); throw new HttpException(500, "Unable to copy uploaded file to destination."); } } @chmod($model->filePath, 0755); } } return $this->render('@icalab/mediafile/views/mediafile/update', ['model' => $model]); }