BEdita API doc | v3.8.0
  • Class
  • Tree
  • Deprecated
  • Download

Classes

  • _emptyAfterFindView
  • Addon
  • AddressbookController
  • AddressbookShell
  • AdminController
  • Alias
  • Annotation
  • ApiAuthComponent
  • ApiBaseController
  • ApiFormatterComponent
  • ApiUploadComponent
  • ApiValidatorComponent
  • AppController
  • AppError
  • AppHelper
  • Application
  • AppModel
  • Area
  • AreasController
  • Audio
  • AuthenticationsController
  • BannedIp
  • BEAppModel
  • BEAppObjectModel
  • BeAuthComponent
  • BeAuthFacebookComponent
  • BeAuthGoogleComponent
  • BeAuthTwitterComponent
  • BeCallbackManager
  • BeConfigure
  • BeCustomPropertyComponent
  • BeditaAnnotationModel
  • BeditaBaseShell
  • BeditaCollectionModel
  • BeditaContentModel
  • BeditaExportFilter
  • BeditaImportFilter
  • BeditaObjectModel
  • BeditaProductModel
  • BeditaShell
  • BeditaSimpleObjectModel
  • BeditaSimpleStreamModel
  • BeditaStreamModel
  • BeEmbedFlashHelper
  • BeEmbedHtml5Helper
  • BeEmbedMediaHelper
  • BeErrorCode
  • BeExceptionHandler
  • BEFile
  • BeFileHandlerComponent
  • BeFormHelper
  • BeFrontHelper
  • BeHashComponent
  • BeHtmlHelper
  • BeLangTextComponent
  • BeLib
  • BeMailComponent
  • BEObject
  • BeObjectCache
  • BeSchema
  • BeSecurityComponent
  • BeSystem
  • BeSystemComponent
  • BeThumb
  • BeTimeHelper
  • BeToolbarHelper
  • BeTreeComponent
  • BeTreeHelper
  • BeUploadToObjComponent
  • BeurlHelper
  • BeVimeoComponent
  • BeYoutubeComponent
  • BuildFilterBehavior
  • CacheableBehavior
  • CacheShell
  • CallbackBehavior
  • CaptchaComponent
  • Card
  • CardsImportFilter
  • Category
  • CleanupTask
  • Comment
  • CommentsController
  • CompactResultBehavior
  • Content
  • CreateIndexFieldsBehavior
  • DataShell
  • DataTransfer
  • DateItem
  • DbadminShell
  • DeleteDependentObjectBehavior
  • DeleteObjectBehavior
  • DeployShell
  • Document
  • DocumentsController
  • DumpModel
  • EditorNote
  • Event
  • EventLog
  • EventsController
  • FilesController
  • ForeignDependenceSaveBehavior
  • FrontendController
  • FrontendShell
  • GalleriesController
  • Gallery
  • GeoTag
  • GettextShell
  • Git
  • GravatarHelper
  • Group
  • HashJob
  • History
  • HomeController
  • Image
  • ImageInfoHelper
  • JsonExportFilter
  • JsonImportFilter
  • JsonView
  • LangText
  • Link
  • MailGroup
  • MailGroupCard
  • MailJob
  • MailLog
  • MailMessage
  • MailShell
  • MailTemplate
  • MediaShell
  • MigrateShell
  • Migration
  • MigrationBase
  • MigrationDateItemsShell
  • Module
  • ModulesController
  • ModuleShell
  • MultimediaController
  • NewsController
  • NewsletterController
  • NewsletterShell
  • NotifyBehavior
  • ObjectEditor
  • ObjectProperty
  • ObjectRelation
  • ObjectType
  • ObjectUser
  • PagesController
  • Permission
  • PermissionModule
  • PermsHelper
  • Product
  • Property
  • PropertyOption
  • PublicationShell
  • RelationShell
  • RemoveDummyNameBehavior
  • ResponseHandlerComponent
  • RestClientModel
  • Revision
  • RevisionObjectBehavior
  • SearchText
  • SearchTextSaveBehavior
  • Section
  • SectionDummy
  • SessionFilterComponent
  • SessionFilterHelper
  • ShortNews
  • SmartyView
  • SoapClientModel
  • SplitterSql
  • StatisticsController
  • Stream
  • StreamsController
  • Svn
  • TagsController
  • ThemeSmartyView
  • ThumbnailHelper
  • ThumbShell
  • TransactionComponent
  • TransactionFS
  • TranslationsController
  • Tree
  • TrHelper
  • User
  • UserProperty
  • UsersController
  • Utility
  • Version
  • Video
  • VimeoHelper
  • WebmarksController
  • XmlExportFilter
  • XmlImportFilter
  • XmlJsonConverter
  • XmlView
  • YoutubeHelper

Interfaces

  • ApiAuthInterface
  • MediaProviderInterface
  • UploadableInterface

Exceptions

  • BeditaAjaxException
  • BEditaAllowURLException
  • BeditaBadRequestException
  • BeditaConflictException
  • BEditaDeleteStreamObjException
  • BeditaException
  • BEditaFileExistException
  • BeditaForbiddenException
  • BeditaFrontAccessException
  • BeditaHashException
  • BEditaInfoException
  • BeditaInternalErrorException
  • BEditaIOException
  • BeditaLengthRequiredException
  • BeditaMailException
  • BEditaMediaProviderException
  • BeditaMethodNotAllowedException
  • BEditaMIMEException
  • BeditaNotFoundException
  • BeditaNotImplementedException
  • BeditaPublicationException
  • BeditaRuntimeException
  • BEditaSaveStreamObjException
  • BeditaServiceUnavailableException
  • BeditaUnauthorizedException
  • BEditaUploadPHPException
  • BEditaURLException
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 
<?php
/*-----8<--------------------------------------------------------------------
 * 
 * BEdita - a semantic content management framework
 * 
 * Copyright 2008-2016 ChannelWeb Srl, Chialab Srl
 * 
 * This file is part of BEdita: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published 
 * by the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 * BEdita is distributed WITHOUT ANY WARRANTY; without even the implied 
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License 
 * version 3 along with BEdita (see LICENSE.LGPL).
 * If not, see <http://gnu.org/licenses/lgpl-3.0.html>.
 * 
 *------------------------------------------------------------------->8-----
 */

/**
 * Module Multimedia: management of Image, Audio, Video objects
 * 
 */
class MultimediaController extends ModulesController {
    var $name = 'Multimedia';

    var $helpers    = array('BeTree', 'BeToolbar', 'ImageInfo');
    var $components = array('BeFileHandler', 'BeUploadToObj', 'BeSecurity');

    // This controller does not use a single model
    var $uses = array('BEObject', 'Application','Stream', 'Image', 'Audio', 'Video', 'Tree', 'User', 'Group','Category','BEFile') ;
    protected $moduleName = 'multimedia';

    function index($id = null, $order = "id", $dir = 0, $page = 1, $dim = 50) {
        $conf  = Configure::getInstance() ;
        $this->setup_args(
            array("id", "integer", &$id),
            array("page", "integer", &$page),
            array("dim", "integer", &$dim),
            array("order", "string", &$order),
            array("dir", "boolean", &$dir)
        ) ;
        $filter["object_type_id"] = array(
            $conf->objectTypes['b_e_file']["id"],
            $conf->objectTypes['image']["id"],
            $conf->objectTypes['audio']["id"],
            $conf->objectTypes['video']["id"],
            $conf->objectTypes['application']["id"]
        );
        
        $filter["count_annotation"] = array("Comment","EditorNote");
        $filter["count_permission"] = true;

        $filter['afterFilter'] = array(
            array(
                'className' => 'ObjectProperty',
                'methodName' => 'objectsCustomProperties'
            ),
            array(
                'className' => 'Stream',
                'methodName' => 'appendStreamFields'
            ),
            array(
                'className' => 'ObjectRelation',
                'methodName' => 'countRelations',
                'options' => array(
                    'relations' => array('attach', 'seealso', 'download')
                )
            ),
            array(
                'className' => 'Tree',
                'methodName' => 'countUbiquity'
            )
        );

        if ($order == 'mediatype') {
            $filter['mediatype'] = 1;
        } else {
            $filter['afterFilter'][] = array(
                'className' => 'Category',
                'methodName' => 'appendMediatype'
            );
        }

        $sessionFilter = $this->SessionFilter->setFromUrl();
        $filter = array_merge($filter, $sessionFilter);
        
        $bedita_items = $this->BeTree->getChildren($id, null, $filter, $order, $dir, $page, $dim)  ;

        $objectRelation = ClassRegistry::init('ObjectRelation');
        $treeModel = ClassRegistry::init("Tree");

        $properties = ClassRegistry::init('Property')->find("all", array(
            "conditions" => array("object_type_id" => $filter["object_type_id"]),
            "contain" => array()
        ));

        $this->params['toolbar'] = &$bedita_items['toolbar'] ;

        // get publications
        $user = $this->BeAuth->getUserSession();
        $expandBranch = array();
        if (!empty($filter['parent_id'])) {
            $expandBranch[] = $filter['parent_id'];
        } elseif (!empty($id)) {
            $expandBranch[] = $id;
        }
        $tree = $treeModel->getAllRoots($user['userid'], null, array('count_permission' => true), $expandBranch);

        // get available relations
        $availableRelations = array();
        foreach ($conf->objectTypes['multimedia']['id'] as $mediaId) {
            $r = $objectRelation->availableRelations($mediaId);
            $availableRelations = array_merge($availableRelations, $r);
        }
        // exclude some kind of relations from view
        $relationsToExclude = array("attach" => "attach","download" => "download","seealso" => "seealso");
        $availableRelations = array_diff_key($availableRelations, $relationsToExclude);

        // get Tags
        $listTags = ClassRegistry::init("Category")->getTags(array("cloud" => false));

        // template data
        $this->set('tree', $tree);
        $this->set('objects', $bedita_items['items']);
        $this->set('properties', $properties);
        $this->set('availableRelations', $availableRelations);
        $this->set('listTags', $listTags);
        $this->setSessionForObjectDetail($bedita_items['items']);

     }

    function view($id = null) {
        $conf  = Configure::getInstance() ;
        $this->setup_args(array("id", "integer", &$id)) ;
        // Get object by $id
        $obj = null ;
        $parents_id = array();
        $name = '';
        if($id) {
            // check if object is forbidden for user
            $user = $this->Session->read("BEAuthUser");
            $permission = ClassRegistry::init("Permission");
            if ($permission->isForbidden($id, $user)) {
                throw new BeditaException(__("Access forbidden to object", true) . " $id");
            }
            $objEditor = ClassRegistry::init("ObjectEditor");
            $objEditor->cleanup($id);
            $model = ClassRegistry::init($this->BEObject->getType($id));
            $name = Inflector::underscore($model->name);
            if (!in_array("multimedia", $model->objectTypesGroups)) {
                throw new BeditaException(__("Error loading object", true));
            }
            $model->containLevel("detailed");
            if(!($obj = $model->findById($id))) {
                 throw new BeditaException(sprintf(__("Error loading object: %d", true), $id));
            }
            if (isset($obj["Category"])) {
                $objCat = array();
                foreach ($obj["Category"] as $oc) {
                    $objCat = $oc["name"];
                }
                $obj["Category"] = $objCat;
            }

            if (!empty($obj['RelatedObject'])) {
                $obj["relations"] = $this->objectRelationArray($obj['RelatedObject']);
            }
            if (!empty($obj['Annotation'])) {
                $this->setupAnnotations($obj);
            }
            unset($obj['Annotation']);

            $imagePath  = $this->BeFileHandler->path($id) ;
            $imageURL   = $this->BeFileHandler->url($id) ;

            $treeModel = ClassRegistry::init("Tree");
            $parents_id = $treeModel->getParents($id) ;

            $previews = $this->previewsForObject($parents_id, $id, $obj['status']);

            $this->historyItem["object_id"] = $id;

            //check if hash is present elsewhere
            if (!empty($obj['hash_file'])) {
                if (empty($obj['uri'])) {
                    //#630 add usr/event msg
                    $this->userErrorMessage(__('Media file expected, hash value is present', true) . ' -  ' . $obj['hash_file']);
                    $this->eventError('multimedia file expected for hash: ' . $obj['hash_file']);
                }
                $results = $this->Image->query("SELECT * FROM streams INNER JOIN objects ON objects.id = streams.id WHERE hash_file='".$obj['hash_file']."'  AND streams.id != ".$obj['id']."");
                $this->set('elsewhere_hash',$results);
            }

            // #536 check local file existence
            if (!empty($obj['uri']) && ($obj['uri'][0] === '/' || $obj['uri'][0] === DS)) {
                $path = Configure::read('mediaRoot') . $obj['uri'];
                if (!file_exists($path)) {
                    $url = Configure::read('mediaUrl') . $obj['uri'];
                    $this->userErrorMessage(__('Media file is missing', true) . ' -  ' . $url);
                    $this->eventError("multimedia missing file: " . $url);
                }
            }

            // #707 check exceeding file size
            if (!empty($obj['file_size']) && $name === 'image' && 
                    ($obj['file_size'] > Configure::read('imgFilesizeLimit'))) {
                $this->userWarnMessage(__('Image file is too big, unable to create thumbnails', true));
            }

            $this->set('objectProperty', $this->BeCustomProperty->setupForView($obj, Configure::read("objectTypes." . $model->name . ".id")));
        } else {
            Configure::write("defaultStatus", "on"); // set default ON for new objects
        }

        $availableRelations = ClassRegistry::init('ObjectRelation')->availableRelations($name);

        // data for template
        $this->set('object',    @$obj);
        $this->set('imagePath', @$imagePath);
        $this->set('imageUrl',  @$imageURL);

        // exclude some kind of relations from view
        $relationsToExclude = array("attach" => "attach","download" => "download","seealso" => "seealso");
        $availableRelations = array_diff_key($availableRelations, $relationsToExclude);

        $this->set('availabeRelations', $availableRelations);

        if(!empty($obj["relations"])) {
            $this->set('relObjects', $obj["relations"]);
        }

        // get publications
        $user = $this->BeAuth->getUserSession();
        $treeModel = ClassRegistry::init("Tree");
        $tree = $treeModel->getAllRoots($user['userid'], null, array('count_permission' => true), $parents_id);

        $this->set('tree', $tree);
        $this->set('parents', $parents_id);
        $this->setSessionForObjectDetail();
     }

    function saveAjax() {
        $this->layout = "ajax";
        try {
            if (!empty($this->params['form']['upload_choice'])) {
                $streamData = $this->Stream->find('first', array(
                    'conditions' => array('id' => $this->params['form']['upload_other_obj_id'])
                ));

                $this->data['uri'] = $streamData['Stream']['uri'];
                $this->data['name'] = $streamData['Stream']['name'];
                $this->data['original_name'] = $streamData['Stream']['original_name'];
                $this->data['mime_type'] = $streamData['Stream']['mime_type'];

                if ($this->params['form']['upload_choice'] == 'new_file_new_obj') {
                    // if it's not a new object then clone original object
                    if (!empty($this->data['id'])) {
                        $this->cloneObject();
                    // else it it's new, save object cloning media attached
                    } else {
                        $this->save(true);
                    }
                } else { // new_file_old_obj
                    $this->BeUploadToObj->cloneMediaObject($this->data, true);
                    $this->save();
                }
            } else {
                $this->set('newObject', empty($this->data['id']));
                $this->save();
            }

            $this->set("redirUrl","/multimedia/view/".$this->Stream->id);

        } catch (BEditaFileExistException $ex) {
            $errTrace = get_class($ex) . " - " . $ex->getMessage()."\nFile: ".$ex->getFile()." - line: ".$ex->getLine()."\nTrace:\n".$ex->getTraceAsString();
            $this->setResult(self::ERROR);
            $this->set("errorFileExist", true);
            $this->set("errorMsg", $ex->getMessage());
            $this->set("objectId", $ex->getObjectId());
            $this->set("objectTitle", $this->BEObject->field("title", array("id" => $ex->getObjectId())));
        } catch(BeditaException $ex) {
            // force header text/plain to haven't javascript error (jQuery undefined) when a file was uploaded
            throw new BeditaAjaxException(
                $ex->getMessage(),
                array(
                    'output' => 'beditaMsg',
                    'headers' => array('Content-Type: text/plain', 'HTTP/1.1 500 Internal Server Error')
                )
            );
        }
    }

    function save($cloneMedia = false) {
        $this->checkWriteModulePermission();
        if(empty($this->data)) {
            throw new BeditaException( __("No data", true));
        }

        $new = (empty($this->data['id'])) ? true : false ;

        if (!$new) {
            $this->checkObjectWritePermission($this->data['id']);
        }

        $this->prepareRelationsToSave();

        // Format custom properties
        $this->BeCustomProperty->setupForSave();

        $this->Transaction->begin() ;
        // save data
        if (!empty($this->params["form"]["tags"])) {
            $this->data["Category"] = $this->Category->saveTagList($this->params["form"]["tags"]);
        }

        if (!empty($this->params['form']['Filedata']['name'])) {
            if(!empty($this->data['url'])) {
                unset($this->data['url']);
            }
            if ($cloneMedia) {
                $this->params['form']['forceupload'] = true;
            }
            $this->Stream->id = $this->BeUploadToObj->upload($this->data);
        } elseif (!empty($this->data['url'])) {
            $this->Stream->id = $this->BeUploadToObj->uploadFromURL($this->data, $cloneMedia);
        } elseif ($cloneMedia) {
            $this->Stream->id = $this->BeUploadToObj->cloneMediaObject($this->data);
        } else {
            if(!empty($this->data['url'])) {
                unset($this->data['url']);
            }
            $model = (!empty($this->data["id"]))? $this->BEObject->getType($this->data["id"]) : "BEFile";

            if ($model == "Video") {
                $this->data["thumbnail"] = $this->BeUploadToObj->getThumbnail($this->data);
            }
            if (!empty($this->params['form']['mediatype'])) {
                $object_type_id = Configure::read("objectTypes." . Inflector::underscore($model) . ".id");
                if (empty($this->data['Category'])) {
                    $this->data['Category'] = array();
                }
                $this->data['Category'] = array_merge($this->data['Category'], $this->Category->checkMediaType($object_type_id, $this->params['form']['mediatype']));
            }

            if (!isset($this->data['Permission'])) {
                $this->data['Permission'] = array();
            }

            if (!$this->{$model}->save($this->data)) {
                throw new BeditaException(__("Error saving multimedia", true), $this->{$model}->validationErrors);
            }
            $this->Stream->id = $this->{$model}->id;
        }

        $this->data['id'] = $this->Stream->id;

        if (isset($this->data['destination'])) {
            if (!$new) {
                $this->BeTree->setupForSave($this->Stream->id, $this->data['destination']);
            }
            ClassRegistry::init('Tree')->updateTree($this->Stream->id, $this->data['destination']);
        }
        $this->Transaction->commit() ;
        $this->userInfoMessage(__("Multimedia object saved", true)." - ".$this->data["title"]);
        $this->eventInfo("multimedia object [". $this->data["title"]."] saved");
    }
    
    public function cloneObject() {
        unset($this->data['id']);
        unset($this->data['nickname']);
        $this->data['status'] = 'draft';
        $this->data['fixed'] = 0;
        $this->save(true);
    }

    function delete() {
        $this->checkWriteModulePermission();
        $objectsListDeleted = $this->deleteObjects("Stream");
        $this->userInfoMessage(__("Multimedia deleted", true) . " -  " . $objectsListDeleted);
        $this->eventInfo("multimedia $objectsListDeleted deleted");
    }

    function deleteSelected() {
        $this->checkWriteModulePermission();
        $objectsListDeleted = $this->deleteObjects("Stream");
        $this->userInfoMessage(__("Multimedia deleted", true) . " -  " . $objectsListDeleted);
        $this->eventInfo("multimedia $objectsListDeleted deleted");
    }

    /**
     * Load multiupload in modal
     * called via ajax
     */
    public function multipleUpload() {
        $this->layout = 'ajax';
    }

    protected function forward($action, $result) {
        $moduleRedirect = array(
            'saveAjax'  =>  array(
                'OK'    => self::VIEW_FWD.'upload_ajax_response',
                'ERROR' => self::VIEW_FWD.'upload_ajax_response'
            )
        );
        return $this->moduleForward($action, $result, $moduleRedirect);
    }

}
BEdita API doc | v3.8.0 API documentation generated by ApiGen