Skip to content
Snippets Groups Projects
class_manage_entities_Abstract.php 72.8 KiB
Newer Older
  • Learn to ignore specific revisions
  • <?php
    
    /*
    *    Copyright 2008-2016 Maarch
    *
    *  This file is part of Maarch Framework.
    *
    *   Maarch Framework is free software: you can redistribute it and/or modify
    *   it under the terms of the GNU General Public License as published by
    *   the Free Software Foundation, either version 3 of the License, or
    *   (at your option) any later version.
    *
    *   Maarch Framework 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 Maarch Framework.  If not, see <http://www.gnu.org/licenses/>.
    */
    
    require("modules/entities/entities_tables.php");
    
    
    abstract class entity_Abstract extends functions
    
    {
        /**
        * Form for the management of the entities.
        *
        * @param    string  $mode administrator mode (modification, suspension, authorization, delete)
        * @param    string  $id  entity identifier (empty by default)
        */
        public function formentity($mode, $id = '')
        {
            $core_tools = new core_tools();
            $state = true;
            if($mode == "up")
            {
                $_SESSION['service_tag'] = 'entity_up';
                echo '<h1><i class="fa fa-sitemap fa-2x"></i> '._ENTITY_MODIFICATION.'</h1>';
                if(empty($_SESSION['error']))
                {
                    $db = new Database();
                    $stmt = $db->query('select * from '.ENT_ENTITIES." where entity_id = ?",array(trim($id)));
                    if($stmt->rowCount() == 0)
                    {
                        $_SESSION['error'] = _ENTITY_MISSING;
                        $state = false;
                    }
                    else
                    {
                        $_SESSION['m_admin']['entity']['entityId'] = functions::show_string($id);
                        $line = $stmt->fetchObject();
    
                        $_SESSION['m_admin']['entity']['label']              = functions::show_string($line->entity_label);
                        $_SESSION['m_admin']['entity']['short_label']        = functions::show_string($line->short_label);
                        $_SESSION['m_admin']['entity']['enabled']            = functions::show_string($line->enabled);
                        $_SESSION['m_admin']['entity']['adrs1']              = functions::show_string($line->adrs_1);
                        $_SESSION['m_admin']['entity']['adrs2']              = functions::show_string($line->adrs_2);
                        $_SESSION['m_admin']['entity']['adrs3']              = functions::show_string($line->adrs_3);
                        $_SESSION['m_admin']['entity']['zcode']              = functions::show_string($line->zipcode);
                        $_SESSION['m_admin']['entity']['city']               = functions::show_string($line->city);
                        $_SESSION['m_admin']['entity']['country']            = functions::show_string($line->country);
                        $_SESSION['m_admin']['entity']['email']              = functions::show_string($line->email);
                        $_SESSION['m_admin']['entity']['business']           = functions::show_string($line->business_id);
                        $_SESSION['m_admin']['entity']['parent']             = functions::show_string($line->parent_entity_id);
                        $_SESSION['m_admin']['entity']['type']               = functions::show_string($line->entity_type);
    
                        $_SESSION['m_admin']['entity']['archival_agreement'] = functions::show_string($line->archival_agreement);
    
                        $_SESSION['m_admin']['entity']['archival_agency']    = functions::show_string($line->archival_agency);
    
                    }
                }
                //$core_tools->execute_modules_services($_SESSION['modules_services'], 'entity_up', "include");
                //$core_tools->execute_app_services($_SESSION['app_services'], 'entity_up', 'include');
            }
            elseif($mode == 'add')
            {
                $_SESSION['service_tag'] = 'entity_add';
                echo '<h1><i class="fa fa-sitemap fa-2x"></i> '._ENTITY_ADDITION.'</h1>';
                if($_SESSION['m_admin']['init']== true || !isset($_SESSION['m_admin']['init'] ))
                {
                    //$this->init_session();
                }
                //$core_tools->execute_modules_services($_SESSION['modules_services'], 'entity_add', "include");
                //$core_tools->execute_app_services($_SESSION['app_services'], 'entity_add', 'include');
            }
            $_SESSION['service_tag_form'] = 'formentity';
            $except = array();
            if(isset($_SESSION['m_admin']['entity']['entityId']))
            {
                $except[] = $_SESSION['m_admin']['entity']['entityId'];
            }
            $entities = array();
            if($_SESSION['user']['UserId'] == 'superadmin')
            {
                $entities = $this->getShortEntityTree($entities, 'all', '', $except );
            }
            else
            {
                $entities = $this->getShortEntityTree($entities, $_SESSION['user']['entities'], '' , $except);
            }
            ?>
            <div id="inner_content" class="clearfix">
                <?php
                $core_tools->execute_modules_services($_SESSION['modules_services'], 'formentity', "include");
                $core_tools->execute_app_services($_SESSION['app_services'], 'formentity', 'include');
                if($state == false)
                {
                    $_SESSION['error'] = _ENTITY_UNKNOWN;
                    echo '<div class="error">'.$_SESSION['error'].'</div>';
                }
                else
                {
                    ?>
    
                    <div class="block" style="float:left;width:65%;height:700px;">
    
                    <form name="formentity" id="formentity" method="post" style="width:500px;margin:auto;" action="<?php  if($mode == 'up') { echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=entities&page=entity_up_db'; } elseif($mode == 'add') { echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=entities&page=entity_add_db'; } ?>" class="forms">
                        <input type="hidden" name="display" value="true" />
                        <input type="hidden" name="module" value="entities" />
                        <?php  if($mode == 'up')
                        {?>
                            <input type="hidden" name="page" value="entity_up_db" />
                        <?php }
                        elseif($mode == 'add')
                        {?>
                            <input type="hidden" name="page" value="entity_add_db" />
                        <?php } ?>
                        <input type="hidden" name="order" id="order" value="<?php if(isset($_REQUEST['order'])){ functions::xecho($_REQUEST['order']);}?>" />
                        <input type="hidden" name="order_field" id="order_field" value="<?php if(isset($_REQUEST['order_field'])){ functions::xecho($_REQUEST['order_field']);}?>" />
                        <input type="hidden" name="what" id="what" value="<?php if(isset($_REQUEST['what'])){functions::xecho($_REQUEST['what']);}?>" />
                        <input type="hidden" name="start" id="start" value="<?php if(isset($_REQUEST['start'])){ functions::xecho($_REQUEST['start']);}?>" />
                        <?php
                        if($mode == 'up')
                        {
                            ?>
                            <p style="text-align:right;">
                                <label><?php echo _ID;?> : </label>
                                <input name="entityId" id="entityId" type="text" value="<?php functions::xecho($_SESSION['m_admin']['entity']['entityId']);?>" readonly="readonly" class="readonly" /><span class="red_asterisk"><i class="fa fa-star"></i></span>
                                <input type="hidden"  name="id" value="<?php functions::xecho($id);?>" />
                                <input type="hidden"  name="mode" value="<?php functions::xecho($mode);?>" />
                            </p>
                            <?php
                        }
                        else
                        {
                            ?>
                            <p style="text-align:right;">
                                <label><?php echo _ID;?> : </label>
                                <input name="entityId" id="entityId" type="text" value="<?php if(isset($_SESSION['m_admin']['entity']['entityId'])){ functions::xecho($_SESSION['m_admin']['entity']['entityId']);} ?>" /><span class="red_asterisk"><i class="fa fa-star"></i></span>
                            </p>
                            <?php
                        }
                        ?>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_LABEL;?> : </label>
                            <input name="label"  type="text" id="label" value="<?php if(isset($_SESSION['m_admin']['entity']['label'])){ echo $_SESSION['m_admin']['entity']['label'];} ?>" /><span class="red_asterisk"><i class="fa fa-star"></i></span>
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _SHORT_LABEL;?> : </label>
                            <input name="short_label"  type="text" id="short_label" value="<?php if(isset($_SESSION['m_admin']['entity']['short_label'])){ functions::xecho($_SESSION['m_admin']['entity']['short_label']);} ?>" /><span class="red_asterisk"><i class="fa fa-star"></i></span>
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_ADR_1;?> : </label>
                            <input name="adrs1"  style="margin-right: 7px" type="text" id="adrs1" value="<?php if(isset( $_SESSION['m_admin']['entity']['adrs1'])){functions::xecho($_SESSION['m_admin']['entity']['adrs1']); }?>" />
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_ADR_2;?> : </label>
                            <input name="adrs2"  style="margin-right: 7px" type="text" id="adrs2" value="<?php if(isset($_SESSION['m_admin']['entity']['adrs2'])){ functions::xecho($_SESSION['m_admin']['entity']['adrs2']);} ?>" />
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_ADR_3;?> : </label>
                            <input name="adrs3"  style="margin-right: 7px" type="text" id="adrs3" value="<?php if(isset($_SESSION['m_admin']['entity']['adrs3'])){ functions::xecho($_SESSION['m_admin']['entity']['adrs3']);} ?>" />
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_ZIPCODE;?> : </label>
                            <input name="zcode"  style="margin-right: 7px" type="text" id="zcode" value="<?php if(isset($_SESSION['m_admin']['entity']['zcode'])){ functions::xecho($_SESSION['m_admin']['entity']['zcode']);} ?>" />
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_CITY;?> : </label>
                            <input name="city"  style="margin-right: 7px" type="text" id="city" value="<?php if(isset($_SESSION['m_admin']['entity']['city'])){ functions::xecho($_SESSION['m_admin']['entity']['city']); }?>" />
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_COUNTRY;?> : </label>
                            <input name="country"  style="margin-right: 7px" type="text" id="country" value="<?php if(isset($_SESSION['m_admin']['entity']['country'])){ functions::xecho($_SESSION['m_admin']['entity']['country']);} ?>" />
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_EMAIL;?> : </label>
                            <input name="email"  style="margin-right: 7px" type="text" id="email" value="<?php if(isset($_SESSION['m_admin']['entity']['email'])){ functions::xecho($_SESSION['m_admin']['entity']['email']);} ?>" />
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_BUSINESS;?> : </label>
                            <input name="business"  style="margin-right: 7px" type="text" id="business" value="<?php if(isset($_SESSION['m_admin']['entity']['business'])){ functions::xecho($_SESSION['m_admin']['entity']['business']); }?>" />
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ENTITY_TYPE;
                            require_once('modules'.DIRECTORY_SEPARATOR.'entities'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'class_modules_tools.php');
    
                            $ent = new entities;
    
                            if($_SESSION['user']['UserId'] =="superadmin")
                            {
                                $entity_type = "all";
                            }
                            else
                            {
                                $entity_type = $this->get_entity_type_level($_SESSION['user']['primaryentity']['id']);
                            }
    
                            $typelist = $this->load_entities_types_for_user($entity_type);
                             ?> : </label>
                            <select name="type" id="type">
                                <option value="" ><?php echo _CHOOSE_ENTITY_TYPE;?></option>
                                <?php
                                    for ($i = 0; $i < count($typelist); $i++)
                                    {
                                ?>
                                        <option value="<?php functions::xecho($typelist[$i]['id']);?>" <?php  if (isset($_SESSION['m_admin']['entity']['type']) &&$_SESSION['m_admin']['entity']['type'] == $typelist[$i]['id']){ echo 'selected="selected"'; } ?> ><?php functions::xecho($typelist[$i]['label']);?></option>
                                <?php
                                    }
                                ?>
                            </select><span class="red_asterisk"><i class="fa fa-star"></i></span>
                        </p>
    
                        <p style="text-align:right;">
                            <label><?php echo _ARCHIVAL_AGREEMENT ?> : </label>
                            <input name="archival_agreement" style="margin-right: 7px" type="text" id="archival_agreement" value="<?php if(isset($_SESSION['m_admin']['entity']['archival_agreement'])){ functions::xecho($_SESSION['m_admin']['entity']['archival_agreement']); }?>">
                        </p>
                        <p style="text-align:right;">
                            <label><?php echo _ARCHIVAL_AGENCY ?> : </label>
                            <input name="archival_agency" style="margin-right: 7px" type="text" id="archival_agency" value="<?php if(isset($_SESSION['m_admin']['entity']['archival_agency'])){ functions::xecho($_SESSION['m_admin']['entity']['archival_agency']); }?>">
                        </p>
    
    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
                        <?php
                        $foundParent = false;
                        for ($cptEnt=0; $cptEnt<count($entities);$cptEnt++) {
                            if ($entities[$cptEnt]['ID'] == $_SESSION['m_admin']['entity']['parent']) {
                                $foundParent = true;
                            }
                        }
                        ?>
                        <p>
                            <label for="parent_id"><?php echo _ENTITY_PARENT;?> : </label><br /><br />
                            <select name="parententity"  size="10" style="width:98%;">
                                <option value=""><?php echo _CHOOSE_ENTITY_PARENT;?></option>
                                <?php
                                if (!$foundParent && $_SESSION['m_admin']['entity']['parent'] <> '') {
                                    $stmt = $db->query("select entity_label from entities where entity_id = ?",array(trim($_SESSION['m_admin']['entity']['parent'])));
                                    $resParent = $stmt->fetchObject();
                                    if ($resParent->entity_label <> '') {
                                        $theLabelParent = $resParent->entity_label;
                                    } else {
                                        $theLabelParent = $_SESSION['m_admin']['entity']['parent'];
                                    }
                                    echo '<option style="font-size:14px;font-weight:bold;" ';
                                    echo 'value="' . $_SESSION['m_admin']['entity']['parent'] . '" ';
                                    echo 'selected="selected" >';
                                    echo $theLabelParent . '</option>';
                                }
                                for ($i=0; $i<count($entities);$i++) {
                                    ?>
                                    <option <?php 
                                        if ($entities[$i]['ID'] <> $_SESSION['m_admin']['entity']['entityId']) {
                                            if (isset($_SESSION['m_admin']['entity']['parent']) && $entities[$i]['ID'] == $_SESSION['m_admin']['entity']['parent']) {
                                                echo 'style="font-size:14px;font-weight:bold;"'; 
                                            } ?> value="<?php functions::xecho($entities[$i]['ID']);?>" <?php 
                                            if (isset($_SESSION['m_admin']['entity']['parent']) && $entities[$i]['ID'] == $_SESSION['m_admin']['entity']['parent']) {
                                                echo 'selected="selected"';
                                            } ?> ><?php echo $entities[$i]['LABEL'];?></option><?php
                                        }
                                }
                                ?>
                            </select>
                        </p>
    
                        <p class="buttons" style="text-align:center;">
                            <input type="submit" name="Submit" value="<?php echo _VALIDATE;?>" class="button" />
                            <input type="button" name="cancel" value="<?php echo _CANCEL;?>" class="button"  onclick="javascript:window.top.location.href='<?php echo $_SESSION['config']['businessappurl'];?>index.php?page=manage_entities&amp;module=entities';"/>
                        </p>
                    </form>
                    </div>
                    <?php
                }
            ?>
            </div>
            <?php
        }
    
        /**
        * Checks if an entity has children
        *
        * @param string $id entity identifier
        */
        public function havechild($id)
        {
            $db = new Database();
            $stmt = $db->query('select entity_id from '.ENT_ENTITIES." where parent_entity_id = ?",array(trim($id)));
            if($stmt->rowCount() == 0){ return false; }
            else{ return true; }
        }
    
        /**
        * Checks if an entity is related with a user
        *
        * @param string $id entity identifier
        */
        public function isRelated($id)
        {
            $db = new Database();
            $stmt = $db->query('select ue.entity_id from '.ENT_USERS_ENTITIES." ue, ".$_SESSION['tablename']['users']." u where ue.user_id = u.user_id and ue.entity_id = ?",array(trim($id)));
            if($stmt->rowCount() == 0){ return false; }
            else{ return true; }
        }
    
    
        /**
        * Inits the session variables related to the entities administration.
        */
        public function init_session()
        {
            unset($_SESSION['m_admin']);
        }
    
        /**
        * Returns entity label
        *
        * @param string $entity_id entity selected
        */
        public function getentitylabel($entity_id)
        {
            $labelreturn = false;
    
            $db = new Database();
            $stmt = $db->query("select entity_label from ".ENT_ENTITIES." where entity_id = ?",array(trim($entity_id)));
    
            if($stmt->rowCount() > 0)
            {
                $line = $stmt->fetchObject();
                return $line->entity_label;
            }
            else
            {
                return $labelreturn;
            }
        }
        /**
        * Returns entity label
        *
        * @param string $entity_id entity selected
        */
        public function getentityshortlabel($entity_id)
        {
            $labelreturn = false;
    
            $db = new Database();
            $stmt = $db->query("select short_label from ".ENT_ENTITIES." where entity_id = ?",array(trim($entity_id)));
         
            if($stmt->rowCount() > 0)
            {
                $line = $stmt->fetchObject();
                return $line->short_label;
            }
            else
            {
                return $labelreturn;
            }
        }
    
    
        /**
        * check whether an entity exists and is enabled
        *
        * @param string $entity_id identifier of the entity
        */
        public function isEnabledEntity($entity_id)
        {
            $db = new Database();
            $stmt = $db->query('select entity_id, entity_label, short_label from '.ENT_ENTITIES." where enabled = 'Y' and entity_id = ?",array(trim($entity_id)));
            if($stmt->rowCount() > 0)
            {
                $line = $stmt->fetchObject();
                return $line;
            }
            else
            {
                return false;
            }
        }
    
        /**
        * Gets all children of an entity in an array
        *
        * @param string $parent the root of the tree
        * @param string $selected identifier of the selected entity
        * @param string $tabspace margin of separation of tree's branches
        * @param array  $except array of entity_id ( elements of the tree that should not appear )
        */
    
        public function getEntityChildrenTree($entities, $parent = '', $tabspace = '', $except = array(), $where = '')
        {
            $db = new Database();
            if(trim($parent) == "")
            {
                $stmt = $db->query('select entity_id, entity_label, short_label from '.ENT_ENTITIES." where enabled = 'Y' and (parent_entity_id ='' or parent_entity_id is null) ".$where . " order by short_label, entity_id");
            }
            else
            {
                $stmt = $db->query('select entity_id, entity_label, short_label from '.ENT_ENTITIES." where enabled = 'Y' and parent_entity_id = '".trim($parent)."' ".$where . " order by short_label, entity_id");
            }
           
            if($stmt->rowCount() > 0)
            {
                $espace = $tabspace.'&emsp;';
    
                while($line = $stmt->fetchObject())
                {
                    if (!in_array($line->entity_id, $except))
                    {
                         array_push($entities, array('ID' =>$line->entity_id, 'LABEL' =>  $espace.functions::xssafe($line->entity_label), 'SHORT_LABEL' =>$espace.functions::show_string($line->short_label), 'KEYWORD' => false));
    
                        $db2 = new entity();
                        $db= new Database();
                        $stmt2 = $db->query('select entity_id from '.ENT_ENTITIES." where enabled = 'Y' and parent_entity_id = ?".$where,array(trim($line->entity_id)));
                        $tmp = array();
                        if($stmt2->rowCount() > 0)
                        {
                            $tmp = $db2->getEntityChildrenTree($tmp,$line->entity_id,  $espace, $except);
                            $entities = array_merge($entities, $tmp);
                        }
                    }
                }
            }
            return $entities;
        }
        
        /**
        * Gets all children of an entity in an array
        *
        * @param string $parent the root of the tree
        * @param string $selected identifier of the selected entity
        * @param string $tabspace margin of separation of tree's branches
        * @param array  $except array of entity_id ( elements of the tree that should not appear )
        */
    
        public function getEntityChildrenTreeAdvanced($entities, $parent = '', $tabspace = '', $except = array(), $where = '')
        {   //var_dump($parent);
            //var_dump($where);
            /**
            lorsqu'on passe la variable trim($parent) dans array, la liste déroulante des entités lors d'un enregistrement d'un courrier n'affiche pas tout
            */
    
            $db = new Database();
            if (trim($parent) == "") {
                $stmt = $db->query('select entity_id, entity_label, short_label from ' 
                    . ENT_ENTITIES 
                    . " where enabled = 'Y' and (parent_entity_id ='' or parent_entity_id is null) " . $where . " order by short_label");
            } else {
                $stmt = $db->query('select entity_id, entity_label, short_label from ' 
                . ENT_ENTITIES . " where enabled = 'Y' and parent_entity_id = '" 
                . trim($parent) . "' " . $where . " order by short_label");
            }
       
            //var_dump($stmt->rowCount());
            if ($stmt->rowCount() > 0) {
                $espace = $tabspace.'&emsp;';
                while ($line = $stmt->fetchObject()) {
                    if (!in_array($line->entity_id, $except)) {
                         array_push(
                            $entities, 
                            array(
                                'ID' =>$line->entity_id, 
                                'LABEL' =>  $espace . functions::show_string($line->entity_label),
                                 'SHORT_LABEL' =>$espace . functions::show_string($line->short_label), 
                                 'KEYWORD' => false,
                                 'DISABLED' => false,
                            )
                        );
                    } else {
                        array_push(
                            $entities, 
                            array(
                                'ID' =>$line->entity_id, 
                                'LABEL' =>  $espace . functions::show_string($line->entity_label),
                                 'SHORT_LABEL' =>$espace . functions::show_string($line->short_label), 
                                 'KEYWORD' => false,
                                 'DISABLED' => true,
                            )
                        );
                    }
                    $db2 = new entity();
                    $db = new Database();
                    //var_dump(trim($line->entity_id));
                    $stmt2 = $db->query('select entity_id from ' . ENT_ENTITIES 
                        . " where enabled = 'Y' and parent_entity_id = ? " . $where,array(trim($line->entity_id)));
                    $tmp = array();
                    //var_dump($stmt2->rowCount());
                    if ($stmt2->rowCount() > 0) {
                        //var_dump(trim($line->entity_id));
                        $tmp = $db2->getEntityChildrenTreeAdvanced($tmp,$line->entity_id,  $espace, $except);
                        $entities = array_merge($entities, $tmp);
                    }
                }
            }
            return $entities;
        }
    
    
        /**
        * Gets all entities in an array
        *
        * @param string $parent the root of the tree
        * @param string $selected identifier of the selected entity
        * @param string $tabspace margin of separation of tree's branches
        * @param array  $except array of entity_id ( elements of the tree that should not appear )
        */
        public function getShortEntityTree($entities, $parent = 'all',  $tabspace = '', $except = array(), $entity_type = '', $root=true)
        {
            $tab_entity_type = array();
            $my_tab_entity_type = array();
            $where = '';
            if($entity_type == '')
            {
                if($_SESSION['user']['UserId'] == 'superadmin')
                {
                    $entity_type = "all";
                }
                else
                {
                    $entity_type = $this->get_entity_type_level($_SESSION['user']['primaryentity']['id']);
                }
            }
            $tab_entity_type = $this->load_entities_types_for_user($entity_type);
    
            foreach($tab_entity_type as $theType)
            {
                $my_tab_entity_type[] = "'".$theType['id']."'";
            }
    
            if (count($my_tab_entity_type)>0)
            {
                $where = " and entity_type in(".join(",", $my_tab_entity_type).")";
            }
    
            if(is_array($parent))
            {
                //print_r($parent);
                for ($i=0; $i < count($parent); $i++)
                {
                    $tmp = array();
                    if($entity = $this->isEnabledEntity($parent[$i]['ENTITY_ID']))
                    {
                        if ($root)
                        {
                            array_push($entities, array('ID' =>$parent[$i]['ENTITY_ID'], 'LABEL' => functions::show_string($parent[$i]['ENTITY_LABEL']),'SHORT_LABEL' => functions::show_string($parent[$i]['SHORT_LABEL']), 'KEYWORD' => false));
                        }
    
                        $tmp = $this->getEntityChildrenTree($tmp, $parent[$i]['ENTITY_ID'], $tabspace, $except, $where);
                        $entities = array_merge($entities, $tmp);
                    }
                }
            }
            elseif($parent == 'all')
            {
                $entities = $this->getEntityChildrenTree($entities,'',  $tabspace, $except, $where);
            }
            return $entities;
        }
    
        /**
        * Gets all entities in an array
        *
        * @param string $parent the root of the tree
        * @param string $selected identifier of the selected entity
        * @param string $tabspace margin of separation of tree's branches
        * @param array  $except array of entity_id ( elements of the tree that should not appear )
        */
        public function getShortEntityTreeAdvanced($entities, $parent = 'all',  $tabspace = '', $except = array(), $entity_type = '', $root=true)
        {
            $tab_entity_type = array();
            $my_tab_entity_type = array();
            $where = '';
            if ($entity_type == '') {
                if ($_SESSION['user']['UserId'] == 'superadmin') {
                    $entity_type = "all";
                } else {
                    $entity_type = $this->get_entity_type_level($_SESSION['user']['primaryentity']['id']);
                }
            }
            $tab_entity_type = $this->load_entities_types_for_user($entity_type);
    
            foreach ($tab_entity_type as $theType) {
                $my_tab_entity_type[] = "'".$theType['id']."'";
            }
    
            if (count($my_tab_entity_type)>0) {
                $where = " and entity_type in(" . join(",", $my_tab_entity_type).")";
            }
    
            if (is_array($parent)) {
                //print_r($parent);
                for ($i=0;$i<count($parent);$i++) {
                    $tmp = array();
                    if ($entity = $this->isEnabledEntity($parent[$i]['ENTITY_ID'])) {
                        if ($root) {
                            array_push(
                                $entities, 
                                array(
                                    'ID' =>$parent[$i]['ENTITY_ID'], 'LABEL' => 
                                    $this->show_string($parent[$i]['ENTITY_LABEL']), 
                                    'SHORT_LABEL' => $this->show_string($parent[$i]['SHORT_LABEL']), 
                                    'KEYWORD' => false,
                                    'DISABLED' => false,
                                )
                            );
                        }
                        $tmp = $this->getEntityChildrenTreeAdvanced(
                            $tmp, 
                            $parent[$i]['ENTITY_ID'], 
                            $tabspace, 
                            $except, 
                            $where
                        );
                        $entities = array_merge($entities, $tmp);
                    }
                }
            } elseif ($parent == 'all') {
                $entities = $this->getEntityChildrenTreeAdvanced(
                    $entities,
                    '',  
                    $tabspace, 
                    $except, 
                    $where
                );
            }
            return $entities;
        }
    
    
        /**
        * Get array of identifiers of all entity's children of an entity (that are related to a user)
        *
        * @param string $parent the root of the tree
        */
        public function getTabChildrenId($tab_children_id, $parent = '', $where = '', $immediate_children_only = false)
        {
            //echo "<br>call getTabChildrenId parent : ".$parent."<br>";
            if($immediate_children_only) {
                //echo "immediate_children_only<br>";
            }
            //static $tab_children_id = array();
    
            $db = new Database();
    
            $stmt = $db->query('SELECT entity_id FROM '.ENT_ENTITIES." WHERE parent_entity_id = '".trim($parent)."'".$where);
            //$this->show();
            if($stmt->rowCount() > 0)
            {
                while($line = $stmt->fetchObject())
                {
                    $tab_children_id[] = "'".trim($line->entity_id)."'";
    
                    if($immediate_children_only == false)
                    {
                        $db2 = new entity();
                        $db = new Database();
                        $stmt2 = $db->query('SELECT entity_id FROM '.ENT_ENTITIES." WHERE parent_entity_id = '".trim($line->entity_id)."'".$where);
                        /*echo "<br>";
                        $db2->show();
                        echo "<br>";*/
                        if($stmt2->rowCount() > 0)
                        {
                            $tab_children_id = $db2->getTabChildrenId($tab_children_id, $line->entity_id, $where);
                        }
                    }
                }
            }
            /*echo "<pre>";
            print_r($tab_children_id);
            echo "</pre>";*/
            return $tab_children_id;
        }
    
        /**
        * Get array of identifiers of all entities that are related to a user
        *
        * @param string $parent the root of the tree
        */
        public function get_all_entities_id_user($parent = 'all')
        {
            $tab_entity_type = array();
            $my_tab_entity_type = array();
            $tab_all_id = array();
            $where = '';
    
            if($_SESSION['user']['UserId'] == 'superadmin')
            {
                $entity_type = "all";
            }
            else
            {
                $entity_type = $this->get_entity_type_level($_SESSION['user']['primaryentity']['id']);
            }
    
            $tab_entity_type = $this->load_entities_types_for_user($entity_type);
    
            foreach($tab_entity_type as $theType)
            {
                $my_tab_entity_type[] = "'".$theType['id']."'";
            }
    
            if (count($my_tab_entity_type)>0)
            {
                $where = " and entity_type in(".join(",", $my_tab_entity_type).")";
            }
    
            if(is_array($parent))
            {
                for ($i=0; $i < count($parent); $i++)
                {
                    if($entity = $this->isEnabledEntity($parent[$i]['ENTITY_ID']))
                    {
                        $tab_all_id[] = "'".$entity->entity_id."'";
                        $tabChildren = array();
                        $tab_all_id = array_merge($tab_all_id, $this->getTabChildrenId($tabChildren, $parent[$i]['ENTITY_ID'], $where));
                    }
                }
            }
            elseif($parent == 'all')
            {
                $tabChildren = array();
                $tab_all_id = $this->getTabChildrenId($tabChildren, '', $where);
            }
    
            return $tab_all_id;
        }
    
        /**
        * Get array of identifiers of all entities that are related to a user
        *
        * @param string $parent the root of the tree
        */
        public function get_entities_of_user($user_id,$parent = 'all')
        {
            $entities = array();
            $db = new Database();
            $stmt = $db->query("select e.entity_id,e.entity_label,e.short_label, ue.primary_entity, ue.user_role from ".ENT_ENTITIES." e, ".ENT_USERS_ENTITIES." ue where ue.entity_id = e.entity_id and ue.user_id = ? order by e.entity_label",array(trim($user_id)));
            while($res = $stmt->fetchObject())
            {
                array_push($entities, array('ID' => $res->entity_id, 'LABEL' => $res->entity_label, 'SHORT_LABEL' => $res->short_label,'PRIMARY' => $res->entity_label, 'ROLE' => $res->user_role ));
            }
            return $entities;
        }
    
        /**
        * Allows or denies an entity and its children
        *
        * @param string $id entity identifier
        * @param string $mode ban or allow
        */
        public function allowbanentity($id, $mode)
        {
            static $count = 1;
    
            if($mode == 'ban'){
                $action  = 'N';
                $histKey = 'BAN';
                $histLabel = _ENTITY_SUSPENSION;
                $hist = 'entityban';
                $msgError = _ENTITY_SUSPENDED;
            }
            else{
                $action  = 'Y';
                $histKey = 'VAL';
                $histLabel = _ENTITY_AUTORIZATION;
                $histKeyDetails = 'entityval';
                $msgError = _ENTITY_AUTORIZED;
            }
            $order = $_REQUEST['order'];
            $order_field = $_REQUEST['order_field'];
            $start = $_REQUEST['start'];
            $what = $_REQUEST['what'];
    
            $db = new Database();
            $stmt = $db->query('Update '.ENT_ENTITIES." set enabled = ? where entity_id = ?",array(trim($action),trim($id)));
    
            if($_SESSION['history'][$histKeyDetails] == "true")
            {
                require_once("core".DIRECTORY_SEPARATOR."class".DIRECTORY_SEPARATOR."class_history.php");
                $hist = new history();
                $hist->add(ENT_ENTITIES, $id, $histKey, 'entityup', $histLabel." : ".$id, $_SESSION['config']['databasetype']);
            }
            $db = new Database();
            $stmt = $db->query('select entity_id from '.ENT_ENTITIES." where parent_entity_id = ?",array(trim($id)));
    
            if($stmt->rowCount() > 0)
            {
                while($line = $stmt->fetchObject())
                {
                    $db2 = new entity();
                    $db = new Database();
    
                    $stmt2 = $db->query('Update '.ENT_ENTITIES." set enabled = ? where entity_id = ?",array(trim($action),trim($line->entity_id)));
                    
                    if($_SESSION['history'][$histKeyDetails] == "true")
                    {
                        require_once("core".DIRECTORY_SEPARATOR."class".DIRECTORY_SEPARATOR."class_history.php");
                        $hist = new history();
                        $hist->add(ENT_ENTITIES, $line->entity_id, $histKey, 'entityup', $histLabel." : ".$line->entity_id, $_SESSION['config']['databasetype']);
                    }
    
                    $count++;
                    $db = new Database();
                    $stmt2 = $db->query('select entity_id from '.ENT_ENTITIES." where parent_entity_id = ?",array(trim($line->entity_id)));
                    if($stmt2->rowCount() > 0)
                    {
                        $db2->allowbanentity($line->entity_id, $mode);
                    }
                }
            }
            $_SESSION['error'] = $count.' '.$msgError;
        }
    
    
        /**
        * Allow, Denied or Delete an entity in the database
        *
        * @param string $id entity identifier
        * @param string $mode allow, ban or del
        */
        public function adminentity($id, $mode)
        {
            $order = $_REQUEST['order'];
            $order_field = $_REQUEST['order_field'];
            $start = $_REQUEST['start'];
            $what = $_REQUEST['what'];
            if(!empty($_SESSION['error']))
            {
                ?>
                <script type="text/javascript">window.top.location.href='<?php echo $_SESSION['config']['businessappurl'].'index.php?page=manage_entities&module=entities&order='.$order."&order_field=".$order_field."&start=".$start."&what=".$what;?>';</script>
                <?php
                //header('location: '.$_SESSION['config']['businessappurl'].'index.php?page=manage_entities&module=entities&order='.$order."&order_field=".$order_field."&start=".$start."&what=".$what);
                exit();
            }
            else
            {
                $db = new Database();
                $stmt = $db->query('select entity_id from '.ENT_ENTITIES." where entity_id = ?",array(trim($id)));
                if($stmt->rowCount() == 0)
                {
                    $_SESSION['error'] = _ENTITY.' '._UNKNWON;
                    //header('location: '.$_SESSION['config']['businessappurl'].'index.php?page=manage_entities&module=entities&order='.$order."&order_field=".$order_field."&start=".$start."&what=".$what);
                    ?>
                    <script type="text/javascript">window.top.location.href='<?php echo $_SESSION['config']['businessappurl'].'index.php?page=manage_entities&module=entities&order='.$order."&order_field=".$order_field."&start=".$start."&what=".$what;?>';</script>
                    <?php
                    exit;
                }
                else
                {
                    if($mode == 'allow')
                    {
                        $this->allowbanentity($id, $mode);
                    }
                    elseif($mode == 'ban')
                    {
                        $this->allowbanentity($id, $mode);
                    }
                    elseif($mode == 'del' )
                    {
                        if($this->havechild($id))
                        {
                            $_SESSION['error'] = _ENTITY_HAVE_CHILD;
                        }
                        elseif($this->isRelated($id))
                        {
                            $_SESSION['error'] = _ENTITY_IS_RELATED;
                        }
                        else
                        {
                            $stmt = $db->query("delete from ".ENT_ENTITIES." where entity_id = ?",array(trim($id)));
                            if($_SESSION['history']['entitydel'] == "true")
                            {
                                require_once('core'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'class_history.php');
                                $hist = new history();
                                $hist->add(ENT_ENTITIES, $id,'DEL','entitydel', _ENTITY_DELETION." : ".$this->protect_string_db(trim($id)), $_SESSION['config']['databasetype']);
                            }
                            $_SESSION['info'] = $id." "._ENTITY_DELETED;
                        }
                    }
                    //header('location: '.$_SESSION['config']['businessappurl'].'index.php?page=manage_entities&module=entities&order='.$order."&order_field=".$order_field."&start=".$start."&what=".$what);
    
                    ?>
                    <script type="text/javascript">
                        window.top.location.href='<?php echo $_SESSION['config']['businessappurl'].'index.php?page=manage_entities&module=entities&order='.$order."&order_field=".$order_field."&start=".$start."&what=".$what;?>';
                    </script>
                    <?php
                    exit();
                }
            }
        }
    
        /**
        * Treats the information returned by the form of formentity()
        *
        * @param    string  $mode administrator mode (modification, suspension, authorization, delete)
        */
        public function entityinfo($mode)
        {
            //require_once('core'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR..'class_core_tools.php');
            $core = new core_tools();
            if($mode == 'up')
            {
                if(empty($_REQUEST['id']) || !isset($_REQUEST['id']))
                {
                    $_SESSION['error'].= _ID_MISSING."<br/>";
                }
                else
                {
                    $_SESSION['m_admin']['entity']['entityId']  = functions::wash($_REQUEST['id'], "alphanum", _THE_ID, 'yes', 0, 32);
                }
            }
    
            if($mode == 'add')
            {
                if(empty($_REQUEST['entityId']) || !isset($_REQUEST['entityId']))
                {
                    $_SESSION['error'].= _ID_MISSING."<br/>";
                }
                else
                {
                    $_SESSION['m_admin']['entity']['entityId']  = functions::wash($_REQUEST['entityId'], "alphanum", _THE_ID, 'yes', 0, 32);
                }
            }
            $_SESSION['m_admin']['entity']['mode'] = $mode;
            if(isset($_REQUEST['label']) && !empty($_REQUEST['label']))
            {
                $_SESSION['m_admin']['entity']['label'] = functions::wash($_REQUEST['label'], "no", _ENTITY_LABEL, 'yes', 0, 255);
            }
            else
            {
                $_SESSION['error'].= _LABEL_MISSING."<br/>";
            }
            if(isset($_REQUEST['short_label']) && !empty($_REQUEST['short_label']))
            {
                $_SESSION['m_admin']['entity']['short_label'] = functions::wash(utf8_decode($_REQUEST['short_label']), "no", _SHORT_LABEL, 'yes', 0, 50);
                $_SESSION['m_admin']['entity']['short_label'] = utf8_encode($_SESSION['m_admin']['entity']['short_label']);
            }
            else
            {
                $_SESSION['error'].= _SHORT_LABEL_MISSING."<br/>";
            }
            $_SESSION['m_admin']['entity']['adrs1'] = '';
            if(isset($_REQUEST['adrs1']) && !empty($_REQUEST['adrs1']))
            {
                $_SESSION['m_admin']['entity']['adrs1'] = functions::wash($_REQUEST['adrs1'], "no", _ENTITY_ADR_1, 'yes', 0, 255);
            }
            $_SESSION['m_admin']['entity']['adrs2'] = '';
            if(isset($_REQUEST['adrs2']) && !empty($_REQUEST['adrs2']))
            {
                $_SESSION['m_admin']['entity']['adrs2'] = functions::wash($_REQUEST['adrs2'], "no", _ENTITY_ADR_2, 'yes', 0, 255);
            }
            $_SESSION['m_admin']['entity']['adrs3'] = '';
            if(isset($_REQUEST['adrs3']) && !empty($_REQUEST['adrs3']))
            {
                $_SESSION['m_admin']['entity']['adrs3'] = functions::wash($_REQUEST['adrs3'], "no", _ENTITY_ADR_3, 'yes', 0, 255);
            }
            $_SESSION['m_admin']['entity']['zcode'] = '';
            if(isset($_REQUEST['zcode']) && !empty($_REQUEST['zcode']))
            {
                $_SESSION['m_admin']['entity']['zcode'] = functions::wash($_REQUEST['zcode'], "no", _ENTITY_ZIPCODE, 'yes', 0, 32);
            }
             $_SESSION['m_admin']['entity']['city'] = '';
            if(isset($_REQUEST['city']) && !empty($_REQUEST['city']))
            {
                $_SESSION['m_admin']['entity']['city'] =  functions::wash($_REQUEST['city'], "no", _ENTITY_CITY, 'yes', 0, 255);
            }
            $_SESSION['m_admin']['entity']['country'] = '';
            if(isset($_REQUEST['country']) && !empty($_REQUEST['country']))
            {
                $_SESSION['m_admin']['entity']['country'] = functions::wash($_REQUEST['country'], "no", _ENTITY_COUNTRY, 'yes', 0, 255);
            }
            $_SESSION['m_admin']['entity']['email'] = '';
            if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
            {
                $_SESSION['m_admin']['entity']['email'] = functions::wash($_REQUEST['email'], "mail", _ENTITY_EMAIL, 'yes', 0, 255);
            }
    
            $_SESSION['m_admin']['entity']['archival_agreement'] = '';
            if(isset($_REQUEST['archival_agreement']) && !empty($_REQUEST['archival_agreement']))
            {
                $_SESSION['m_admin']['entity']['archival_agreement'] = functions::wash($_REQUEST['archival_agreement'], "no", _ARCHIVAL_AGREEMENT, 'yes', 0, 255);
            }
            $_SESSION['m_admin']['entity']['archival_agency'] = '';
            if(isset($_REQUEST['archival_agency']) && !empty($_REQUEST['archival_agency']))
            {
                $_SESSION['m_admin']['entity']['archival_agency'] = functions::wash($_REQUEST['archival_agency'], "no", _ARCHIVAL_AGENCY, 'yes', 0, 255);
            }
    
            $_SESSION['m_admin']['entity']['business'] = '';
            if(isset($_REQUEST['business']) && !empty($_REQUEST['business']))
            {
                $_SESSION['m_admin']['entity']['business'] = functions::wash($_REQUEST['business'], "no", _ENTITY_BUSINESS, 'yes', 0, 32);
            }
    
            if(isset($_REQUEST['type']) && !empty($_REQUEST['type']))
            {
                $_SESSION['m_admin']['entity']['type'] =  functions::wash($_REQUEST['type'], "no", _ENTITY_TYPE, 'yes', 0, 64);
            }
            else
            {