BEdita API doc | 4-cactus
  • Class
  • Tree
  • Deprecated
  • Download

Classes

  • 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
  • BePaginatorToolbarHelper
  • BeSchema
  • BeSecurityComponent
  • BeSystem
  • BeSystemComponent
  • BeThumb
  • BeTimeHelper
  • BeToolbarHelper
  • BeTreeComponent
  • BeTreeHelper
  • BeUploadToObjComponent
  • BeurlHelper
  • BeVimeoComponent
  • BeYoutubeComponent
  • BuildFilterBehavior
  • CacheableBehavior
  • CacheShell
  • CallbackBehavior
  • CaptchaComponent
  • Caption
  • CaptionsBehavior
  • Card
  • CardsImportFilter
  • Category
  • CleanupDataTask
  • CleanupTask
  • Comment
  • CommentsController
  • CompactResultBehavior
  • Content
  • CreateIndexFieldsBehavior
  • DataShell
  • DataTransfer
  • DateItem
  • DbadminShell
  • DeleteDependentObjectBehavior
  • DeleteObjectBehavior
  • DeployShell
  • Document
  • DocumentsController
  • DumpModel
  • EditorialContentsShell
  • 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
  • Mask
  • MediaShell
  • MigrateDumpModel
  • 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
  • RedisShell
  • RelationCheck
  • RelationRepair
  • RelationShell
  • RelationStats
  • RemoveDummyNameBehavior
  • ResponseHandlerComponent
  • RestClientModel
  • Revision
  • RevisionObjectBehavior
  • SearchText
  • SearchTextSaveBehavior
  • Section
  • SectionDummy
  • SessionFilterComponent
  • SessionFilterHelper
  • ShortNews
  • SmartyView
  • SoapClientModel
  • SplitterSql
  • StatisticsController
  • Stream
  • StreamLog
  • 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 
<?php
/*-----8<--------------------------------------------------------------------
 *
 * BEdita - a semantic content management framework
 *
 * Copyright 2010 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 Model class
 *
 */
class Module extends BEAppModel {

    /**
     * get a list of module plugin available (plugged and unplugged)
     *
     * @return array ("plugged" => array(), "unplugged" => array() )
     */
    public function getPluginModules() {
        $pluggedModulesList = $this->find('list', array(
                'fields' => array('name', 'id'),
                'conditions' => array('module_type' => array('plugin', 'addon'))
            )
        );

        $pluginModules = array("plugged" => array(), "unplugged" => array());
        if(!file_exists(BEDITA_MODULES_PATH)) {
            throw new BeditaException(__("Missing plugins directory on filesystem", true) . " " . BEDITA_MODULES_PATH);
        }
        App::Import('Core', 'Folder');
        $folder = new Folder(BEDITA_MODULES_PATH);
        $plugins = $folder->read(true, true);
        foreach ($plugins[0] as $plugin) {
            if (file_exists(BEDITA_MODULES_PATH . DS . $plugin . DS . "config" . DS . "bedita_module_setup.php")) {
                include(BEDITA_MODULES_PATH . DS . $plugin . DS . "config" . DS . "bedita_module_setup.php");
                $moduleSetup["pluginPath"] = BEDITA_MODULES_PATH . DS . $plugin;
                if (!array_key_exists($plugin, $pluggedModulesList)) {
                    $moduleSetup["pluginName"] = $plugin;
                    $pluginModules["unplugged"][] = $moduleSetup;
                } else {
                    $mod = $this->find("first", array(
                            "conditions" => array("id" => $pluggedModulesList[$plugin])
                        )
                    );
                    $pluginModules["plugged"][] = array_merge($mod["Module"], array("info" => $moduleSetup));
                }
            }
        }

        return $pluginModules;
    }

    /**
     * plug a module
     * insert module, eventually insert new object types, set modify permission at administrator group
     *
     * @param string $pluginName
     * @param array $setup
     * @return bool
     */
    public function plugModule($pluginName, array& $setup, $pluginPath=null) {
        if (empty($pluginName) || empty($setup)) {
            return false;
        }

        // check BEdita version compatibility
        if (empty($setup["BEditaMinVersion"])) {
            throw new BeditaException(__("Missing minimum BEdita version required to instal module" . " " . $pluginName, true));
        }
        preg_match('/^\d{1,}(\.\d){1,}/', Configure::read('version'), $matches);
        $beditaVersion = $matches[0];
        if ($setup["BEditaMinVersion"] > $beditaVersion) {
            throw new BeditaException(__($pluginName . " " . "require at least BEdita " . $setup["BEditaMinVersion"], true));
        }
        if (!empty($setup["BEditaMaxVersion"]) && $setup["BEditaMaxVersion"] < $beditaVersion) {
            throw new BeditaException(__($pluginName . " " . "is supported up to BEdita " . $setup["BEditaMaxVersion"], true));
        }

        $c = $this->find("count", array(
                "conditions" => array("name" => $pluginName)
            )
        );
        if ($c > 0) {
            throw new BeditaException(__("A module with name " . $pluginName . " already exist", true));
        }

        $data["Module"]["name"] = $pluginName;
        $data["Module"]["label"] = (!empty($setup["publicName"]))? $setup["publicName"] : $pluginName;
        $data["Module"]["url"] = $pluginName;
        $data["Module"]["status"] = "on";
        $data["Module"]["module_type"] = (!empty($setup['type']))? $setup['type'] : 'plugin';
        $data["Module"]["priority"] = $this->field("priority", null, "priority DESC") + 1;
        if (!$this->save($data)) {
            throw new BeditaException(__("error saving module data", true));
        }
        $newModuleId = $this->id;

        if (!empty($setup["BEditaObjects"])) {
            if (!is_array($setup["BEditaObjects"])) {
                $setup["BEditaObjects"] = array($setup["BEditaObjects"]);
            }
            $beLib = BeLib::getInstance();
            $modelPaths = App::path('models');
            $pluginModelsPath = BEDITA_MODULES_PATH . DS  . $pluginName . DS . "models" . DS;
            if (!in_array($pluginModelsPath, $modelPaths)){
                App::build(array("models" => $pluginModelsPath));
            }

            $behaviorPaths = App::path('behaviors');
            $pluginBehaviorsPath = $pluginModelsPath ."behaviors";
            if (!in_array($pluginBehaviorsPath, $behaviorPaths)){
                App::build(array("behaviors" => $pluginBehaviorsPath));
            }

            // check db schema, create tables if needed
            $this->handlePluginSchema($pluginName, $setup, BEDITA_MODULES_PATH);

            $dirPath = BEDITA_MODULES_PATH . DS . $pluginName . DS . "models" . DS;

            $otModel = ClassRegistry::init("ObjectType");
            $ot_id = $otModel->newPluggedId();
            foreach ($setup["BEditaObjects"] as $modelName) {
                $objectType = Inflector::underscore($modelName);
                $filename = $objectType . ".php";
                if (!file_exists($dirPath . $filename)) {
                    throw new BeditaException(__('Model file ' . $filename . ' not found', true));
                }

                if ($beLib->isFileNameUsed($filename, "models", array(BEDITA_MODULES_PATH . DS  . $pluginName . DS . "models" . DS))) {
                    throw new BeditaException(__($filename . " is already used. Please change your file and model name", true));
                }

                if (!$beLib->isBeditaObjectType($modelName, $dirPath)) {
                    throw new BeditaException(__($modelName . " doesn't seem to be a BEdita object. It has to extend BEAppObjectModel", true));
                }

                $obj = $otModel->find("count", array(
                        "conditions" => array("name" => $objectType),
                        "contain" => array()
                    )
                );
                if ($obj == 0) {
                    $model = ClassRegistry::init($pluginName . "." . $modelName);
                    $objectTypeId = (!empty($model->objectTypeId)) ? $model->objectTypeId : null;
                    if(!empty($objectTypeId)) {
                        $obj = $otModel->find("count", array(
                                "conditions" => array("id" => $objectTypeId),
                                "contain" => array()
                            )
                        );
                        if ($obj > 0) {
                            throw new BeditaException(__("objectTypeId " . $objectTypeId . " is already in use: change objectTypeId for model " . $modelName, true));
                        }
                    } else {
                        $objectTypeId = $ot_id++;
                    }
                    $dataO["id"] = $objectTypeId;
                    $dataO["name"] = $objectType;
                    $dataO["module_name"] = $pluginName;
                    if (!$otModel->save($dataO)) {
                        throw new BeditaException(__("error saving objectTypes", true));
                    }
                }
            }
        } else if (!empty($setup["tables"])) {
            $this->handlePluginSchema($pluginName, $setup, BEDITA_MODULES_PATH);
        }

        // set admin permission
        $group_id = ClassRegistry::init("Group")->field("id", array("name" => "administrator"));
        $permMod = ClassRegistry::init("PermissionModule");
        $dataPM["module_id"] = $newModuleId;
        $dataPM["ugid"] = $group_id;
        $dataPM["switch"] = "group";
        $dataPM["flag"] = 3;
        if (!$permMod->save($dataPM)) {
            throw new BeditaException(__("Error saving admin permission", true));
        }

        clearCache(null, 'models');
        clearCache(null, 'persistent');

        // recaching configuration
        BeLib::getObject("BeConfigure")->cacheConfig();

        return true;
    }

    private function createPluginSchema($pluginName, $pluginPath) {
        // load and check schema
        $schemaClass = Inflector::camelize($pluginName). "Schema";
        App::import('Model', 'CakeSchema');
        $schemaPath = $pluginPath . DS  . $pluginName . DS . "config". DS. "sql" . DS;
        $schemaFile = $schemaPath . "schema.php";
        if(!file_exists($schemaFile)) {
            throw new BeditaException(__("Missing schema file", true));
        }
        include($schemaFile);
        return new $schemaClass();
    }

    protected function handlePluginSchema($pluginName, array& $setup, $pluginPath) {
        if(empty($setup["tables"])) {
            return;
        }
        $schemaPath = $pluginPath . DS  . $pluginName . DS . "config". DS. "sql" . DS;

        $pluginSchema = $this->createPluginSchema($pluginName, $pluginPath);
        $pluginTables = $pluginSchema->tables;

        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $currentTables = $db->listSources();

        $beSchema = ClassRegistry::init("BeSchema");

        $found = false;
        $numTablesFound = 0;
        $tabsNotFound = "";
        foreach ($pluginTables as $tabName => $tabData) {
            if(in_array($tabName, $currentTables)) {
                $found = true;
                $numTablesFound++;

                $modelName = Inflector::camelize($tabName);
                $model = ClassRegistry::init($modelName);

                $tableMeta = $beSchema->tableMetaData($model, $db);

                // if fields do not match, error
                ksort($tabData);
                ksort($tableMeta);
                $diff1 = array_diff_key($tabData, $tableMeta);
                $diff2 = array_diff_key($tableMeta, $tabData);
                if(!empty($diff1) || !empty($diff2)) {
                    throw new BeditaException(__('Database schema conflict, table has different schema', true)
                        . ": " . $tabName, array_merge($diff1, $diff2));
                }
                ClassRegistry::removeObject($modelName);

            } else {
                $tabsNotFound .= " '" . $tabName . "'";
            }
        }
        if($found && $numTablesFound < count($pluginTables)) {
            throw new BeditaException(__("Some plugin tables are missing", true) . $tabsNotFound);
        }

        if(!$found) {
            // find sql schema for current driver
            $sqlSchema = $schemaPath . $db->config["driver"] . "_schema.sql";
            if(!file_exists($sqlSchema)) {
                throw new BeditaException(__("Database schema for current driver not found", true) . " [".$db->config["driver"]."]");
            }
            // execute script
            $beSchema->executeQuery($db, $sqlSchema);
            $db->cacheSources = false;
        }
    }


    /**
     * unplug module
     * delete row on modules table, all module objects and object type
     * @param $id
     * @param array $setup
     * @return void
     */
    public function unplugModule($id, array& $setup) {
        $name = $this->field("name", array("id" => $id));
        if (!$this->delete($id)) {
            throw new BeditaException(__("Error deleting module " . $setup["publicName"], true));
        }

        if (!empty($setup["BEditaObjects"])) {
            if (!is_array($setup["BEditaObjects"])) {
                $setup["BEditaObjects"] = array($setup["BEditaObjects"]);
            }
            $otModel = ClassRegistry::init("ObjectType");
            $beObject = ClassRegistry::init("BEObject");
            foreach ($setup["BEditaObjects"] as $modelName) {
                $objectType = Inflector::underscore($modelName);
                $otModel->purgeType($objectType);
            }
        }

        // drop tables
        if (!empty($setup["tables"])) {
            $pluginTables = $setup["tables"];
            foreach (array_reverse($pluginTables) as $t) {
                $q = "DROP TABLE " . $t;
                // #CUSTOM QUERY
                $this->query($q);
            }
        }

        clearCache(null, 'models');
        clearCache(null, 'persistent');

        $pluginPath = BEDITA_MODULES_PATH . DS . $name . DS . "models" . DS;
        $appPaths = App::path('models');
        $res = array_search($pluginPath, $appPaths);
        if($res !== false) {
            unset($appPaths[$res]);
            App::build(array("models" => $appPaths), true);
        }

        // recaching configuration
        BeLib::getObject("BeConfigure")->cacheConfig();
    }

}


?>
BEdita API doc | 4-cactus API documentation generated by ApiGen