manageBranding.php 40.8 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 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
<?php
/**
 * $Id$
 *
 * KnowledgeTree Community Edition
 * Document Management Made Simple
 * Copyright (C) 2008, 2009, 2010 KnowledgeTree Inc.
 * 
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * You can contact KnowledgeTree Inc., PO Box 7775 #87847, San Francisco, 
 * California 94120-7775, or email info@knowledgetree.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * KnowledgeTree" logo and retain the original copyright notice. If the display of the 
 * logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices
 * must display the words "Powered by KnowledgeTree" and retain the original 
 * copyright notice.
 * Contributor( s): ______________________________________
 */

require_once(KT_LIB_DIR . '/dispatcher.inc.php');
require_once(KT_LIB_DIR . '/templating/templating.inc.php');
require_once(KT_LIB_DIR . '/browse/columnregistry.inc.php');
require_once(KT_LIB_DIR . '/widgets/reorderdisplay.inc.php');
require_once(KT_LIB_DIR . '/widgets/fieldWidgets.php');
require_once(KT_LIB_DIR . "/widgets/FieldsetDisplayRegistry.inc.php");
require_once(KT_LIB_DIR . "/widgets/fieldsetDisplay.inc.php");
require_once(KT_LIB_DIR . "/widgets/widgetfactory.inc.php");
require_once(KT_LIB_DIR . "/validation/dispatchervalidation.inc.php");
require_once(KT_LIB_DIR . "/metadata/fieldsetregistry.inc.php");
require_once(KT_LIB_DIR . "/validation/validatorfactory.inc.php");

class ManageBrandDispatcher extends KTAdminDispatcher {

    private $maxLogoWidth = 313;
    private $maxLogoHeight = 50;
    public $supportedTypes = array('gif', 'png', 'pjpeg', 'jpe', 'jpeg', 'jpg', 'jfif', 'jfif-tbnl');
    
    function check() {

        $this->aBreadcrumbs[] = array('url' => $_SERVER['PHP_SELF'], 'name' => _kt('Manage Branding'));
        return parent::check();
    }

    function do_main() {
        $oForms[] = $this->getLogoDetailsForm();
        $oForms[] = $this->getUploadLogoForm();
        
        $oTemplating =& KTTemplating::getSingleton();
        $oTemplate = $oTemplating->loadTemplate('ktcore/branding/list');
        $oTemplate->setData(array(
            'context' => $this,
            'document_types' => $aDocumentTypes,
            'associated_types' => $aAssocDocs,
            'add_fields' => $addFields,
            'oForms' => $oForms,
        ));
        
        return $oTemplate;
    }


    /**
     * Returns the set logo details
     * @return KTForm 
     *
     */

    function getLogoDetailsForm() {
        $this->oPage->setBreadcrumbDetails(_kt("Set Logo Details"));

        $oForm = new KTForm;
        $oForm->setOptions(array(
                    'identifier' => 'ktcore.folder.branding',
                    'label' => _kt('Set Logo Details'),
                    'submit_label' => _kt('Save'),
                    'action' => 'setdetails',
                    'fail_action' => 'main',
                    'encoding' => 'multipart/form-data',
                    'context' => &$this,
                    'extraargs' => $this->meldPersistQuery("","",true),
                    'description' => _kt('You can set the branding details.')
                    ));

        $oWF =& KTWidgetFactory::getSingleton();
        $oVF =& KTValidatorFactory::getSingleton();

        $widgets = array();
        $validators = array();

        $oConfig = KTConfig::getSingleton();
        $logoTitle = $oConfig->get("ui/companyLogoTitle");
        $logoUrl = $oConfig->get("ui/companyLogoUrl");

        // Adding the title widget
        $widgets[] = $oWF->get('ktcore.widgets.string', array(
                    'label' => _kt('Title'),
                    'required' => false,
                    'name' => 'logo_title',
                    'value' => $logoTitle,
                    'description' => _kt("This will appear when hovering over the logo."),
                    ));

        // Adding the url widget
        $widgets[] = $oWF->get('ktcore.widgets.string', array(
                    'label' => _kt('Url'),
                    'required' => false,
                    'name' => 'logo_url',
                    'id' => 'file',
                    'value' => $logoUrl,
                    'description' => _kt("This is the website address you will be redirected to after clicking the logo. The url should include the protocol e.g. http://www.knowledgetree.com . If no protocol is given the url is treated as a relative link."),
                    ));


        // Adding the url widget
        $validators[] = $oVF->get('ktcore.widgets.string', array(
                    'test' => 'logo_url',
                    'output' => 'logo_url',
                    ));
                    
        $oForm->setWidgets($widgets); 
        $oForm->setValidators($validators);

        // TODO: Should electronic signature be implemented for this?
        // Implement an electronic signature for accessing the admin section, it will appear every 10 minutes
        /* //Have to instanciate the oFolder
        global $default;
        $iFolderId = $this->oFolder->getId();
        if($default->enableESignatures){
            $sUrl = KTPluginUtil::getPluginPath('electronic.signatures.plugin', true);
            $heading = _kt('You are attempting to perform a bulk upload');
            $submit['type'] = 'button';
            $submit['onclick'] = "javascript: showSignatureForm('{$sUrl}', '{$heading}', 'ktcore.transactions.bulk_upload', 'bulk', 'bulk_upload_form', 'submit', {$iFolderId});";
        }else{
            $submit['type'] = 'submit';
            $submit['onclick'] = '';
        }
        */

        return $oForm;
    }


    /**
     * Returns the upload logo form
     * @return KTForm 
     *
     */

    function getUploadLogoForm() {
        $this->oPage->setBreadcrumbDetails(_kt("Upload Logo"));

        $oForm = new KTForm;
        $oForm->setOptions(array(
                    'identifier' => 'ktcore.folder.branding',
                    'label' => _kt('Upload Logo'),
                    'submit_label' => _kt('Upload'),
                    'action' => 'upload',
                    'fail_action' => 'main',
                    'encoding' => 'multipart/form-data',
                    'context' => &$this,
                    'extraargs' => $this->meldPersistQuery("","",true),
                    'description' => _kt('You can upload a logo to brand your KnowledgeTree site.')
                    ));

        $oWF =& KTWidgetFactory::getSingleton();

        $widgets = array();
        $validators = array();

        // Adding the File Upload Widget
        $widgets[] = $oWF->get('ktcore.widgets.file', array(
                    'label' => _kt('Logo File'),
                    'required' => false,
                    'name' => 'file',
                    'id' => 'file',
                    'value' => '',
                    'description' => _kt("The logo's dimensions should be 313px width by 50px height. If your logo doesn't fit these dimensions, you can choose to scale it."),
                    ));
        
        //$aVocab['crop'] = 'Crop - Cut out a selection';
        $aVocab['scale'] = 'Scale - Stretch or Shrink to fit';
        $aVocab['nothing'] = 'Don\'t do anything <span class="descriptiveText">(My image has the correct dimensions)</span>';
        
		//Adding document type lookup widget
		$widgets[] = $oWF->get('ktcore.widgets.selection',array(
                    'label' => _kt('Fitting Image'),
				    'id' => 'logo_action',
                    'description' => _kt('How would you like to resize the image?'),
                    'name' => 'resize_method',
                    'vocab' => $aVocab,
                    'selected' => 'crop',
                    'label_method' => 'getName',
                    'simple_select' => true,
		));

        $oForm->setWidgets($widgets); 
        $oForm->setValidators($validators);

        // TODO: Should electronic signature be implemented for this?
        // Implement an electronic signature for accessing the admin section, it will appear every 10 minutes
        /* //Have to instanciate the oFolder
        global $default;
        $iFolderId = $this->oFolder->getId();
        if($default->enableESignatures){
            $sUrl = KTPluginUtil::getPluginPath('electronic.signatures.plugin', true);
            $heading = _kt('You are attempting to perform a bulk upload');
            $submit['type'] = 'button';
            $submit['onclick'] = "javascript: showSignatureForm('{$sUrl}', '{$heading}', 'ktcore.transactions.bulk_upload', 'bulk', 'bulk_upload_form', 'submit', {$iFolderId});";
        }else{
            $submit['type'] = 'submit';
            $submit['onclick'] = '';
        }
        */

        return $oForm;
    }

    /**
     * Returns the scale logo form
     *
     * This form will display a preview of all the possible sclaled combinations.
     * This includes:
     *
     * Stretched, Top Left Cropped, Proportional Stretch, Proportional Top Left Cropped
     *
     * @return KTForm 
     *
     */

    function getScaleLogoForm($logoItems = array()) {
        $this->oPage->setBreadcrumbDetails(_kt("Scale Logo"));

        $oForm = new KTForm;
        $oForm->setOptions(array(
                    'identifier' => 'ktcore.folder.branding',
                    'label' => _kt('Choose Logo'),
                    'submit_label' => _kt('Select'),
                    'action' => 'selectLogo',
                    'cancel_action' => 'main',
                    'fail_action' => 'main',
                    'encoding' => 'multipart/form-data',
                    'context' => &$this,
                    'extraargs' => $this->meldPersistQuery("","",true),
                    'description' => _kt('Choose a logo by clicking on one of the images')
                    ));

        $oWF =& KTWidgetFactory::getSingleton();

        $widgets = array();
        $validators = array();

        $logoFileName = 'var'.DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR.$logoFileName;

        // Adding the image select widget (User will select the best image)
        $widgets[] = $oWF->get('ktcore.widgets.imageselect', array(
                    'label' => _kt('Logo Preview'),
                    'name' => $logoFileName,
                    'value' => $logoItems,
                    ));

        // Adding the Hidden FileName Input String
        $widgets[] = $oWF->get('ktcore.widgets.hidden', array(
                    'name' => 'kt_imageselect',
                    'value' => $logoItems[0],
                    ));

        $oForm->setWidgets($widgets);
        $oForm->setValidators($validators);

        return $oForm;
    }


    /**
     * Returns the crop logo form
     *
     * This form will assist the user in selecting an area of the image to use as the logo
     * within predefined dimensions required for the logo to fit properly into the page header.
     *
     * @return KTForm 
     *
     */

    function getCropLogoForm($logoFileName = '') {
        $this->oPage->setBreadcrumbDetails(_kt("Crop Logo"));

        $oForm = new KTForm;
        $oForm->setOptions(array(
                    'identifier' => 'ktcore.folder.branding',
                    'name' => 'crop_form',
                    'label' => _kt('Crop Logo'),
                    'submit_label' => _kt('Crop'),
                    'action' => 'crop',
                    'fail_action' => 'main',
                    'encoding' => 'multipart/form-data',
                    'context' => &$this,
                    'extraargs' => $this->meldPersistQuery("","",true),
                    'description' => _kt('Use this facility to ensure that the logo meets the required dimensions for the header.')
                    ));

        $oWF =& KTWidgetFactory::getSingleton();

        $widgets = array();
        $validators = array();

        $logoFile = 'var'.DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR.$logoFileName;
        $ext = end(explode('.', end(explode(DIRECTORY_SEPARATOR, $logoFile))));
        $type = $ext;
        
        $imageWidth = $this->getImageWidth($logoFile, $type);
        $imageHeight = $this->getImageHeight($logoFile, $type);

        if ($imageWidth > $this->maxLogoWidth) {
            $imageWidth = $this->maxLogoWidth;
        }

        if ($imageHeight > $this->maxLogoHeight) {
            $imageHeight = $this->maxLogoHeight;
        }

        // Adding the Image Crop Widget
        $widgets[] = $oWF->get('ktcore.widgets.imagecrop', array(
                    'label' => _kt('Crop Logo'),
                    //'name' => 'Logo',
                    'value' => $logoFile,
                    'init_width' => $imageWidth,
                    'init_height' => $imageHeight,
                    'description' => _kt('To crop an area of the logo, click and drag the resizable rectangle over the image.'),
                    ));

        // Adding the Hidden FileName Input String
        $widgets[] = $oWF->get('ktcore.widgets.hidden', array(
                    'name' => 'logo_file_name',
                    'value' => $logoFileName,
                    ));

        // Adding the Hidden Coordinates X1
        $widgets[] = $oWF->get('ktcore.widgets.hidden', array(
                    'name' => 'crop_x1',
                    'value' => 'x1test',
                    ));

        // Adding the Hidden Coordinates Y1
        $widgets[] = $oWF->get('ktcore.widgets.hidden', array(
                    'name' => 'crop_y1',
                    'value' => '',
                    ));

        // Adding the Hidden Coordinates X2
        $widgets[] = $oWF->get('ktcore.widgets.hidden', array(
                    'name' => 'crop_x2',
                    'value' => '',
                    ));

        // Adding the Hidden Coordinates Y2
        $widgets[] = $oWF->get('ktcore.widgets.hidden', array(
                    'name' => 'crop_y2',
                    'value' => '',
                    ));
                    
        $oForm->setWidgets($widgets);
        $oForm->setValidators($validators);

        return $oForm;
    }

    /**
     * Returns the apply logo form
     *
     * This form will display a preview of the correctly sized logo and prompt the user to apply it.
     *
     * @return KTForm 
     *
     */

    function getApplyLogoForm($logoFileName = '') {
        $this->oPage->setBreadcrumbDetails(_kt("Apply Logo"));

        $oForm = new KTForm;
        $oForm->setOptions(array(
                    'identifier' => 'ktcore.folder.branding',
                    'label' => _kt('Apply Logo'),
                    'submit_label' => _kt('Apply'),
                    'action' => 'apply',
                    'cancel_action' => 'main',
                    'fail_action' => 'main',
                    'encoding' => 'multipart/form-data',
                    'context' => &$this,
                    'extraargs' => $this->meldPersistQuery("","",true),
                    'description' => _kt('Applying the logo will activate it in the header making it visible to all who access this site.')
                    ));

        $oWF =& KTWidgetFactory::getSingleton();

        $widgets = array();
        $validators = array();

        $logoFileName = 'var'.DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR.$logoFileName;

        // Adding the Image Widget
        $widgets[] = $oWF->get('ktcore.widgets.image', array(
                    'label' => _kt('Logo Preview'),
                    'name' => $logoFileName, // title and alt attributes get set to this.
                    'value' => $logoFileName,
                    'width' => $this->maxLogoWidth,
                    'height' => $this->maxLogoHeight,
                    'div_border' => '1px solid #cccccc'
                    ));

        // Adding the Hidden FileName Input String
        $widgets[] = $oWF->get('ktcore.widgets.hidden', array(
                    'name' => 'logo_file_name',
                    'value' => $logoFileName,
                    ));

        $oForm->setWidgets($widgets);
        $oForm->setValidators($validators);

        return $oForm;
    }

    /*
     *  Action responsible for setting the logo details
     *
     */

    function do_setdetails(){
        global $default;

        $config =& KTConfig::getSingleton();
        $logoUrl = $_REQUEST['data']['logo_url'];
        $logoTitle = $_REQUEST['data']['logo_title'];
        
        $aOptions = array('redirect_to' => 'main');

        if ($logoTitle != '') {
            $this->oValidator->validateIllegalCharacters($logoTitle, $aOptions);
        }
        
        if ($config->set('ui/companyLogoUrl', $logoUrl) && $config->set('ui/companyLogoTitle', $logoTitle)) {
            $this->successRedirectTo('main', _kt('Logo fields have been successfully updated.'));
        } else {
            $this->errorRedirectToMain(_kt("Couldn't update logo fields"));
        }

    }

    /*
     *  Action responsible for uploading the logo
     *
     */

    function do_upload(){
        global $default;

		$oForm = $this->getUploadLogoForm();
        $res = $oForm->validate();
        if (!empty($res['errors'])) {
            return $oForm->handleError();
        }
        
        //  Setting up the branding directory, logos will be stored in var/branding/
        $brandDir = $default->varDirectory.DIRECTORY_SEPARATOR.'branding';

		if (stristr(PHP_OS,'WIN')) {
            $brandDir = str_replace('/', '\\', $brandDir);
		}
        
        //if branding dir does not exist, generate one and add an index file to block access
        if (!file_exists($brandDir)) {
        	 mkdir($brandDir, 0755);
        	 touch($brandDir.DIRECTORY_SEPARATOR.'index.html');
        	 file_put_contents($brandDir.DIRECTORY_SEPARATOR.'index.html', 'You do not have permission to access this directory.');
        }

        $logoDir = $brandDir.DIRECTORY_SEPARATOR."logo";
        //if branding dir does not exist, generate one and add an index file to block access
        if (!file_exists($logoDir)) {
        	 mkdir($logoDir, 0755);
        	 touch($logoDir.DIRECTORY_SEPARATOR.'index.html');
        	 file_put_contents($logoDir.DIRECTORY_SEPARATOR.'index.html', 'You do not have permission to access this directory.');
        }

        $logoFileName = $_FILES['_kt_attempt_unique_file']['name'];

        //Changing to logo.jpg (Need to preserve extention as GD requires the exact image type to work)
        $ext = end(explode('.', $logoFileName));

        $type = $_FILES['_kt_attempt_unique_file']['type'];

        //Stage 1 filename based ext check:
        if (!$this->isSupportedExtension($ext)) {
            //If filename based extension isn't supported will try and guess based on mime type
            $default->log->error("Stage 1: Unsupported file type: '".$type."' for file: ':".$_FILES['_kt_attempt_unique_file']['name']."'");
            $ext = $this->getExtension($type);
            
            if (!$this->isSupportedExtension($ext)) {
                $default->log->error("Unsupported file type: '".$type."' for file: ':".$_FILES['_kt_attempt_unique_file']['name']."'");
                $this->errorRedirectToMain("The file you tried to upload is not supported.");
            }
        }
        
        $type = $ext; //GD Methods changed to accept extention as type
        
        $logoFileName = 'logo_tmp_'.md5(Date('ymd-hms')).'.'.$ext; //Fighting the browser cache here
        $logoFile = $logoDir.DIRECTORY_SEPARATOR.$logoFileName;

        // deleting old tmp file
		if (file_exists($logoFile)) {
			@unlink($logoFile);
		}

        //TODO: Test Upload Failure by setting the $logoFile to ''

        if(!move_uploaded_file($_FILES['_kt_attempt_unique_file']['tmp_name'], $logoFile)) {
            $default->log->error("Couldn't upload file from '".$_FILES['_kt_attempt_unique_file']['tmp_name']."' to '$logoFile'");
            $this->errorRedirectToMain("Couldn't upload file");
            exit(0);
        }

        $resizeMethod = $_REQUEST['data']['resize_method'];

        $relDir = 'var'.DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR;

        switch ($resizeMethod) {
        /* //crop was disabled
            case 'crop':
            
                if ($this->isImageCroppable($logoFile, $this->maxLogoWith, $this->maxLogoHeight, $type)) {
    
                    $retForm = $this->getCropLogoForm($logoFileName);
                } else {
                    $_SESSION['KTErrorMessage'][] = _kt("The image was too small to be cropped.");
                    $retForm = $this->getApplyLogoForm($logoFileName);
                }
                
                return $retForm->render();
                */
                
            case 'scale':
            
                $logoFileNameStretched = 'logo_tmp_stretched_'.md5(Date('ymd-hms')).'.'.$ext; //Fighting the browser cache here
                $logoFileStretched = $logoDir.DIRECTORY_SEPARATOR.$logoFileNameStretched;

                $logoFileNameCropped = 'logo_tmp_cropped_'.md5(Date('ymd-hms')).'.'.$ext; //Fighting the browser cache here
                $logoFileCropped = $logoDir.DIRECTORY_SEPARATOR.$logoFileNameCropped;

                $default->log->info($logoFileStretched);
                $default->log->info($logoFileCropped);

                //Creating stretched image                
                $res = $this->scaleImage($logoFile, $logoFileStretched, $this->maxLogoWidth, $this->maxLogoHeight, $type, false, false);

                //Creating top-left cropped image
                $res = $this->scaleImage($logoFile, $logoFileCropped, $this->maxLogoWidth, $this->maxLogoHeight, $type, false, true);
                $res = $this->cropImage($logoFileCropped, $logoFileCropped, 0, 0, $this->maxLogoWidth, $this->maxLogoHeight, $type);

                $logoItem[] = $relDir.$logoFileNameStretched;
                $logoItem[] = $relDir.$logoFileNameCropped;
                
                $form = $this->getScaleLogoForm($logoItem);
                
                $oForms[] = $form;
                $oTemplating =& KTTemplating::getSingleton();
                $oTemplate = $oTemplating->loadTemplate('ktcore/branding/list');
                $oTemplate->setData(array(
                    'context' => $this,
                    'oForms' => $oForms,
                ));
        
                return $oTemplate;
                
            default:
                $form = $this->getApplyLogoForm($logoFileName);

                $oForms[] = $form;
                $oTemplating =& KTTemplating::getSingleton();
                $oTemplate = $oTemplating->loadTemplate('ktcore/branding/list');
                $oTemplate->setData(array(
                    'context' => $this,
                    'oForms' => $oForms,
                ));
        
                return $oTemplate;
        }        

    }

    /**
     * Returns the MIME of the filename, deducted from its extension
     * If the extension is unknown, returns "image/jpeg"
     */
    function getMime($filename)
    {
        $pos = strrpos($filename, '.');
        $extension = "";
        if ($pos !== false) {
            $extension = strtolower(substr($filename, $pos+1));
        }

        switch($extension) {
        case 'gif':
            return 'image/gif';
        case 'jfif':
            return 'image/jpeg';
        case 'jfif-tbnl':
            return 'image/jpeg';
        case 'png':
            return 'image/png';
        case 'jpe':
            return 'image/jpeg';
        case 'jpeg':
            return 'image/jpeg';
        case 'jpg':
            return 'image/jpeg';
        default:
            return 'image/jpeg';
        }
    }


    /**
     * Returns the MIME of the filename, deducted from its extension
     * If the extension is unknown, returns "image/jpeg"
     */
    function getExtension($type)
    {

        switch(strtolower($type)) {
        case 'image/gif':
            return 'gif';
        case 'image/jpeg':
            return 'jfif';
        case 'image/jpeg':
            return 'jfif-tbnl';
        case 'image/png':
            return 'png';
        case 'image/x-png':
            return 'png';
        case 'image/jpeg':
            return 'jpe';
        case 'image/jpeg':
            return 'jpeg';
        case 'image/jpeg':
            return 'jpg';
        case 'image/pjpeg':
            return 'jpg';
        default:
            return 'image/jpeg';
        }
    }


    /**
     * Returns TRUE of the extension is supported
     */
    function isSupportedExtension($extension)
    {
        if (in_array(strtolower($extension), $this->supportedTypes)) {
            return TRUE;
        }
        
        return FALSE;
    }
     
    /*
     *  This method uses the GD library to scale an image.
     *  - Supported images are jpeg, png  and gif
     *
     */
    public function scaleImage( $origFile, $destFile, $width, $height, $type = 'jpg', $scaleUp = false, $keepProportion = true) {
        global $default;
        
        //Requires the GD library if not exit gracefully
        if (!extension_loaded('gd')) {
            $default->log->error("The GD library isn't loaded");
            return false;
        }
        
        switch($type) {
            case 'jpg':
                $orig = imagecreatefromjpeg($origFile);
                break;
            case 'png':
                $orig = imagecreatefrompng($origFile);
                break;
            case 'gif':
                $orig = imagecreatefromgif($origFile);
                break;
            default:
                //Handle Error
                $default->log->error("Tried to crop an unsupported file type: $type");
                return false;
        }

        if($orig) {
            /*
             *  calculate the size of the new image.
             */
            $orig_x = imagesx($orig);
            $orig_y = imagesy($orig);
            
            if (($orig_x < $width) && ($orig_y < $height)) {
                //Image Qualifies for Upscaling
                //If we're not going to scale up then exit here.
                if (!$scaleUp) {
                    return true;
                }
            }
            
            $image_x = $width;
            $image_y = $height;

            //Constraining proportion
            if ($keepProportion) {
                $image_y = round(($orig_y * $image_x) / $orig_x); //Preserve proportion
            }

            /*
             * create the new image, and scale the original into it.
             */
            $image = imagecreatetruecolor($image_x, $image_y);
            imagecopyresampled($image, $orig, 0, 0, 0, 0, $image_x, $image_y, $orig_x, $orig_y);

            switch($type) {
                case 'jpg':
                    imagejpeg($image, $destFile);
                    break;
                case 'png':
                    imagepng($image, $destFile);
                    break;
                case 'gif':
                    imagegif($image, $destFile);
                    break;
                default:
                    //Handle Error
                    $default->log->error("Tried to crop an unsupported file type: $type");
                    return false;
            }

        } else {
            //Handle Error
            $default->log->error("Couldn't obtain a valid GD resource");
            $default->log->error($sourceFile);
            $default->log->error($destFile);
            return false;
        }
        
        return true;
    }


    /*
     *  Action responsible for cropping the logo
     *
     */
    function do_crop(){
        global $default;

        $logoFileName = $_REQUEST['data']['logo_file_name'];
        $logoFile = 'var'.DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR.$logoFileName;

        $ext = end(explode('.', $logoFileName));
        $destFileName = 'logo_tmp_'.md5(Date('ymd-hms')).'.'.$ext;
        $destFile = 'var'.DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR.$destFileName;

        $x1 = $_REQUEST['data']['crop_x1'];
        $y1 = $_REQUEST['data']['crop_y1'];
        
        $x2 = $_REQUEST['data']['crop_x2'];
        $y2 = $_REQUEST['data']['crop_y2'];
        
        $type = $this->getMime($logoFileName);
        
        //GD Crop
        $res = $this->cropImage($logoFile, $destFile, $x1, $y1, $x2, $y2, $type);
        
        //If dimensions don't conform then will scale it further
        $width = $x2 - $x1;
        $height = $y2 - $y1;
        
        if (($width > $this->maxLogoWidth) || ($height > $this->maxLogoHeight)) {
            $default->log->info('SCALING IMAGE AFTER CROP');
            $res = $this->scaleImage($destFile, $destFile, $this->maxLogoWidth, $this->maxLogoHeight, $type, false, false);
        }
        
        // ImageMagick Crop
        /*
        // do generation
        $pathConvert = (!empty($default->convertPath)) ? $default->convertPath : 'convert';
        
        // windows path may contain spaces
        if (stristr(PHP_OS,'WIN')) {
		    $cmd = "\"{$pathConvert}\" \"{$logoFileName}" . $pageNumber . "\" -crop 313x50+110+110 \"$logoFileName\"";
        }
	    else {
		    $cmd = "{$pathConvert} {$logoFileName}" . $pageNumber . " -resize 313x50 $logoFileName";
	    }

	    $result = KTUtil::pexec($cmd);
        */

        $applyLogoForm = $this->getApplyLogoForm($destFileName);
        return $applyLogoForm->render();
        
    }

    /*
     *  This method is used to determine if the image actually can be cropped
     *  - Supported images are jpeg, png  and gif
     *
     */
    public function isImageCroppable( $origFile, $width, $height, $type) {
        global $default;
        
        //Requires the GD library if not exit gracefully
        if (!extension_loaded('gd')) {
            $default->log->error("The GD library isn't loaded");
            return false;
        }
        
        switch($type) {
            case 'jpg':
                $orig = imagecreatefromjpeg($origFile);
                break;
            case 'png':
                $orig = imagecreatefrompng($origFile);
                break;
            case 'gif':
                $orig = imagecreatefromgif($origFile);
                break;
            default:
                //Handle Error
                $default->log->error("Tried to crop an unsupported file type: $type");
                return false;
        }


        if($orig) {
            /*
             *  calculate the size of the new image.
             */
            $orig_x = imagesx($orig);
            $orig_y = imagesy($orig);

            if (($orig_x > $width) || ($orig_y > $height)) {
                return true;
            }
            
        } else {
            //Handle Error
            $default->log->error("Couldn't obtain a valid GD resource $origFile");
            return false;
        }
        
        return true;
    }


    /*
     *  This method uses GD library to return the image width
     *  - Supported images are jpeg, png  and gif     *
     */
    public function getImageWidth( $origFile, $type) {
        global $default;
        
        //Requires the GD library if not exit gracefully
        if (!extension_loaded('gd')) {
            $default->log->error("The GD library isn't loaded");
            return false;
        }
        
        switch($type) {
            case 'jpg':
                $orig = imagecreatefromjpeg($origFile);
                break;
            case 'png':
                $orig = imagecreatefrompng($origFile);
                break;
            case 'gif':
                $orig = imagecreatefromgif($origFile);
                break;
            default:
                //Handle Error
                $default->log->error("Tried to crop an unsupported file type: $type");
                return false;
        }

        if($orig) {
            /*
             *  calculate the size of the new image.             */
            
            $orig_x = imagesx($orig);
            return $orig_x;
            
        } else {
            //Handle Error
            $default->log->error("Couldn't obtain a valid GD resource $origFile");
            return false;
        }
        
        return false;
    }


    /*
     *  This method uses GD library to return the image height
     *  - Supported images are jpeg, png  and gif     *
     */
    public function getImageHeight( $origFile, $type) {
        global $default;
        
        //Requires the GD library if not exit gracefully
        if (!extension_loaded('gd')) {
            $default->log->error("The GD library isn't loaded");
            return false;
        }
        
        switch($type) {
            case 'jpg':
                $orig = imagecreatefromjpeg($origFile);
                break;
            case 'png':
                $orig = imagecreatefrompng($origFile);
                break;
            case 'gif':
                $orig = imagecreatefromgif($origFile);
                break;
            default:
                //Handle Error
                $default->log->error("Tried to crop an unsupported file type: $type");
                return false;
        }

        if($orig) {
            /*
             *  calculate the size of the new image.             */
            
            $orig_y = imagesy($orig);
            return $orig_y;
            
        } else {
            //Handle Error
            $default->log->error("Couldn't obtain a valid GD resource $origFile");
            return false;
        }
        
        return false;
    }


    /*
     *  This method uses the GD library to crop an image.
     *  - Supported images are jpeg, png  and gif
     *
     */
    public function cropImage( $origFile, $destFile, $x1, $y1, $x2, $y2, $type = 'jpg', $scaleUp = true) {
        global $default;

        $width = $x2 - $x1;
        $height = $y2 - $y1;
        
        //Requires the GD library if not exit gracefully
        if (!extension_loaded('gd')) {
            $default->log->error("The GD library isn't loaded");
            return false;
        }
        
        switch($type) {
            case 'jpg':
                $orig = imagecreatefromjpeg($origFile);
                break;
            case 'png':
                $orig = imagecreatefrompng($origFile);
                break;
            case 'gif':
                $orig = imagecreatefromgif($origFile);
                break;
            default:
                //Handle Error
                $default->log->error("Tried to crop an unsupported file type: $type");
                return false;
        }

        if($orig) {
            /*
             * create the new image, and crop it.
             */
            $image = imagecreatetruecolor($width, $height);
            //imagecopyresampled($image, $orig, 0, 0, 0, 0, $image_x, $image_y, $orig_x, $orig_y);

            // Generate the cropped image
            imagecopyresampled($image, $orig, 0, 0, $x1, $y1, $width, $height, $width, $height);
            //imagecopyresized($canvas, $piece, 0,0, $cropLeft, $cropHeight,$newwidth, $newheight, $width, $height);

            switch($type) {
                case 'jpg':
                    imagejpeg($image, $destFile);
                    break;
                case 'png':
                    imagepng($image, $destFile);
                    break;
                case 'gif':
                    imagegif($image, $destFile);
                    break;
                default:
                    //Handle Error
                    $default->log->error("Tried to crop an unsupported file type: $type");
                    return false;
            }


        } else {
            //Handle Error
            $default->log->error("Couldn't obtain a valid GD resource $sourceFile $destFile");
            return false;
        }
        
        return true;
    }


    /*
     *  Action responsible for selecting the logo after it has been scaled.
     *
     */
    function do_selectLogo(){
        global $default;

        if ($_REQUEST['kt_imageselect'] != '') {
            $tmpLogoFileName = end(explode(DIRECTORY_SEPARATOR, $_REQUEST['kt_imageselect']));
        } else {
            $tmpLogoFileName = end(explode(DIRECTORY_SEPARATOR, $_REQUEST['data']['kt_imageselect']));
        }
        
        $form = $this->getApplyLogoForm($tmpLogoFileName);

        $oForms[] = $form;
        $oTemplating =& KTTemplating::getSingleton();
        $oTemplate = $oTemplating->loadTemplate('ktcore/branding/list');
        $oTemplate->setData(array(
            'context' => $this,
            'oForms' => $oForms,
        ));

        return $oTemplate;

    }



    /*
     *  Action responsible for applying the logo
     *
     */
    function do_apply(){
        global $default;

        $rootPath = $default->varDirectory . '/';
        
        $tmpLogoFileName = $_REQUEST['data']['logo_file_name'];
        $tmpLogoFileName = end(explode(DIRECTORY_SEPARATOR, $tmpLogoFileName));
        $tmpLogoFile = $default->varDirectory.DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR.$tmpLogoFileName;

        $ext = end(explode('.', $tmpLogoFileName));
        $logoFileName = 'logo_'.md5(Date('ymd-hms')).'.'.$ext;
        $logoFile = $default->varDirectory.DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR.$logoFileName;

        $logoFileRel = end(explode(DIRECTORY_SEPARATOR, $default->varDirectory)).DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR.$logoFileName;

        // Applying the new logo
        if(!@copy($tmpLogoFile, $logoFile)){
            $default->log->info("Couldn't copy logo ".$tmpLogoFile." to ".$logoFile);
        } else {
            //Cleaning stale files
            $brandDir = $default->varDirectory.DIRECTORY_SEPARATOR.'branding'.DIRECTORY_SEPARATOR.'logo'.DIRECTORY_SEPARATOR;
            $handle = opendir($brandDir);
            while (false !== ($file = readdir($handle))) {
                if (!is_dir($file) && $file != $tmpLogoFileName && $file != $logoFileName) {
                    if (!@unlink($brandDir.$file)) {
                        $default->log->error("Couldn't delete '".$brandDir.$file."'");
                    } else {
                        $default->log->error("Cleaning Brand Logo Dir: Deleted '".$brandDir.$file."'");
                    }                    
                }
            }
        }

        //
        // Updating Config Settings with the new Logo Location
        //
        
        $sql = "SELECT id from config_settings WHERE item = 'companyLogo'";
        $companyLogoId = DBUtil::getOneResultKey($sql,'id');
        if (PEAR::isError($companyLogoId))
        {
            if (PEAR::isError($res)) {
                $default->log->error(sprintf(_kt("Failed to apply logo: %s"), $res->getMessage()));
                $this->errorRedirectToMain(sprintf(_kt("Failed to apply logo: %s"), $res->getMessage()));
                exit();
            }
        }
        
        $res = DBUtil::autoUpdate('config_settings', array('value' => $logoFileRel), $companyLogoId);
        if (PEAR::isError($res)) {
            $default->log->error(sprintf(_kt("Failed to apply logo: %s"), $res->getMessage()));
            $this->errorRedirectToMain(sprintf(_kt("Failed to apply logo: %s"), $res->getMessage()));
            exit();
        }
        
        // Clear the cached settings
        $oKTConfig = new KTConfig();
        $oKTConfig->clearCache();
        
        $this->successRedirectTo('', _kt("Logo succesfully applied."));
    }

}

?>