KTWorkflowTriggers.inc.php 22.1 KB
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 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
<?php

/**
 * $Id$
 *
 * The contents of this file are subject to the KnowledgeTree Public
 * License Version 1.1.2 ("License"); You may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.knowledgetree.com/KPL
 * 
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
 * See the License for the specific language governing rights and
 * limitations under the License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by KnowledgeTree" logo and
 *    (ii) the KnowledgeTree copyright notice
 * in the same form as they appear in the distribution.  See the License for
 * requirements.
 * 
 * The Original Code is: KnowledgeTree Open Source
 * 
 * The Initial Developer of the Original Code is The Jam Warehouse Software
 * (Pty) Ltd, trading as KnowledgeTree.
 * Portions created by The Jam Warehouse Software (Pty) Ltd are Copyright
 * (C) 2007 The Jam Warehouse Software (Pty) Ltd;
 * All Rights Reserved.
 * Contributor( s): ______________________________________
 *
 */

require_once(KT_LIB_DIR . '/workflow/workflowtrigger.inc.php');

require_once(KT_LIB_DIR . '/permissions/permission.inc.php');
require_once(KT_LIB_DIR . '/permissions/permissionutil.inc.php');

require_once(KT_LIB_DIR . '/groups/GroupUtil.php');

class PermissionGuardTrigger extends KTWorkflowTrigger {
    var $sNamespace = 'ktcore.workflowtriggers.permissionguard';
    var $sFriendlyName;
    var $sDescription;
    var $oTriggerInstance;
    var $aConfig = array();
    
    // generic requirements - both can be true
    var $bIsGuard = true;
    var $bIsAction = false;
    
    function PermissionGuardTrigger() {
        $this->sFriendlyName = _kt('Permission Restrictions');
        $this->sDescription = _kt('Prevents users who do not have the specified permission from using this transition.');
    }
    
    // override the allow transition hook.
    function allowTransition($oDocument, $oUser) {
        if (!$this->isLoaded()) {
            return true;
        }
        // the actual permissions are stored in the array.  
        if (!is_null($this->aConfig['perms']))
        {
        	foreach ($this->aConfig['perms'] as $sPermName) {
            $oPerm = KTPermission::getByName($sPermName);
            if (PEAR::isError($oPerm)) {
                continue; // possible loss of referential integrity, just ignore it for now.
            }
            $res = KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDocument);
            if (!$res) {
                return false;
            }
        }
        }
        return true;
    }
    
    function displayConfiguration($args) {
        // permissions
        $aPermissions = KTPermission::getList();
        $aKeyPermissions = array();
        foreach ($aPermissions as $oPermission) { $aKeyPermissions[$oPermission->getName()] = $oPermission; }
        
        $current_perms = array();
        $this->aConfig['perms'] = KTUtil::arrayGet($this->aConfig, 'perms', array());
        foreach ($this->aConfig['perms'] as $sPermName) {
            $current_perms[$sPermName] = true;
        }

        $oTemplating =& KTTemplating::getSingleton();
		$oTemplate = $oTemplating->loadTemplate('ktcore/workflowtriggers/permissions');
		$aTemplateData = array(
              'context' => $this,
              'perms' => $aKeyPermissions,
              'current_perms' => $current_perms, 
              'args' => $args,
		);
		return $oTemplate->render($aTemplateData);    
    }
    
    function saveConfiguration() {
        $perms = KTUtil::arrayGet($_REQUEST, 'trigger_perms', array());
        if (!is_array($perms)) {
            $perms = (array) $perms;
        }
        $aFinalPerms = array();
        foreach ($perms as $sPermName => $ignore) {
            $oPerm = KTPermission::getByName($sPermName);
            if (!PEAR::isError($oPerm)) {
                $aFinalPerms[] = $sPermName;
            }
        }
        
        $config = array();
        $config['perms'] = $aFinalPerms;
        
        $this->oTriggerInstance->setConfig($config);
        $res = $this->oTriggerInstance->update();
        
        return $res;
    }
    
    function getConfigDescription() {
        if (!$this->isLoaded()) {
            return _kt('This trigger has no configuration.');
        }
        // the actual permissions are stored in the array.
        $perms = array();  
        if (empty($this->aConfig) || is_null($this->aConfig['perms'])) { 
             return _kt('No permissions are required to perform this transition');
        }
        foreach ($this->aConfig['perms'] as $sPermName) {
            $oPerm = KTPermission::getByName($sPermName);
            if (!PEAR::isError($oPerm)) {
                $perms[] = $oPerm->getHumanName();
            }
        }
        if (empty($perms)) {
            return _kt('No permissions are required to perform this transition');
        }
        
        $perm_string = implode(', ', $perms);
        return sprintf(_kt('The following permissions are required: %s'), $perm_string);
    }    
}


class RoleGuardTrigger extends KTWorkflowTrigger {
    var $sNamespace = 'ktcore.workflowtriggers.roleguard';
    var $sFriendlyName;
    var $sDescription;
    var $oTriggerInstance;
    var $aConfig = array();
    
    // generic requirements - both can be true
    var $bIsGuard = true;
    var $bIsAction = false;
    
    function RoleGuardTrigger() {
        $this->sFriendlyName = _kt('Role Restrictions');
        $this->sDescription = _kt('Prevents users who do not have the specified role from using this transition.');
    }
    
    // override the allow transition hook.
    function allowTransition($oDocument, $oUser) {
        if (!$this->isLoaded()) {
            return true;
        }

        $iRoleId = $this->aConfig['role_id'];
        $oRole = Role::get($this->aConfig['role_id']);
        if (PEAR::isError($oRole)) {
            return true; // fail safe for cases where the role is deleted.
        }        

        $bHaveRole = true;
        if ($iRoleId) {
            $bHaveRole = false;
            // handle the magic roles            
            if ($iRoleId == -3) {
                // everyone:  just accept                                    
                $bHaveRole = true; 
            } else if (($iRoleId == -4) && !$oUser->isAnonymous()) {
                // authenticated
                $bHaveRole = true;
            } else {
                $bHaveRole = true;            
                $oRoleAllocation = DocumentRoleAllocation::getAllocationsForDocumentAndRole($oDocument->getId(), $iRoleId);
                if ($oRoleAllocation == null) {   // no role allocation on the doc - check the folder.
                    $oRoleAllocation = RoleAllocation::getAllocationsForFolderAndRole($oDocument->getParentID(), $iRoleId);
                }
                // if that's -also- null                        
                if ($oRoleAllocation == null) {   // no role allocation, no fulfillment.
                    $bHaveRole = false;
                } else if (!$oRoleAllocation->hasMember($oUser)) {
                    $bHaveRole = false;
                }
            }
        }
        
        return $bHaveRole;
    }
    
    function displayConfiguration($args) {
        // permissions
        $aKeyedRoles = array();
        $aRoles = Role::getList();
        foreach ($aRoles as $oRole) { $aKeyedRoles[$oRole->getId()] = $oRole->getName(); }

        $oTemplating =& KTTemplating::getSingleton();
		$oTemplate = $oTemplating->loadTemplate('ktcore/workflowtriggers/roles');
		$aTemplateData = array(
              'context' => $this,
              'roles' => $aKeyedRoles,
              'current_role' => KTUtil::arrayGet($this->aConfig, 'role_id'),
              'args' => $args,
		);
		return $oTemplate->render($aTemplateData);    
    }
    
    function saveConfiguration() {
        $role_id = KTUtil::arrayGet($_REQUEST, 'role_id', null);
        $oRole = Role::get($role_id);
        if (PEAR::isError($oRole)) {
            // silenty ignore
            $role_id = null;
            // $_SESSION['ktErrorMessages'][] = _kt('Unable to use the role you specified.');
        }

        $config = array();
        $config['role_id'] = $role_id;
        
        $this->oTriggerInstance->setConfig($config);
        $res = $this->oTriggerInstance->update();
        
        return $res;
    }
    
    function getConfigDescription() {
        if (!$this->isLoaded()) {
            return _kt('This trigger has no configuration.');
        }
        // the actual permissions are stored in the array.
        $perms = array();  
        if (empty($this->aConfig) || is_null($this->aConfig['role_id'])) { 
             return _kt('No role is required to perform this transition');
        }
        $oRole = Role::get($this->aConfig['role_id']);
        if (PEAR::isError($oRole)) {
            return _kt('The role required for this trigger has been deleted, so anyone can perform this action.');
        } else {
            return sprintf(_kt('The user will require the <strong>%s</strong> role.'), htmlentities($oRole->getName(), ENT_NOQUOTES, 'UTF-8'));
        }
    }    
}


class GroupGuardTrigger extends KTWorkflowTrigger {
    var $sNamespace = 'ktcore.workflowtriggers.groupguard';
    var $sFriendlyName;
    var $sDescription;
    var $oTriggerInstance;
    var $aConfig = array();
    
    // generic requirements - both can be true
    var $bIsGuard = true;
    var $bIsAction = false;
    
    function GroupGuardTrigger() {
        $this->sFriendlyName = _kt('Group Restrictions');
        $this->sDescription = _kt('Prevents users who are not members of the specified group from using this transition.');
    }
    
    // override the allow transition hook.
    function allowTransition($oDocument, $oUser) {
        if (!$this->isLoaded()) {
            return true;
        }

        $iGroupId = $this->aConfig['group_id'];
        $oGroup = Group::get($this->aConfig['group_id']);
        if (PEAR::isError($oGroup)) {
            return true; // fail safe for cases where the role is deleted.
        }        
        $res = GroupUtil::getMembershipReason($oUser, $oGroup);
        if (PEAR::isError($res) || empty($res)) { // broken setup, or no reason
            return false;
        } else {
            return true;
        }
    }
    
    function displayConfiguration($args) {
        // permissions
        $aKeyedGroups = array();
        $aGroups = Group::getList();
        foreach ($aGroups as $oGroup) { $aKeyedGroups[$oGroup->getId()] = $oGroup->getName(); }

        $oTemplating =& KTTemplating::getSingleton();
		$oTemplate = $oTemplating->loadTemplate('ktcore/workflowtriggers/group');
		$aTemplateData = array(
              'context' => $this,
              'groups' => $aKeyedGroups,
              'current_group' => KTUtil::arrayGet($this->aConfig, 'group_id'),
              'args' => $args,
		);
		return $oTemplate->render($aTemplateData);    
    }
    
    function saveConfiguration() {
        $group_id = KTUtil::arrayGet($_REQUEST, 'group_id', null);
        $oGroup = Group::get($group_id);
        if (PEAR::isError($oGroup)) {
            // silenty ignore
            $group_id = null;
            // $_SESSION['ktErrorMessages'][] = _kt('Unable to use the group you specified.');
        }

        $config = array();
        $config['group_id'] = $group_id;
        
        $this->oTriggerInstance->setConfig($config);
        $res = $this->oTriggerInstance->update();
        
        return $res;
    }
    
    function getConfigDescription() {
        if (!$this->isLoaded()) {
            return _kt('This trigger has no configuration.');
        }
        // the actual permissions are stored in the array.
        $perms = array();  
        if (empty($this->aConfig) || is_null($this->aConfig['group_id'])) { 
             return _kt('No group is required to perform this transition');
        }
        $oGroup = Group::get($this->aConfig['group_id']);
        if (PEAR::isError($oGroup)) {
            return _kt('The group required for this trigger has been deleted, so anyone can perform this action.');
        } else {
            return sprintf(_kt('The user must be a member of the group "<strong>%s</strong>".'), htmlentities($oGroup->getName(), ENT_NOQUOTES, 'UTF-8'));
        }
    }    
}


class ConditionGuardTrigger extends KTWorkflowTrigger {
    var $sNamespace = 'ktcore.workflowtriggers.conditionguard';
    var $sFriendlyName;
    var $sDescription;
    var $oTriggerInstance;
    var $aConfig = array();
    
    // generic requirements - both can be true
    var $bIsGuard = true;
    var $bIsAction = false;
    
    function ConditionGuardTrigger() {
        $this->sFriendlyName = _kt('Conditional Restrictions');
        $this->sDescription = _kt('Prevents this transition from occuring if the condition specified is not met for the document.');
    }
    
    // override the allow transition hook.
    function allowTransition($oDocument, $oUser) {
        if (!$this->isLoaded()) {
            return true;
        }

        $iConditionId = $this->aConfig['condition_id'];
        $oCondition = KTSavedSearch::get($this->aConfig['condition_id']);
        if (PEAR::isError($oCondition)) {
            return true; // fail safe for cases where the role is deleted.
        }        
        return KTSearchUtil::testConditionOnDocument($iConditionId, $oDocument);
    }
    
    function displayConfiguration($args) {
        // permissions
        $aKeyedConditions = array();
        $aConditions = KTSavedSearch::getConditions();
        foreach ($aConditions as $oCondition) { $aKeyedConditions[$oCondition->getId()] = $oCondition->getName(); }

        $oTemplating =& KTTemplating::getSingleton();
		$oTemplate = $oTemplating->loadTemplate('ktcore/workflowtriggers/condition');
		$aTemplateData = array(
              'context' => $this,
              'conditions' => $aKeyedConditions,
              'current_condition' => KTUtil::arrayGet($this->aConfig, 'condition_id'),
              'args' => $args,
		);
		return $oTemplate->render($aTemplateData);    
    }
    
    function saveConfiguration() {
        $condition_id = KTUtil::arrayGet($_REQUEST, 'condition_id', null);
        $oCondition = KTSavedSearch::get($condition_id);
        if (PEAR::isError($oCondition)) {
            // silenty ignore
            $condition_id = null;
            // $_SESSION['ktErrorMessages'][] = _kt('Unable to use the group you specified.');
        }

        $config = array();
        $config['condition_id'] = $condition_id;
        
        $this->oTriggerInstance->setConfig($config);
        $res = $this->oTriggerInstance->update();
        
        return $res;
    }
    
    function getConfigDescription() {
        if (!$this->isLoaded()) {
            return _kt('This trigger has no configuration.');
        }
        // the actual permissions are stored in the array.
        $perms = array();  
        if (empty($this->aConfig) || is_null($this->aConfig['condition_id'])) { 
             return _kt('No condition must be fulfilled before this transition becomes available.');
        }
        $oCondition = KTSavedSearch::get($this->aConfig['condition_id']);
        if (PEAR::isError($oCondition)) {
            return _kt('The condition required for this trigger has been deleted, so it is always available.');
        } else {
            return sprintf(_kt('The document must match condition "<strong>%s</strong>".'), htmlentities($oCondition->getName(), ENT_NOQUOTES, 'UTF-8'));
        }
    }    
}


class CopyActionTrigger extends KTWorkflowTrigger {
    var $sNamespace = 'ktcore.workflowtriggers.copyaction';
    var $sFriendlyName;
    var $sDescription;
    var $oTriggerInstance;
    var $aConfig = array();
    
    // generic requirements - both can be true
    var $bIsGuard = false;
    var $bIsAction = true;
    
    function CopyActionTrigger() {
        $this->sFriendlyName = _kt('Moves Document');
        $this->sDescription = _kt('Moves the document to another folder.');
    }
   
    // perform more expensive checks -before- performTransition.
    function precheckTransition($oDocument, $oUser) {
        $iFolderId = KTUtil::arrayGet($this->aConfig, 'folder_id');
        $oFolder = Folder::get($iFolderId);
        if (PEAR::isError($oFolder)) { 
            return PEAR::raiseError(_kt('The folder to which this document should be moved does not exist.  Cancelling the transition - please contact a system administrator.')); 
        }
        
        return true;
    }
    
    function performTransition($oDocument, $oUser) {
    
        $iFolderId = KTUtil::arrayGet($this->aConfig, 'folder_id');
        $oToFolder = Folder::get($iFolderId);
        if (PEAR::isError($oFolder)) { 
            return PEAR::raiseError(_kt('The folder to which this document should be moved does not exist.  Cancelling the transition - please contact a system administrator.')); 
        }
        
        return KTDocumentUtil::move($oDocument, $oToFolder, $oUser);
    }
        
    function displayConfiguration($args) {
        $oTemplating =& KTTemplating::getSingleton();
		$oTemplate = $oTemplating->loadTemplate('ktcore/workflowtriggers/moveaction');
		
        require_once(KT_LIB_DIR . '/browse/DocumentCollection.inc.php');
        require_once(KT_LIB_DIR . '/browse/columnregistry.inc.php');
		
        $collection = new AdvancedCollection;       
        $oColumnRegistry = KTColumnRegistry::getSingleton();
        $aColumns = array();
        $aColumns[] = $oColumnRegistry->getColumn('ktcore.columns.singleselection');
        $aColumns[] = $oColumnRegistry->getColumn('ktcore.columns.title');    
        
        $collection->addColumns($aColumns);	
        
        $aOptions = $collection->getEnvironOptions(); // extract data from the environment
        
        
        $qsFrag = array();
        foreach ($args as $k => $v) {
            if ($k == 'action') { $v = 'editactiontrigger'; } // horrible hack - we really need iframe embedding. 
            $qsFrag[] = sprintf('%s=%s',urlencode($k), urlencode($v));
        }
        $qs = implode('&',$qsFrag);
        $aOptions['result_url'] = KTUtil::addQueryStringSelf($qs);                
        $aOptions['show_documents'] = false;
        
        $fFolderId = KTUtil::arrayGet($_REQUEST, 'fFolderId', KTUtil::arrayGet($this->aConfig, 'folder_id', 1));        
        
        $collection->setOptions($aOptions);
        $collection->setQueryObject(new BrowseQuery($fFolderId, $this->oUser));    
        $collection->setColumnOptions('ktcore.columns.singleselection', array(
            'rangename' => 'folder_id',
            'show_folders' => true,
            'show_documents' => false,
        ));	
        
        $collection->setColumnOptions('ktcore.columns.title', array(
            'direct_folder' => false,
            'folder_link' => $aOptions['result_url'],
        ));			
		
		$oFolder = Folder::get($fFolderId);
        $aBreadcrumbs = array();
        $folder_path_names = $oFolder->getPathArray();
        $folder_path_ids = explode(',', $oFolder->getParentFolderIds());
        $folder_path_ids[] = $oFolder->getId();
        if ($folder_path_ids[0] == 0) {
            array_shift($folder_path_ids);
            array_shift($folder_path_names);
        }

        foreach (range(0, count($folder_path_ids) - 1) as $index) {
            $id = $folder_path_ids[$index];
            $qsFrag2 = $qsFrag;
            $qsFrag2[] = sprintf('fFolderId=%d', $id);
            $qs2 = implode('&',$qsFrag2);
            $url = KTUtil::addQueryStringSelf($qs2);              
            $aBreadcrumbs[] = sprintf('<a href="%s">%s</a>', $url, htmlentities($folder_path_names[$index], ENT_NOQUOTES, 'UTF-8'));
        }
		
        $sBreadcrumbs = implode(' &raquo; ', $aBreadcrumbs);		
		
		$aTemplateData = array(
              'context' => $this,
              'breadcrumbs' => $sBreadcrumbs,
              'collection' => $collection,
              'args' => $args,
		);
		return $oTemplate->render($aTemplateData);    
    }
    
    function saveConfiguration() {
        $folder_id = KTUtil::arrayGet($_REQUEST, 'folder_id', null);
        $oFolder = Folder::get($folder_id);
        if (PEAR::isError($oFolder)) {
            // silenty ignore
            $folder_id = null;
        }

        $config = array();
        $config['folder_id'] = $folder_id;
        
        $this->oTriggerInstance->setConfig($config);
        $res = $this->oTriggerInstance->update();
        
        return $res;
    }
    
    function getConfigDescription() {
        if (!$this->isLoaded()) {
            return _kt('This trigger has no configuration.');
        }
        // the actual permissions are stored in the array.
        $perms = array();  
        if (empty($this->aConfig) || is_null($this->aConfig['folder_id'])) { 
             return _kt('<strong>This transition cannot be performed:  no folder has been selected.</strong>');
        }
        $oFolder = Folder::get($this->aConfig['folder_id']);
        if (PEAR::isError($oFolder)) {
            return _kt('<strong>The folder required for this trigger has been deleted, so the transition cannot be performed.</strong>');
        } else {
            return sprintf(_kt('The document will be moved to folder "<a href="%s">%s</a>".'), KTBrowseUtil::getUrlForFolder($oFolder), htmlentities($oFolder->getName(), ENT_NOQUOTES, 'UTF-8'));
        }
    }    
}


class CheckoutGuardTrigger extends KTWorkflowTrigger {
    var $sNamespace = 'ktcore.workflowtriggers.checkoutguard';
    var $sFriendlyName;
    var $sDescription;
    var $oTriggerInstance;
    var $aConfig = array();
    
    // generic requirements - both can be true
    var $bIsGuard = true;
    var $bIsAction = false;
    
    var $bIsConfigurable = false;
    
    function CheckoutGuardTrigger() {
        $this->sFriendlyName = _kt('Checkout Guard');
        $this->sDescription = _kt('Prevents a transition from being followed if the document is checked out..');
    }
    
    // override the allow transition hook.
    function allowTransition($oDocument, $oUser) {
        return (!$oDocument->getIsCheckedOut());
    }
    
    
    function getConfigDescription() {
        return _kt('This transition cannot be performed while the document is checked out.');
    }    
}



?>