Rewrite File Module

This commit is contained in:
Lucas Bartholemy 2015-06-29 02:05:44 +02:00
parent 9954148812
commit dd5bac2db9
34 changed files with 462 additions and 493 deletions

View File

@ -22,7 +22,8 @@
"cebe/markdown": "1.0.2",
"yiisoft/yii2-jui": "^2.0",
"zendframework/zend-http": "*",
"nqxcode/zendsearch": "^2.0"
"nqxcode/zendsearch": "^2.0",
"xj/yii2-jplayer-widget": "*"
},
"suggest": {
"zendframework/zend-ldap": "LDAP authentication"

View File

@ -64,7 +64,8 @@ class CommentController extends \humhub\core\content\components\ContentAddonCont
$comment->object_id = $this->parentContent->getPrimaryKey();
$comment->save();
//File::attachPrecreated($comment, Yii::$app->request->getParam('fileList'));
\humhub\core\file\models\File::attachPrecreated($comment, Yii::$app->request->post('fileList'));
// Reload comment to get populated created_at field
$comment = Comment::findOne(['id' => $comment->id]);
@ -97,9 +98,9 @@ class CommentController extends \humhub\core\content\components\ContentAddonCont
}
return $this->renderAjax('edit', array(
'comment' => $this->contentAddon,
'contentModel' => $this->contentAddon->object_model,
'contentId' => $this->contentAddon->object_id
'comment' => $this->contentAddon,
'contentModel' => $this->contentAddon->object_model,
'contentId' => $this->contentAddon->object_id
));
}

View File

@ -8,7 +8,7 @@ class m141020_193920_rm_alsocreated extends Migration
public function up()
{
$this->delete('notification', 'class=:alsoComment', array(':alsoComment' => 'AlsoCommentedNotification'));
##### $this->delete('notification', 'class=:alsoComment', array(':alsoComment' => 'AlsoCommentedNotification'));
}
public function down()

View File

@ -24,15 +24,12 @@ use yii\helpers\Url;
?>
<?php
/*
// Creates Uploading Button
$this->widget('application.modules_core.file.widgets.FileUploadButtonWidget', array(
'uploaderId' => 'comment_upload_' . $comment->id,
'fileListFieldName' => 'fileList',
'object' => $comment
));
*
*/
// Creates Uploading Button
echo humhub\core\file\widgets\FileUploadButton::widget(array(
'uploaderId' => 'comment_upload_' . $comment->id,
'fileListFieldName' => 'fileList',
'object' => $comment
));
?>
@ -53,14 +50,11 @@ use yii\helpers\Url;
?>
<?php
/*
// Creates a list of already uploaded Files
$this->widget('application.modules_core.file.widgets.FileUploadListWidget', array(
'uploaderId' => 'comment_upload_' . $comment->id,
'object' => $comment
));
*
*/
// Creates a list of already uploaded Files
echo \humhub\core\file\widgets\FileUploadList::widget(array(
'uploaderId' => 'comment_upload_' . $comment->id,
'object' => $comment
));
?>
<?php CActiveForm::end(); ?>

View File

@ -18,14 +18,11 @@ use humhub\compat\widgets\AjaxButton;
<?php
/*
// Creates Uploading Button
$this->widget('application.modules_core.file.widgets.FileUploadButtonWidget', array(
'uploaderId' => 'comment_upload_' . $id,
'fileListFieldName' => 'fileList',
));
*
*/
// Creates Uploading Button
echo humhub\core\file\widgets\FileUploadButton::widget(array(
'uploaderId' => 'comment_upload_' . $id,
'fileListFieldName' => 'fileList',
));
?>
<?php
@ -57,13 +54,10 @@ use humhub\compat\widgets\AjaxButton;
<?php
/*
// Creates a list of already uploaded Files
$this->widget('application.modules_core.file.widgets.FileUploadListWidget', array(
'uploaderId' => 'comment_upload_' . $id,
));
*
*/
// Creates a list of already uploaded Files
echo \humhub\core\file\widgets\FileUploadList::widget(array(
'uploaderId' => 'comment_upload_' . $id,
));
?>
</div>

View File

@ -81,7 +81,7 @@ $canDelete = $comment->canDelete();
<div class="content" id="comment_editarea_<?php echo $comment->id; ?>">
<span id="comment-message-<?php echo $comment->id; ?>"><?php echo humhub\widgets\RichText::widget(['text' => $comment->message]); ?></span>
<?php //$this->widget('application.modules_core.file.widgets.ShowFilesWidget', array('object' => $comment)); ?>
<?php echo humhub\core\file\widgets\ShowFiles::widget(array('object' => $comment)); ?>
</div>

View File

@ -69,7 +69,7 @@ class Content extends \humhub\components\ActiveRecord
return [
[
'class' => \humhub\components\behaviors\UnderlyingObject::className(),
'mustBeInstanceOf' => array('HActiveRecordContent'),
'mustBeInstanceOf' => array(\humhub\core\content\components\activerecords\Content::className()),
],
[
'class' => \humhub\components\behaviors\GUID::className(),
@ -202,7 +202,7 @@ class Content extends \humhub\components\ActiveRecord
}
}
//File::attachPrecreated($this->getUnderlyingObject(), $this->attachFileGuidsAfterSave);
\humhub\core\file\models\File::attachPrecreated($this->getUnderlyingObject(), $this->attachFileGuidsAfterSave);
return parent::afterSave($insert, $changedAttributes);
}
@ -649,7 +649,7 @@ class Content extends \humhub\components\ActiveRecord
}
// Store List of attached Files to add them after Save
//$this->attachFileGuidsAfterSave = Yii::$app->request->post('fileList');
$this->attachFileGuidsAfterSave = Yii::$app->request->post('fileList');
}
public function beforeValidate()

View File

@ -16,12 +16,9 @@ use yii\helpers\Url;
<?php
/* Modify textarea for mention input */
/*
$this->widget('application.widgets.HEditorWidget', array(
'id' => 'contentForm_message',
));
*
*/
echo \humhub\widgets\RichTextEditor::widget(array(
'id' => 'contentForm_message',
));
?>
<div id="notifyUserContainer" class="form-group hidden" style="margin-top: 15px;">
@ -84,13 +81,10 @@ use yii\helpers\Url;
?>
<?php
// Creates Uploading Button
/*
$this->widget('application.modules_core.file.widgets.FileUploadButtonWidget', array(
'uploaderId' => 'contentFormFiles',
'fileListFieldName' => 'fileList',
));
*
*/
echo humhub\core\file\widgets\FileUploadButton::widget(array(
'uploaderId' => 'contentFormFiles',
'fileListFieldName' => 'fileList',
));
?>
<script>
$('#fileUploaderButton_contentFormFiles').bind('fileuploaddone', function (e, data) {
@ -143,12 +137,9 @@ use yii\helpers\Url;
<?php
// Creates a list of already uploaded Files
/*
$this->widget('application.modules_core.file.widgets.FileUploadListWidget', array(
'uploaderId' => 'contentFormFiles'
));
*
*/
echo \humhub\core\file\widgets\FileUploadList::widget(array(
'uploaderId' => 'contentFormFiles'
));
?>
</div>
@ -211,7 +202,7 @@ use yii\helpers\Url;
$('#contentForm_message_contenteditable').addClass('atwho-placeholder');
// Notify FileUploadButtonWidget to clear (by providing uploaderId)
//resetUploader('contentFormFiles');
resetUploader('contentFormFiles');
if (response.errors) {
$('#contentFormError').show();

View File

@ -18,13 +18,15 @@
* GNU Affero General Public License for more details.
*/
namespace humhub\core\file;
/**
* FileModuleEvents handles all events described in autostart.php
*
* @package humhub.modules_core.file
* @author luke
*/
class FileModuleEvents
class Events extends \yii\base\Object
{
/**
@ -34,7 +36,7 @@ class FileModuleEvents
*/
public static function onWallEntryAddonInit($event)
{
$event->sender->addWidget('application.modules_core.file.widgets.ShowFilesWidget', array('object'=>$event->sender->object), array('sortOrder' => 5));
$event->sender->addWidget(widgets\ShowFiles::className(), array('object' => $event->sender->object), array('sortOrder' => 5));
}
/**
@ -46,16 +48,15 @@ class FileModuleEvents
*/
public static function onCronDailyRun($event)
{
/*
$cron = $event->sender;
$cron = $event->sender;
/**
* Delete unused files
// Delete unused files
$deleteTime = time() - (60 * 60 * 24 * 1); // Older than 1 day
foreach (File::model()->findAllByAttributes(array(), 'created_at < :date AND (object_model IS NULL or object_model = "")', array(':date' => date('Y-m-d', $deleteTime))) as $file) {
$file->delete();
}
*/
$deleteTime = time() - (60 * 60 * 24 * 1); // Older than 1 day
foreach (File::model()->findAllByAttributes(array(), 'created_at < :date AND (object_model IS NULL or object_model = "")', array(':date' => date('Y-m-d', $deleteTime))) as $file) {
$file->delete();
}
}
/**
@ -65,18 +66,20 @@ class FileModuleEvents
*/
public static function onIntegrityCheck($event)
{
/*
$integrityChecker = $event->sender;
$integrityChecker->showTestHeadline("Validating File Module (" . File::model()->count() . " entries)");
$integrityChecker = $event->sender;
$integrityChecker->showTestHeadline("Validating File Module (" . File::model()->count() . " entries)");
foreach (File::model()->findAll() as $a) {
foreach (File::model()->findAll() as $a) {
if ($a->object_model != "" && $a->object_id != "" && $a->getUnderlyingObject() === null) {
$integrityChecker->showFix("Deleting file id " . $a->id . " without existing target!");
if (!$integrityChecker->simulate)
$a->delete();
}
}
if ($a->object_model != "" && $a->object_id != "" && $a->getUnderlyingObject() === null) {
$integrityChecker->showFix("Deleting file id " . $a->id . " without existing target!");
if (!$integrityChecker->simulate)
$a->delete();
}
}
*
*/
}
/**
@ -84,9 +87,9 @@ class FileModuleEvents
*
* @param CEvent $event
*/
public static function onBeforeHActiveRecordDelete($event)
public static function onBeforeActiveRecordDelete($event)
{
foreach (File::model()->findAllByAttributes(array('object_id' => $event->sender->getPrimaryKey(), 'object_model' => get_class($event->sender))) as $file) {
foreach (models\File::find()->where(['object_id' => $event->sender->getPrimaryKey(), 'object_model' => $event->sender->className()])->all() as $file) {
$file->delete();
}
}

View File

@ -1,24 +0,0 @@
<?php
/**
* File Module
*
* @package humhub.modules_core.file
* @since 0.5
*/
class FileModule extends HWebModule
{
public $isCoreModule = true;
/**
* Inits the Module
*/
public function init()
{
$this->setImport(array(
));
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace humhub\core\file;
/**
* File Module
*
* @package humhub.modules_core.file
* @since 0.5
*/
class Module extends \yii\base\Module
{
public $isCoreModule = true;
}

View File

@ -1,23 +1,20 @@
<?php
# Disable until migrated
return;
use humhub\core\content\widgets\WallEntryAddons;
use humhub\commands\CronController;
use humhub\commands\IntegrityController;
use yii\db\ActiveRecord;
use humhub\core\file\Events;
Yii::app()->moduleManager->register(array(
Yii::$app->moduleManager->register(array(
'id' => 'file',
'class' => 'application.modules_core.file.FileModule',
'class' => \humhub\core\file\Module::className(),
'isCoreModule' => true,
'import' => array(
'application.modules_core.file.*',
'application.modules_core.file.models.*',
'application.modules_core.file.libs.*',
),
// Events to Catch
'events' => array(
array('class' => 'WallEntryAddonWidget', 'event' => 'onInit', 'callback' => array('FileModuleEvents', 'onWallEntryAddonInit')),
array('class' => 'ZCronRunner', 'event' => 'onDailyRun', 'callback' => array('FileModuleEvents', 'onCronDailyRun')),
array('class' => 'IntegrityChecker', 'event' => 'onRun', 'callback' => array('FileModuleEvents', 'onIntegrityCheck')),
array('class' => 'HActiveRecord', 'event' => 'onBeforeDelete', 'callback' => array('FileModuleEvents', 'onBeforeHActiveRecordDelete')),
array('class' => WallEntryAddons::className(), 'event' => WallEntryAddons::EVENT_INIT, 'callback' => array(Events::className(), 'onWallEntryAddonInit')),
array('class' => CronController::className(), 'event' => CronController::EVENT_ON_DAILY_RUN, 'callback' => array(Events::className(), 'onCronDailyRun')),
array('class' => IntegrityController::className(), 'event' => IntegrityController::EVENT_ON_RUN, 'callback' => array(Events::className(), 'onIntegrityCheck')),
array('class' => ActiveRecord::className(), 'event' => \humhub\components\ActiveRecord::EVENT_BEFORE_DELETE, 'callback' => array(Events::className(), 'onBeforeActiveRecordDelete')),
),
));
?>

View File

@ -1,46 +1,22 @@
<?php
namespace humhub\core\file\controllers;
use Yii;
use yii\web\HttpException;
use humhub\models\Setting;
use yii\web\UploadedFile;
use humhub\core\file\models\File;
/**
* UploadController provides uploading functions for files
*
* @package humhub.modules_core.file.controllers
* @since 0.5
*/
class FileController extends Controller
class FileController extends \humhub\components\Controller
{
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow',
'users' => array((HSetting::Get('allowGuestAccess', 'authentication_internal')) ? "?" : "@"),
'actions' => array('download'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'users' => array('@'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
/**
* Action which handles file uploads
*
@ -48,24 +24,26 @@ class FileController extends Controller
*/
public function actionUpload()
{
Yii::$app->response->format = 'json';
// Object which the uploaded file(s) belongs to (optional)
$object = null;
$objectModel = Yii::app()->request->getParam('objectModel');
$objectId = Yii::app()->request->getParam('objectId');
if ($objectModel != "" && $objectId != "") {
$givenObject = $objectModel::model()->findByPk($objectId);
$objectModel = Yii::$app->request->get('objectModel');
$objectId = Yii::$app->request->get('objectId');
if ($objectModel != "" && $objectId != "" && \humhub\libs\Helpers::CheckClassType($objectModel, \yii\db\ActiveRecord::className())) {
$givenObject = $objectModel::findOne(['id' => $objectId]);
// Check if given object is HActiveRecordContent or HActiveRecordContentAddon and can be written by the current user
if ($givenObject !== null && ($givenObject instanceof HActiveRecordContent || $givenObject instanceof HActiveRecordContentAddon) && $givenObject->content->canWrite()) {
if ($givenObject !== null && ($givenObject instanceof \humhub\core\content\components\activerecords\Content || $givenObject instanceof \humhub\core\content\components\activerecords\ContentAddon) && $givenObject->content->canWrite()) {
$object = $givenObject;
}
}
$files = array();
foreach (CUploadedFile::getInstancesByName('files') as $cFile) {
foreach (UploadedFile::getInstancesByName('files') as $cFile) {
$files[] = $this->handleFileUpload($cFile, $object);
}
return $this->renderJson(array('files' => $files));
return ['files' => $files];
}
/**
@ -100,7 +78,7 @@ class FileController extends Controller
if ($object != null) {
$file->object_id = $object->getPrimaryKey();
$file->object_model = get_class($object);
$file->object_model = $object->className();
}
if ($file->validate() && $file->save()) {
@ -109,7 +87,7 @@ class FileController extends Controller
$output['name'] = $file->file_name;
$output['title'] = $file->title;
$output['size'] = $file->size;
$output['mimeIcon'] = HHtml::getMimeIconClassByExtension($file->getExtension());
$output['mimeIcon'] = \humhub\libs\MimeHelper::getMimeIconClassByExtension($file->getExtension());
$output['mimeBaseType'] = $file->getMimeBaseType();
$output['mimeSubType'] = $file->getMimeSubType();
$output['url'] = $file->getUrl("", false);
@ -133,28 +111,28 @@ class FileController extends Controller
*/
public function actionDownload()
{
$guid = Yii::app()->request->getParam('guid');
$suffix = Yii::app()->request->getParam('suffix');
$guid = Yii::$app->request->get('guid');
$suffix = Yii::$app->request->get('suffix');
$file = File::model()->findByAttributes(array('guid' => $guid));
$file = File::findOne(['guid' => $guid]);
if ($file == null) {
throw new CHttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
throw new HttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
}
if (!$file->canRead()) {
throw new CHttpException(401, Yii::t('FileModule.controllers_FileController', 'Insufficient permissions!'));
throw new HttpException(401, Yii::t('FileModule.controllers_FileController', 'Insufficient permissions!'));
}
$filePath = $file->getPath($suffix);
$filePath = $file->getPath();
$fileName = $file->getFilename($suffix);
if (!file_exists($filePath . DIRECTORY_SEPARATOR . $fileName)) {
throw new CHttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
throw new HttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
}
if (!HSetting::Get('useXSendfile', 'file')) {
Yii::app()->getRequest()->sendFile($fileName, file_get_contents($filePath . DIRECTORY_SEPARATOR . $fileName), $file->mime_type);
if (!Setting::Get('useXSendfile', 'file')) {
Yii::$app->response->sendFile($filePath . DIRECTORY_SEPARATOR . $fileName);
} else {
$options = array(
'saveName' => $fileName,
@ -168,7 +146,7 @@ class FileController extends Controller
$filePath = substr($filePath, strlen($docroot));
}
}
Yii::app()->getRequest()->xSendFile($filePath . DIRECTORY_SEPARATOR . $fileName, $options);
Yii::$app->response->xSendFile($filePath . DIRECTORY_SEPARATOR . $fileName, $options);
}
}
@ -176,15 +154,15 @@ class FileController extends Controller
{
$this->forcePostRequest();
$guid = Yii::app()->request->getParam('guid');
$file = File::model()->findByAttributes(array('guid' => $guid));
$guid = Yii::$app->request->post('guid');
$file = File::findOne(['guid' => $guid]);
if ($file == null) {
throw new CHttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
throw new HttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
}
if (!$file->canDelete()) {
throw new CHttpException(401, Yii::t('FileModule.controllers_FileController', 'Insufficient permissions!'));
throw new HttpException(401, Yii::t('FileModule.controllers_FileController', 'Insufficient permissions!'));
}
$file->delete();

View File

@ -18,6 +18,10 @@
* GNU Affero General Public License for more details.
*/
namespace humhub\core\file\libs;
use humhub\models\Setting;
/**
* ImageConverter provides a simple interface for converting or resizing images.
*
@ -37,8 +41,8 @@ class ImageConverter
public static function TransformToJpeg($sourceFile, $targetFile)
{
if (HSetting::Get('imageMagickPath', 'file')) {
$convertCommand = HSetting::Get('imageMagickPath', 'file');
if (Setting::Get('imageMagickPath', 'file')) {
$convertCommand = Setting::Get('imageMagickPath', 'file');
$command = $convertCommand . " \"{$sourceFile}\" \"{$targetFile}\"";
$ret = passthru($command);
} else {
@ -77,7 +81,7 @@ class ImageConverter
if (!isset($options['mode']))
$options['mode'] = 'force';
if (HSetting::Get('imageMagickPath', 'file')) {
if (Setting::Get('imageMagickPath', 'file')) {
self::ResizeImageMagick($sourceFile, $targetFile, $options);
} else {
self::ResizeGD($sourceFile, $targetFile, $options);
@ -248,7 +252,7 @@ class ImageConverter
*/
private static function ResizeImageMagick($sourceFile, $targetFile, $options = array())
{
$convertCommand = HSetting::Get('imageMagickPath', 'file');
$convertCommand = Setting::Get('imageMagickPath', 'file');
$width = (int) $options['width'];
$height = (int) $options['height'];

View File

@ -18,6 +18,8 @@
* GNU Affero General Public License for more details.
*/
namespace humhub\core\file\libs;
/**
* Experimental downloader of files (images)
*

View File

@ -1,8 +1,13 @@
<?php
class m131023_170159_initial extends ZDbMigration {
use yii\db\Schema;
use yii\db\Migration;
public function up() {
class m131023_170159_initial extends Migration
{
public function up()
{
$this->createTable('file', array(
'id' => 'pk',
'guid' => 'varchar(45) DEFAULT NULL',
@ -19,7 +24,8 @@ class m131023_170159_initial extends ZDbMigration {
), '');
}
public function down() {
public function down()
{
echo "m131023_170159_initial does not support migration down.\n";
return false;
}
@ -34,4 +40,4 @@ class m131023_170159_initial extends ZDbMigration {
{
}
*/
}
}

View File

@ -1,6 +1,9 @@
<?php
class m140901_080432_indices extends EDbMigration
use yii\db\Schema;
use yii\db\Migration;
class m140901_080432_indices extends Migration
{
public function up()

View File

@ -1,6 +1,9 @@
<?php
class m140930_210142_fix_default extends EDbMigration
use yii\db\Schema;
use yii\db\Migration;
class m140930_210142_fix_default extends Migration
{
public function up()

View File

@ -1,20 +1,24 @@
<?php
class m150322_195619_allowedExt2Text extends EDbMigration
use yii\db\Schema;
use yii\db\Migration;
use humhub\models\Setting;
class m150322_195619_allowedExt2Text extends Migration
{
public function up()
{
$allowedExtensions = HSetting::Get('allowedExtensions', 'file');
$allowedExtensions = Setting::Get('allowedExtensions', 'file');
if ($allowedExtensions != "") {
HSetting::Set('allowedExtensions', '', 'file');
HSetting::SetText('allowedExtensions', $allowedExtensions, 'file');
Setting::Set('allowedExtensions', '', 'file');
Setting::SetText('allowedExtensions', $allowedExtensions, 'file');
}
$showFilesWidgetBlacklist = HSetting::Get('showFilesWidgetBlacklist', 'file');
$showFilesWidgetBlacklist = Setting::Get('showFilesWidgetBlacklist', 'file');
if ($showFilesWidgetBlacklist != "") {
HSetting::Set('showFilesWidgetBlacklist', '', 'file');
HSetting::SetText('showFilesWidgetBlacklist', $showFilesWidgetBlacklist, 'file');
Setting::Set('showFilesWidgetBlacklist', '', 'file');
Setting::SetText('showFilesWidgetBlacklist', $showFilesWidgetBlacklist, 'file');
}
}

View File

@ -1,5 +1,14 @@
<?php
namespace humhub\core\file\models;
use Yii;
use yii\web\UploadedFile;
use humhub\models\Setting;
use yii\helpers\Url;
use humhub\core\file\libs\ImageConverter;
use yii\base\Exception;
/**
* This is the model class for table "file".
*
@ -20,7 +29,7 @@
* @package humhub.modules_core.file.models
* @since 0.5
*/
class File extends HActiveRecord
class File extends \humhub\components\ActiveRecord
{
// Configuration
@ -29,9 +38,9 @@ class File extends HActiveRecord
/**
* Uploaded File or File Content
*
* @var type
* @var UploadedFile
*/
private $cUploadedFile = null;
private $uploadedFile = null;
/**
* New content of the file
@ -40,16 +49,6 @@ class File extends HActiveRecord
*/
public $newFileContent = null;
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return File the static model class
*/
public static function model($className = __CLASS__)
{
return parent::model($className);
}
/**
* Returns all files belongs to a given HActiveRecord Object.
* @todo Add chaching
@ -57,15 +56,15 @@ class File extends HActiveRecord
* @param HActiveRecord $object
* @return Array of File instances
*/
public static function getFilesOfObject(HActiveRecord $object)
public static function getFilesOfObject(\yii\db\ActiveRecord $object)
{
return File::model()->findAllByAttributes(array('object_id' => $object->getPrimaryKey(), 'object_model' => get_class($object)));
return self::findAll(array('object_id' => $object->getPrimaryKey(), 'object_model' => $object->className()));
}
/**
* @return string the associated database table name
*/
public function tableName()
public static function tableName()
{
return 'file';
}
@ -76,36 +75,31 @@ class File extends HActiveRecord
public function rules()
{
return array(
array('created_by, updated_by', 'numerical', 'integerOnly' => true),
array('guid, size', 'length', 'max' => 45),
array('mime_type', 'length', 'max' => 150),
array(['created_by', 'updated_by', 'size'], 'integer'),
array(['guid'], 'string', 'max' => 45),
array(['mime_type'], 'string', 'max' => 150),
array('filename', 'validateExtension'),
array('filename', 'validateSize'),
array('mime_type', 'match', 'not' => true, 'pattern' => '/[^a-zA-Z0-9\.ä\/\-]/', 'message' => Yii::t('FileModule.models_File', 'Invalid Mime-Type')),
array('file_name, title', 'length', 'max' => 255),
array('created_at, updated_at', 'safe'),
array(['file_name', 'title'], 'string', 'max' => 255),
array(['created_at', 'updated_at'], 'safe'),
);
}
/**
* Add mix-ins to this model
*
* @return type
*/
public function behaviors()
{
return array(
'HUnderlyingObjectBehavior' => array(
'class' => 'application.behaviors.HUnderlyingObjectBehavior',
'mustBeInstanceOf' => array('HActiveRecord'),
),
'HGuidBehavior' => array(
'class' => 'application.behaviors.HGuidBehavior',
),
);
return [
[
'class' => \humhub\components\behaviors\UnderlyingObject::className(),
'mustBeInstanceOf' => array(\yii\db\ActiveRecord::className()),
],
[
'class' => \humhub\components\behaviors\GUID::className(),
],
];
}
protected function beforeSave()
public function beforeSave($insert)
{
$this->sanitizeFilename();
@ -113,10 +107,10 @@ class File extends HActiveRecord
$this->title = $this->file_name;
}
return parent::beforeSave();
return parent::beforeSave($insert);
}
protected function beforeDelete()
public function beforeDelete()
{
$path = $this->getPath();
@ -134,25 +128,24 @@ class File extends HActiveRecord
return parent::beforeDelete();
}
protected function afterSave()
public function afterSave($insert, $changedAttributes)
{
// Set new uploaded file
if ($this->cUploadedFile !== null && $this->cUploadedFile instanceof CUploadedFile) {
if ($this->uploadedFile !== null && $this->uploadedFile instanceof UploadedFile) {
$newFilename = $this->getPath() . DIRECTORY_SEPARATOR . $this->getFilename();
if (is_uploaded_file($this->cUploadedFile->getTempName())) {
move_uploaded_file($this->cUploadedFile->getTempName(), $newFilename);
if (is_uploaded_file($this->uploadedFile->tempName)) {
move_uploaded_file($this->uploadedFile->tempName, $newFilename);
@chmod($newFilename, 0744);
}
/**
* For uploaded jpeg files convert them again - to handle special
* exif attributes (e.g. orientation)
*/
if ($this->cUploadedFile->getType() == 'image/jpeg') {
if ($this->uploadedFile->type == 'image/jpeg') {
ImageConverter::TransformToJpeg($newFilename, $newFilename);
}
}
// Set file by given contents
@ -162,7 +155,7 @@ class File extends HActiveRecord
@chmod($newFilename, 0744);
}
return parent::afterSave();
return parent::afterSave($insert, $changedAttributes);
}
/**
@ -189,7 +182,7 @@ class File extends HActiveRecord
*/
public function getPath()
{
$path = Yii::getPathOfAlias('webroot') .
$path = Yii::getAlias('@webroot') .
DIRECTORY_SEPARATOR . "uploads" .
DIRECTORY_SEPARATOR . $this->folder_uploads .
DIRECTORY_SEPARATOR . $this->guid;
@ -216,11 +209,9 @@ class File extends HActiveRecord
$params['suffix'] = $suffix;
}
if (!$absolute) {
return Yii::app()->getController()->createUrl('//file/file/download', $params);
}
array_unshift($params, '/file/file/download');
return Yii::app()->getController()->createAbsoluteUrl('//file/file/download', $params);
return Url::to($params, $absolute);
}
/**
@ -312,7 +303,7 @@ class File extends HActiveRecord
public function canRead($userId = "")
{
$object = $this->getUnderlyingObject();
if ($object !== null && ($object instanceof HActiveRecordContent || $object instanceof HActiveRecordContentAddon)) {
if ($object !== null && ($object instanceof \humhub\core\content\components\activerecords\Content || $object instanceof \humhub\core\content\components\activerecords\ContentAddon)) {
return $object->content->canRead($userId);
}
@ -328,7 +319,7 @@ class File extends HActiveRecord
public function canDelete($userId = "")
{
$object = $this->getUnderlyingObject();
if ($object !== null && ($object instanceof HActiveRecordContent || $object instanceof HActiveRecordContentAddon)) {
if ($object !== null && ($object instanceof \humhub\core\content\components\activerecords\Content || $object instanceof \humhub\core\content\components\activerecords\ContentAddon)) {
return $object->content->canWrite($userId);
}
@ -340,12 +331,12 @@ class File extends HActiveRecord
return false;
}
public function setUploadedFile(CUploadedFile $cUploadedFile)
public function setUploadedFile(UploadedFile $uploadedFile)
{
$this->file_name = $cUploadedFile->getName();
$this->mime_type = $cUploadedFile->getType();
$this->size = $cUploadedFile->getSize();
$this->cUploadedFile = $cUploadedFile;
$this->file_name = $uploadedFile->name;
$this->mime_type = $uploadedFile->type;
$this->size = $uploadedFile->size;
$this->uploadedFile = $uploadedFile;
}
public function sanitizeFilename()
@ -371,13 +362,13 @@ class File extends HActiveRecord
public function validateExtension($attribute, $params)
{
$allowedExtensions = HSetting::GetText('allowedExtensions', 'file');
$allowedExtensions = Setting::GetText('allowedExtensions', 'file');
if ($allowedExtensions != "") {
$extension = $this->getExtension();
$extension = trim(strtolower($extension));
$allowed = array_map('trim', explode(",", HSetting::GetText('allowedExtensions', 'file')));
$allowed = array_map('trim', explode(",", Setting::GetText('allowedExtensions', 'file')));
if (!in_array($extension, $allowed)) {
$this->addError($attribute, Yii::t('FileModule.models_File', 'This file type is not allowed!'));
@ -387,8 +378,8 @@ class File extends HActiveRecord
public function validateSize($attribute, $params)
{
if ($this->size > HSetting::Get('maxFileSize', 'file')) {
$this->addError($attribute, Yii::t('FileModule.models_File', 'Maximum file size ({maxFileSize}) has been exceeded!', array("{maxFileSize}" => Yii::app()->format->formatSize(HSetting::Get('maxFileSize', 'file')))));
if ($this->size > Setting::Get('maxFileSize', 'file')) {
$this->addError($attribute, Yii::t('FileModule.models_File', 'Maximum file size ({maxFileSize}) has been exceeded!', array("{maxFileSize}" => Yii::$app->formatter->asSize(Setting::Get('maxFileSize', 'file')))));
}
}
@ -401,17 +392,19 @@ class File extends HActiveRecord
*/
public static function attachPrecreated($object, $files)
{
if (!$object instanceof HActiveRecord) {
throw new CException("Invalid object given - require instance of HActiveRecord!");
if (!$object instanceof \yii\db\ActiveRecord) {
throw new Exception("Invalid object given - require instance of HActiveRecord!");
}
// Attach Files
foreach (explode(",", $files) as $fileGuid) {
$file = File::model()->findByAttributes(array('guid' => trim($fileGuid)));
$file = self::findOne(['guid' => trim($fileGuid)]);
if ($file != null && $file->object_model == "") {
$file->object_model = get_class($object);
$file->object_model = $object->className();
$file->object_id = $object->getPrimaryKey();
$file->save();
if (!$file->save()) {
throw new Exception("Could not save precreated file!");
}
}
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace humhub\core\file\widgets;
/**
* FileUploadButtonWidget creates an upload button / system.
*
* The button uploads files and stores the uploaded file guids to a given hidden field id.
* The underlying module can use the guids to adobt these files.
*
* The related widget FileUploadListWidget can optionally used to display states
* of the current upload progress.
*
* @package humhub.modules_core.file.widgets
* @since 0.5
*/
class FileUploadButton extends \yii\base\Widget
{
/**
* @var String unique id of this uploader
*/
public $uploaderId = "";
/**
* Hidden field which stores uploaded file guids
*
* @var string
*/
public $fileListFieldName = '';
/**
* The HActiveRecord which the uploaded files belongs to.
* Leave empty when object not exists yet.
*
* @var HActiveRecord
*/
public $object = null;
/**
* Draws the Upload Button output.
*/
public function run()
{
$objectModel = "";
$objectId = "";
if ($this->object !== null) {
$objectModel = $this->object->className();
$objectId = $this->object->getPrimaryKey();
}
return $this->render('fileUploadButton', array(
'fileListFieldName' => $this->fileListFieldName,
'uploaderId' => $this->uploaderId,
'objectModel' => $objectModel,
'objectId' => $objectId
));
}
}
?>

View File

@ -1,72 +0,0 @@
<?php
/**
* FileUploadButtonWidget creates an upload button / system.
*
* The button uploads files and stores the uploaded file guids to a given hidden field id.
* The underlying module can use the guids to adobt these files.
*
* The related widget FileUploadListWidget can optionally used to display states
* of the current upload progress.
*
* @package humhub.modules_core.file.widgets
* @since 0.5
*/
class FileUploadButtonWidget extends HWidget
{
/**
* @var String unique id of this uploader
*/
public $uploaderId = "";
/**
* Hidden field which stores uploaded file guids
*
* @var string
*/
public $fileListFieldName = '';
/**
* The HActiveRecord which the uploaded files belongs to.
* Leave empty when object not exists yet.
*
* @var HActiveRecord
*/
public $object = null;
/**
* Ensure that imported javascript resources are included in the output
*/
public function init()
{
$assetPrefix = Yii::app()->assetManager->publish(dirname(__FILE__) . '/../resources', true, 0, defined('YII_DEBUG'));
Yii::app()->clientScript->registerScriptFile($assetPrefix . '/fileuploader.js');
Yii::app()->clientScript->setJavascriptVariable('fileuploader_error_modal_title', Yii::t('FileModule.widgets_FileUploadButtonWidget', '<strong>Upload</strong> error'));
Yii::app()->clientScript->setJavascriptVariable('fileuploader_error_modal_btn_close', Yii::t('FileModule.widgets_FileUploadButtonWidget', 'Close'));
Yii::app()->clientScript->setJavascriptVariable('fileuploader_error_modal_errormsg', Yii::t('FileModule.widgets_FileUploadButtonWidget', 'Could not upload File:'));
}
/**
* Draws the Upload Button output.
*/
public function run()
{
$objectModel = "";
$objectId = "";
if ($this->object !== null) {
$objectModel = get_class($this->object);
$objectId = $this->object->getPrimaryKey();
}
$this->render('fileUploadButton', array(
'fileListFieldName' => $this->fileListFieldName,
'uploaderId' => $this->uploaderId,
'objectModel' => $objectModel,
'objectId' => $objectId
));
}
}
?>

View File

@ -1,5 +1,7 @@
<?php
namespace humhub\core\file\widgets;
/**
* FileUploadListWidget works in combination of FileUploadButtonWidget and is
* primary responsible to display some status informations like upload progress
@ -11,7 +13,7 @@
* @package humhub.modules_core.file.widgets
* @since 0.5
*/
class FileUploadListWidget extends HWidget
class FileUploadList extends \yii\base\Widget
{
/**
@ -34,14 +36,12 @@ class FileUploadListWidget extends HWidget
$files = array();
if ($this->object !== null) {
$files = File::getFilesOfObject($this->object);
$files = \humhub\core\file\models\File::getFilesOfObject($this->object);
}
Yii::app()->clientScript->setJavaScriptVariable('file_delete_url', $this->createUrl('//file/file/delete'));
$this->render('fileUploadList', array(
'uploaderId' => $this->uploaderId,
'files' => $files
return $this->render('fileUploadList', array(
'uploaderId' => $this->uploaderId,
'files' => $files
));
}

View File

@ -0,0 +1,39 @@
<?php
namespace humhub\core\file\widgets;
use humhub\models\Setting;
/**
* This widget is used include the files functionality to a wall entry.
*
* @package humhub.modules_core.file
* @since 0.5
*/
class ShowFiles extends \yii\base\Widget
{
/**
* Object to show files from
*/
public $object = null;
/**
* Executes the widget.
*/
public function run()
{
$blacklisted_objects = explode(',', Setting::GetText('showFilesWidgetBlacklist', 'file'));
if (!in_array(get_class($this->object), $blacklisted_objects)) {
$files = \humhub\core\file\models\File::getFilesOfObject($this->object);
return $this->render('showFiles', array('files' => $files,
'maxPreviewImageWidth' => Setting::Get('maxPreviewImageWidth', 'file'),
'maxPreviewImageHeight' => Setting::Get('maxPreviewImageHeight', 'file'),
'hideImageFileInfo' => Setting::Get('hideImageFileInfo', 'file')
));
}
}
}
?>

View File

@ -1,35 +0,0 @@
<?php
/**
* This widget is used include the files functionality to a wall entry.
*
* @package humhub.modules_core.file
* @since 0.5
*/
class ShowFilesWidget extends HWidget
{
/**
* Object to show files from
*/
public $object = null;
/**
* Executes the widget.
*/
public function run()
{
$blacklisted_objects = explode(',', HSetting::GetText('showFilesWidgetBlacklist','file'));
if (!in_array(get_class($this->object), $blacklisted_objects)) {
$files = File::getFilesOfObject($this->object);
$this->render('showFiles', array('files' => $files,
'maxPreviewImageWidth' => HSetting::Get('maxPreviewImageWidth', 'file'),
'maxPreviewImageHeight' => HSetting::Get('maxPreviewImageHeight', 'file'),
'hideImageFileInfo' => HSetting::Get('hideImageFileInfo', 'file')
));
}
}
}
?>

View File

@ -1,23 +1,15 @@
<?php
/**
* Shows the upload file button which handles file uploads.
* This view is used by FileUploadButtonWidget.
*
* If an FileUploadListWidget Instance is exists, this view should update some
* informations like process or already uploaded files per javascript.
*
* Its also necessary to update the bindToFormFieldId on successful uploads.
* This hidden field contains a list all uploaded file guids.
*
* @property String $uploaderId is the unique id of the uploader.
* @property String $bindToFormFieldId is the id of the hidden id which stores a comma seprated list of file guids.
*
* @package humhub.modules_core.file.widgets
* @since 0.5
*/
use yii\helpers\Html;
use yii\helpers\Url;
$this->registerJsFile("@web/resources/file/fileuploader.js");
$this->registerJsVar('fileuploader_error_modal_title', Yii::t('FileModule.widgets_FileUploadButtonWidget', '<strong>Upload</strong> error'));
$this->registerJsVar('fileuploader_error_modal_btn_close', Yii::t('FileModule.widgets_FileUploadButtonWidget', 'Close'));
$this->registerJsVar('fileuploader_error_modal_errormsg', Yii::t('FileModule.widgets_FileUploadButtonWidget', 'Could not upload File:'));
?>
<?php echo CHtml::hiddenField($this->fileListFieldName, '', array('id' => "fileUploaderHiddenField_" . $uploaderId)); ?>
<?php echo Html::hiddenInput($this->context->fileListFieldName, '', array('id' => "fileUploaderHiddenField_" . $uploaderId)); ?>
<style>
.fileinput-button {
@ -43,16 +35,16 @@
<i class="fa fa-cloud-upload"></i>
<input id="fileUploaderButton_<?php echo $uploaderId; ?>" type="file" name="files[]"
data-url="<?php echo Yii::app()->createUrl('//file/file/upload', array('objectModel' => $objectModel, 'objectId' => $objectId)); ?>" multiple>
data-url="<?php echo Url::to(['/file/file/upload', 'objectModel' => $objectModel, 'objectId' => $objectId]); ?>" multiple>
</span>
<script>
$(function() {
$(function () {
'use strict';
installUploader("<?php echo $uploaderId; ?>");
// fixing staying tooltip while opening file browser window
$('.fileinput-button').click(function() {
$('.fileinput-button').click(function () {
$('.tt').tooltip('hide');
})
})

View File

@ -1,16 +1,10 @@
<?php
/**
* Displays a list of uploaded files by FileUploadButtonWidget.
*
* The data will be updated via javascript by FileUploadButtonWidget.
* This view is used by FileUploadListWidget.
*
* @property String $uploaderId is the unique id of the uploader.
* @property String $bindToFormFieldId is the id of the hidden id which stores a comma seprated list of file guids.
*
* @package humhub.modules_core.file.widgets
* @since 0.5
*/
use yii\helpers\Html;
use yii\helpers\Url;
use humhub\libs\MimeHelper;
$this->registerJsVar('file_delete_url', Url::to(['/file/file/delete']));
?>
<div class="progress" id="fileUploaderProgressbar_<?php echo $uploaderId; ?>" style="display:none">
<div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="0" aria-valuemin="0"
@ -25,6 +19,6 @@
<script>
<?php foreach ($files as $file): ?>
addToUploadList("<?php echo $uploaderId; ?>", "<?php echo $file->guid; ?>", "<?php echo $file->file_name; ?>", "<?php echo HHtml::getMimeIconClassByExtension($file->getExtension()); ?>");
addToUploadList("<?php echo $uploaderId; ?>", "<?php echo $file->guid; ?>", "<?php echo $file->file_name; ?>", "<?php echo MimeHelper::getMimeIconClassByExtension($file->getExtension()); ?>");
<?php endforeach; ?>
</script>

View File

@ -1,24 +1,24 @@
<?php
/**
* This view shows all attached files of a wall content object.
*
* @property Array $files a list of file objects
*
* @package humhub.modules_core.file.widgets
* @since 0.5
*/
use humhub\libs\Helpers;
$object = $this->context->object;
?>
<?php if (count($files) != 0) : ?>
<!-- Show Images as Thumbnails -->
<div class="post-files" id="post-files-<?php echo $this->object->getUniqueId(); ?>">
<div class="post-files" id="post-files-<?php echo $object->getUniqueId(); ?>">
<?php foreach ($files as $file) : ?>
<?php if ($file->getMimeBaseType() == "image") : ?>
<?php
//Note: We need to add "#.jpeg" to the full url for image detection of ekko lightbox.
?>
<a data-toggle="lightbox" data-gallery="<?php if (count($files) > 1) { echo "gallery-". $this->object->getUniqueId(); } ?>" href="<?php echo $file->getUrl(); ?>#.jpeg" data-footer='<button type="button" class="btn btn-primary" data-dismiss="modal"><?php echo Yii::t('FileModule.widgets_views_showFiles', 'Close'); ?></button>'>
<a data-toggle="lightbox" data-gallery="<?php
if (count($files) > 1) {
echo "gallery-" . $object->getUniqueId();
}
?>" href="<?php echo $file->getUrl(); ?>#.jpeg" data-footer='<button type="button" class="btn btn-primary" data-dismiss="modal"><?php echo Yii::t('FileModule.widgets_views_showFiles', 'Close'); ?></button>'>
<img src='<?php echo $file->getPreviewImageUrl($maxPreviewImageWidth ? $maxPreviewImageWidth : 200, $maxPreviewImageHeight ? $maxPreviewImageHeight : 200); ?>'>
</a>
<?php endif; ?>
@ -28,23 +28,31 @@
<!-- Show List of all files -->
<hr>
<ul class="files" style="list-style: none; margin: 0;" id="files-<?php echo $this->object->getPrimaryKey(); ?>">
<ul class="files" style="list-style: none; margin: 0;" id="files-<?php echo $object->getPrimaryKey(); ?>">
<?php foreach ($files as $file) : ?>
<?php if ($file->getMimeBaseType() == "image" && $hideImageFileInfo)
continue;
?>
<li class="mime <?php echo HHtml::getMimeIconClassByExtension($file->getExtension()); ?>"><a
<?php
if ($file->getMimeBaseType() == "image" && $hideImageFileInfo)
continue;
?>
<li class="mime <?php echo \humhub\libs\MimeHelper::getMimeIconClassByExtension($file->getExtension()); ?>"><a
href="<?php echo $file->getUrl(); ?>" target="_blank"><span
class="filename"><?php echo Helpers::trimText($file->file_name, 40); ?></span></a>
<span class="time" style="padding-right: 20px;"> - <?php echo Yii::app()->format->formatSize($file->size); ?></span>
<span class="time" style="padding-right: 20px;"> - <?php echo Yii::$app->formatter->asSize($file->size); ?></span>
<?php if ($file->getExtension() == "mp3") : ?>
<!-- Integrate jPlayer -->
<?php $this->widget('ext.jplayer.jplayer', array(
<?php
echo xj\jplayer\AudioWidget::widget(array(
'id' => $file->id,
'file' => $file->getUrl(),
)); ?>
<?php endif;?>
'mediaOptions' => [
'mp3' => $file->getUrl(),
],
'jsOptions' => [
'smoothPlayBar' => true,
]
));
?>
<?php endif; ?>
</li>
<?php endforeach; ?>

View File

@ -12,17 +12,14 @@ use yii\helpers\Url;
<!-- create contenteditable div for HEditorWidget to place the data -->
<div id="post_input_<?php echo $post->id; ?>_contenteditable" class="form-control atwho-input" contenteditable="true"><?php echo \humhub\widgets\RichText::widget(['text' => $post->message]); ?></div>
<?= \humhub\widgets\RichTextEditor::widget(['id'=>'post_input_' . $post->id, 'inputContent'=>$post->message]); ?>
<?= \humhub\widgets\RichTextEditor::widget(['id' => 'post_input_' . $post->id, 'inputContent' => $post->message]); ?>
<?php
// Creates Uploading Button
/*
$this->widget('application.modules_core.file.widgets.FileUploadButtonWidget', array(
'uploaderId' => 'post_upload_' . $post->id,
'object' => $post
));
*
*/
echo humhub\core\file\widgets\FileUploadButton::widget(array(
'uploaderId' => 'post_upload_' . $post->id,
'object' => $post
));
?>
@ -43,14 +40,11 @@ use yii\helpers\Url;
?>
<?php
/*
// Creates a list of already uploaded Files
$this->widget('application.modules_core.file.widgets.FileUploadListWidget', array(
'uploaderId' => 'post_upload_' . $post->id,
'object' => $post
));
*
*/
// Creates a list of already uploaded Files
echo \humhub\core\file\widgets\FileUploadList::widget(array(
'uploaderId' => 'post_upload_' . $post->id,
'object' => $post
));
?>
<?php CActiveForm::end(); ?>

View File

@ -34,6 +34,7 @@ Quick Guide about
- HSetting
- UserModel: CanApproveUsers
- Url Rewriting
- Use AssetBundels
### Bugs

View File

@ -275,52 +275,6 @@ class HHtml extends CHtml
return self::textField($name, $value, $htmlOptions);
}
/**
* Returns Stylesheet Classname based on file extension
*
* @return string CSS Class
*/
public static function getMimeIconClassByExtension($ext)
{
// lowercase string
$ext = strtolower($ext);
// Word
if ($ext == 'doc' || $ext == 'docx') {
return "mime-word";
// Excel
} else if ($ext == 'xls' || $ext == 'xlsx') {
return "mime-excel";
// Powerpoint
} else if ($ext == 'ppt' || $ext == 'pptx') {
return "mime-excel";
// PDF
} else if ($ext == 'pdf') {
return "mime-pdf";
// Archive
} else if ($ext == 'zip' || $ext == 'rar' || $ext == 'tar' || $ext == '7z') {
return "mime-zip";
// Audio
} else if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif') {
return "mime-image";
// Audio
} else if ($ext == 'mp3' || $ext == 'aiff' || $ext == 'wav') {
return "mime-audio";
// Video
} else if ($ext == 'avi' || $ext == 'mp4' || $ext == 'mov' || $ext == 'mpeg' || $ext == 'wma') {
return "mime-video";
// Adobe Photoshop
} else if ($ext == 'psd') {
return "mime-photoshop";
// Adobe Illustrator
} else if ($ext == 'ai') {
return "mime-illustrator";
// other file formats
} else {
return "mime-file";
}
}
}

View File

@ -0,0 +1,66 @@
<?php
/**
* @link https://www.humhub.org/
* @copyright Copyright (c) 2015 HumHub GmbH & Co. KG
* @license https://www.humhub.com/licences
*/
namespace humhub\libs;
/**
* Description of MimeHelper
*
* @author luke
*/
class MimeHelper
{
/**
* Returns Stylesheet Classname based on file extension
*
* @return string CSS Class
*/
public static function getMimeIconClassByExtension($ext)
{
// lowercase string
$ext = strtolower($ext);
// Word
if ($ext == 'doc' || $ext == 'docx') {
return "mime-word";
// Excel
} else if ($ext == 'xls' || $ext == 'xlsx') {
return "mime-excel";
// Powerpoint
} else if ($ext == 'ppt' || $ext == 'pptx') {
return "mime-excel";
// PDF
} else if ($ext == 'pdf') {
return "mime-pdf";
// Archive
} else if ($ext == 'zip' || $ext == 'rar' || $ext == 'tar' || $ext == '7z') {
return "mime-zip";
// Audio
} else if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif') {
return "mime-image";
// Audio
} else if ($ext == 'mp3' || $ext == 'aiff' || $ext == 'wav') {
return "mime-audio";
// Video
} else if ($ext == 'avi' || $ext == 'mp4' || $ext == 'mov' || $ext == 'mpeg' || $ext == 'wma') {
return "mime-video";
// Adobe Photoshop
} else if ($ext == 'psd') {
return "mime-photoshop";
// Adobe Illustrator
} else if ($ext == 'ai') {
return "mime-illustrator";
// other file formats
} else {
return "mime-file";
}
}
}

View File

@ -3,8 +3,8 @@
use yii\helpers\Html;
use yii\helpers\Url;
$this->registerJsFile(Yii::getAlias('@web/resources/at/jquery.caret.min.js'), ['position'=>\yii\web\View::POS_BEGIN]);
$this->registerJsFile(Yii::getAlias('@web/resources/at/jquery.atwho.min.js'), ['position'=>\yii\web\View::POS_BEGIN]);
$this->registerJsFile(Yii::getAlias('@web/resources/at/jquery.caret.min.js'), ['position'=>\yii\web\View::POS_END]);
$this->registerJsFile(Yii::getAlias('@web/resources/at/jquery.atwho.min.js'), ['position'=>\yii\web\View::POS_END]);
$this->registerCssFile(Yii::getAlias('@web/resources/at/jquery.atwho.css'));
?>